I'm calling a withdrawal method from a contract written in solidity from a react.js app using metamask. The transaction is failing and I don't know why. I think is something related to the gas fee because when I change it I get different errors. This is the react code:
contract.methods
.withdrawDividends()
.send({
from: userAddress,
value: availableToWithdraw,
})
.on("transactionHash", function (hash: string) {
console.log(hash);
})
.on(
"confirmation",
function (confirmationNumber: number, receipt: unknown) {
console.log(confirmationNumber);
console.log(receipt);
}
)
.on("receipt", function (receipt: unknown) {
// receipt example
console.log(receipt);
})
.on("error", function (error: unknown, receipt: unknown) {
// If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
console.log(error);
console.log(receipt);
});
This is my solidity method:
function withdrawDividends() public {
User storage user = users[_msgSender()];
uint256 totalAmount = getUserDividends(_msgSender());
require(totalAmount > 0, "User has no dividends");
user.checkpoint = block.timestamp;
(bool success, ) = _msgSender().call.value(totalAmount)("");
require(success, "Transfer failed.");
emit Withdrawn(_msgSender(), totalAmount);
}
The method is not crashing but I see the following error in metamask:
What I'm doing wrong? Is something related to the gas?
If you want your function to accept ETH value, it needs to have the payable
modifier.
In your case:
function withdrawDividends() public payable {
You can read more about the payable
modifier in the docs. It links to the receive
function, which is a slightly different topic. But it also covers the payable
modifier.