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? Jan 14 '21 at 4:34
  • BTW, function web3.toWei is on web3.js v0.x. On web3.js v1.x, it is function web3.utils.toWei. Jan 14 '21 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
    Jan 14 '21 at 5:02
  • This is the error I received: Please pass numbers as strings or BN objects to avoid precision errors.
    – Wolfizzy
    Jan 14 '21 at 5:03
  • So what part of this error is not clear to you??? Jan 14 '21 at 5:04
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". Jan 14 '21 at 6:12
  • Edited, that was a mistake; I was experimenting with different values after looking it up in the docs.
    – Wolfizzy
    Jan 14 '21 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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