bitcoin core – how can i modify of transfer function

[ad_1]

this is log of my souce code

[
  {
    txid: 'eb31223773c7b86288e16f63ce16d1ed40ca7b308ab612f3d698db87e33de45e',
    vout: 1,
    status: {
      confirmed: true,
      block_height: 790395,
      block_hash: '0000000000000000000481a20c90090f35f5efb9c7633d275ec9bd4a1cc519f7',
      block_time: 1684465824
    },
    value: 546
  },
  {
    txid: 'd3b262afa2fd6242952bfbed7b6fefd07d1225f58e35c330ca5bae21ad71d9d5',
    vout: 0,
    status: {
      confirmed: true,
      block_height: 826653,
      block_hash: '000000000000000000037cddb5c23599063fbc75a4c701dc143a493a9e1c63c0',
      block_time: 1705825641
    },
    value: 10000
  },
  {
    txid: '2429d9ad4f66b8eb0ea240033cd53cc0944e3a8dac32bc291a237145c9ab092d',
    vout: 0,
    status: {
      confirmed: true,
      block_height: 819740,
      block_hash: '00000000000000000003043fcdbf1f554027bfe32339c8184382704c6b39e690',
      block_time: 1701691113
    },
    value: 546
  }
]
Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.
송금 가능. UTXO 합계: 11092
DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface
DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface
DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface
Test Mempool Accept Result: [
  [Object: null prototype] {
    txid: 'e7b368d5ffea7d47039b59b31d5a8e64e6bd8845d697ecb4bdc9bb8889e5c6ac',
    allowed: false,
    'reject-reason': 'missing-inputs'
  }
]
Error fetching or processing UTXOs: bad-txns-inputs-missingorspent

but i don’t know why it can not work and how to fix it..

who know this problem… please fix or explain to this problems..

my souce code is here..

async function transferBitcoin(senderAddress, senderPrivate, recipientAddress, amount) {
    //const network = bitcoin.networks.mainnet;
    //getUTX(senderAddress);
    // Bitcoin Core RPC configuration
    const rpcConfig = {
        username: 'raspibolt',
        password: 'test00000',
        port: 8332,
        host: 'localhost',
        network: 'mainnet',
    };



    // Private key for sending wallet
    const sendingPrivateKeyWIF = senderPrivate;
    const sendingKeyPair = bitcoin.ECPair.fromWIF(sendingPrivateKeyWIF, network);

    // Private key for receiving wallet
    const receivingPrivateKeyWIF = senderPrivate;
    const receivingKeyPair = bitcoin.ECPair.fromWIF(receivingPrivateKeyWIF, network);

    const receivingAddress = bitcoin.payments.p2wpkh({ pubkey: receivingKeyPair.publicKey, network }).address;



    amount = parseInt(btcToSatoshi(amount));
    // Bitcoin Core client
    const client = new BitcoinCore(rpcConfig);

    // Mempool.space API for UTXOs
    const mempoolApi = 'https://mempool.space/api';

    try {
        const response = await axios.get(`${mempoolApi}/address/${senderAddress}/utxo`);
        const utxos = response.data;
        console.log(utxos);

        if (utxos.length === 0) {
            console.error('No UTXOs found. Aborting transaction.');
            return;
        }

        const txb = new bitcoin.TransactionBuilder(network);

        // Iterate through UTXOs
        utxos.forEach((utxo) => {
            txb.addInput(utxo.txid, utxo.vout);
        });

        const outputScript = bitcoin.address.toOutputScript(receivingAddress, network);
        const outputAmount = 5000; // Adjust this based on your needs

        txb.addOutput(outputScript, outputAmount);

        // Calculate fee
        const fee = 1000; // Adjust the fee as needed

        // Calculate total input amount (sum of UTXO values)
        const totalInputAmount = utxos.reduce((total, utxo) => total + utxo.value, 0);
        const totalOutputAmount = outputAmount + fee;

        // 잔고 확인
        if (totalInputAmount < totalOutputAmount) {
        console.error('잔고 부족. 송금 불가능.');
        } else {
        console.log('송금 가능. UTXO 합계:', totalInputAmount);
        }


        // Calculate change amount (total input - output amount - fee)
        const changeAmount = totalInputAmount - outputAmount - fee;

        // Add change output if there's any change
        if (changeAmount > 0) {
            const changeAddress = senderAddress; // Change address is the sender's address in this example
            const changeScript = bitcoin.address.toOutputScript(changeAddress, network);
            txb.addOutput(changeScript, changeAmount);
        }

        // Sign inputs
        utxos.forEach((utxo, index) => {
            txb.sign(index, sendingKeyPair);
        });

        // Build the transaction
        const tx = txb.build();
        const rawTx = tx.toHex();
        const txid = crypto.createHash('sha256').update(Buffer.from(rawTx, 'hex')).digest('hex');

        // Test transaction acceptance in the mempool
        const testResult = await client.testMempoolAccept([rawTx]);

        console.log('Test Mempool Accept Result:', testResult);


        // Broadcast the transaction
        const broadcastResult = await client.sendRawTransaction(rawTx);

        console.log("Transaction broadcasted. Result:", broadcastResult);

    } catch (error) {
        console.error('Error fetching or processing UTXOs:', error.message);
        if (error.response && error.response.data) {
            console.error('Error response data:', error.response.data);
        }
    }

    
}

[ad_2]

Source link

Leave a Comment