Reputation: 1382
I've a smart contract with constructor payable type. As per my understanding declaring payable constructor means a smart contract can able to receive a payments. I've published it through metamask on testnet Binance smart chain. But as soon as I go to send funds directly to smart contract address. It appears an error of gas price, with even the smallest amount of transaction i send it doesn't work,
Contract deployed at: https://testnet.bscscan.com/address/0x75d0b70f597fd23e73c5f193af45023bc65471d7
Transaction Failing in: https://testnet.bscscan.com/tx/0x1258efe59c2fd2d074858082d3b20c6742256c231ecbfa9c48eee4d81a73153a Solidity Code:
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.0;
import "hardhat/console.sol";
contract BurgerShop {
uint256 public cost = 0.2 * (10**18);
event BurgerBought(address indexed _from, uint256 cost);
constructor() payable{
emit BurgerBought(msg.sender, cost);
}
}
Secondly, I want to know what is the best approach to recieve funds directly send through smart contract address. Like If i have a smart contract A with an address of 0xaaa...zzzz How can user directly deposit into smart contract address from WALLET?
Upvotes: 1
Views: 424
Reputation: 43481
When a constructor
uses the payable
modifier, the contract is able to accept ETH during deployment. I.e. the deployment transaction can have non-zero value
.
But this doesn't mean that the contract is able to accept ETH later.
In order to accept ETH just like an end user address, a contract needs to implement either fallback()
or receive()
special function.
Docs: https://docs.soliditylang.org/en/v0.8.13/contracts.html#special-functions
Example:
pragma solidity ^0.8;
contract MyContract {
receive() external payable {
// executed when the `data` field is empty and `value` is > 0
}
}
Upvotes: 2