Solidity – Create Smart Contract with Hard-Coded Wallet Address and Ether Amount

soliditywallet-transfer

I want to create a smart contract to transfer ethers automatically to a wallet address upon deployment of the contract without providing any user input or performing any other action after deployment. The wallet address and the amount to be transferred will be hard coded in the contract itself.

pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT


contract SendEther {
    address payable public walletAddress = payable(Hardcoded wallet address);
    uint public etherAmount = 0.01 ether; // Hardcoded ether amount

    constructor() payable {
        walletAddress.transfer(etherAmount);
    }
}

I call the transfer function in the constructor. I have sufficient ether in my sender wallet, however I am getting an 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":5648130930692979}

Best Answer

The solidity part looks fine. The only thing I will change is this line:

walletAddress.transfer(etherAmount);

Generally it's better to use .call so you can be sure walletAddress doesn't revert for out-of-gas (it can happen if it executes some logic when it receives ETH).

(bool success, ) = walletAddress.call{value: etherAmount}("");
require(success);

However this is very unlikely so I don't think it's the cause of your error.

It's more likely you're messing up how to send the transaction. For example, check that you actually send value: etherAmount with it. Using ethers:

const contract = await contractFactory.deploy({value: etherAmount});

Using remix there's a value box input.

Related Topic