Bitcoin-com / bitbox-sdk

BITBOX SDK for Bitcoin Cash
https://developer.bitcoin.com/bitbox
MIT License
88 stars 62 forks source link

Got [object Object] error in react native when sending BCH #184

Open cshung1994 opened 4 years ago

cshung1994 commented 4 years ago

Here is how I sign and brocast bch tx:

// receiver, sender: cash type address
// mnemonic: 12 words mnemonic code
// amount: (unit BCH)
const transferBch = async (receiver, amount, sender, mnemonic) => {
  const transactionBuilder = new bitbox.TransactionBuilder('mainnet');
  try {
    // Utxo
    const utxo = await bitbox.Address.utxo(sender);
    let balance = 0;
    utxo.utxos.every((item, index) => {
      balance += item.satoshis;
      transactionBuilder.addInput(item.txid, item.vout);
    });
    const amountInSatoshi = bitbox.BitcoinCash.toSatoshi(amount);
    const byteCount = bitbox.BitcoinCash.getByteCount({P2PKH: 1}, {P2PKH: 2});
    const sendAmount = amountInSatoshi - byteCount;
    transactionBuilder.addOutput(receiver, sendAmount);
    // Change
    transactionBuilder.addOutput(sender, balance - sendAmount - byteCount);

    transactionBuilder.setLockTime(50000);
    // Sign
    const seedBuffer = bitbox.Mnemonic.toSeed(mnemonic);
    // create HDNode from seed buffer
    const hdNode = bitbox.HDNode.fromSeed(seedBuffer);
    // keypair
    let keyPair = bitbox.HDNode.toKeyPair(hdNode);
    // empty redeemScript variable
    let redeemScript;
    // sign w/ keyPair
    transactionBuilder.sign(
      0,
      keyPair,
      redeemScript,
      transactionBuilder.hashTypes.SIGHASH_ALL,
      amountInSatoshi,
      // transactionBuilder.signatureAlgorithms.SCHNORR,
    );
    const tx = transactionBuilder.build();
    const hex = tx.toHex();
    // sendRawTransaction to running BCH node
    try {
      const sendRawTransaction = await bitbox.RawTransactions.sendRawTransaction(
        hex,
      );
      console.log(rawTransaction);
    } catch (error) {
      throw new Error(error);
    }
  } catch (error) {
    console.log(error, 'errr');
    throw new Error(error);
  }
};

But I still can't send my bch by following the developer guide and doc