0

Problem

I am following this tutorial on how to make a donate button on my React app. The tutorial is in HTML, however, so below is my attempt at converting it to ReactJS.

Code

App.jsx

donate = () => {
  const donationAddress = "0x...";

  web3.eth.sendTransaction({
    to: donationAddress,
    value: web3.utils.toWei("1", "ether")
  }, (err, transactionId) => {
    if (err) {
      console.log("Donation failed", err);
      alert("Donation failed.");
    } else {
      console.log("Donation successful", transactionId);
      alert("Donation successful!");
    }
  })
}

render() {
  return (
    <div>
      <p>Donate</p>
      <button onClick={this.donate}>Donate 1 wei</button>
    </div>
  );
}

I commented out the two lines of code above from the tutorial because I had received this error: TypeError: web3__WEBPACK_IMPORTED_MODULE_3__.default.toWei is not a function.

Output

Initially, I don't receive an error on the page until I click the button. Then I receive this error: The send transactions "from" field must be defined!.

It highlights this line as the error: web3.eth.sendTransaction({.

How do I fix this? Thank you!

10
  • Is there any chance that accounts.length == 0 hence accounts[0] === undefined? Commented Jan 14, 2021 at 4:34
  • BTW, function web3.toWei is on web3.js v0.x. On web3.js v1.x, it is function web3.utils.toWei. Commented Jan 14, 2021 at 4:35
  • @goodvibration, thanks for your second comment, I updated it with utils in it and that error disappeared. However, I did get a different error.
    – Wolfizzy
    Commented Jan 14, 2021 at 5:02
  • This is the error I received: Please pass numbers as strings or BN objects to avoid precision errors.
    – Wolfizzy
    Commented Jan 14, 2021 at 5:03
  • So what part of this error is not clear to you??? Commented Jan 14, 2021 at 5:04

1 Answer 1

0

Updated code. Thanks @goodvibration!

  donate = async () => {
    const donationAddress = "0x...";

    const accounts = await web3.eth.getAccounts();
    this.setState({ account: accounts[0] });

    web3.eth.sendTransaction({
      to: donationAddress,
      from: accounts[0],
      value: web3.utils.toWei("1", "ether")
    }, (err, transactionId) => {
      if (err) {
        console.log("Donation failed", err);
        alert("Donation failed.");
      } else {
        console.log("Donation successful", transactionId);
        alert("Donation successful!");
      }
    })
  }
2
  • What's the point in web3.utils.toWei("1", "wei")? You may as well just use "1". Commented Jan 14, 2021 at 6:12
  • Edited, that was a mistake; I was experimenting with different values after looking it up in the docs.
    – Wolfizzy
    Commented Jan 14, 2021 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.