I am trying to build a smart contract in solidity where the owner of the contract will deploy a contract which will have a fixed reciever's wallet address and a fixed amount of ether(20000000000000000 wei) to be transfered. An investor can transfer the required amount of ether to the reciever's wallet address. The sender can select the wallet from where the ether can be transfered to the receiver.
The owner of the contract will have the ability to change the required amount of wei in contract.
I have tried the following code in Remix IDE, the deployment works but it wont allow me to change the required amount of wei as an owner:
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
contract Wallet {
address payable public receiver; // address of the receiver
uint public requiredWei = 20000000000000000; // amount of wei to be sent (default value)
constructor() {
receiver = payable(xxxxxreceiver's wallet); // replace with receiver's address
}
function sendWei(address payable sender) public payable {
require(msg.value == requiredWei, "Amount of wei sent must be equal to the required amount"); // ensure correct amount of wei is sent
sender.transfer(msg.value); // transfer wei from sender to receiver
}
function setRequiredWei(uint newRequiredWei) public {
require(msg.sender == owner(), "Only the contract owner can change the required amount of wei");
requiredWei = newRequiredWei;
}
function owner() public view returns (address) {
return address(this);
}
receive() external payable {
// fallback function to receive wei
}
}
I get the following error:
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
Returned error: {"jsonrpc":"2.0","error":"execution reverted","id":4455215050618515}
Note: The sender's wallet has enough ether to be transfered.
Best Answer
Your transaction is reverting.
In your
setRequiredWei
you are checking thatmsg.sender
is the owner. You get the owner address from functionowner()
, which gets it fromaddress(this)
. The problem is thataddress(this)
refers to the contract's address. The contract can never bemsg.sender
, so therequire
statement reverts.I'm not sure what you are trying to achieve with your
owner()
function, but typically contract's owner is the one who deploys the contract. So you could have a variableowner
which is set to be the value ofmsg.sender
in the constructor. Or better yet, use OpenZeppelin's ready Ownable contract: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol