Issue
When the contract is deployed it has an address that we can call by address(this). My contract is receivable from an address which means I can send() or transfer() to this contract but If I want to transfer from this actual contract to any account how can I do that?
example code:
function submitTransaction(address _to,uint _value,string memory _desc) public
onlyOwner
{
require(_value <= address(this).balance,"This wallet does not have enough balace to send");
if(!_to.send(_value)){
revert("doposit fail");
}
}
but how can I deduct from address(this).balance?
Solution
You can see this example of smart contract code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Bank {
address owner;
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "You're not the smart contract owner!");
_;
}
event Deposited(address from, uint amount);
function depositMoney() public payable {
emit Deposited(msg.sender, msg.value);
}
// Use transfer method to withdraw an amount of money and for updating automatically the balance
function withdrawMoney(address _to, uint _value) public onlyOwner {
payable(_to).transfer(_value);
}
// Getter smart contract Balance
function getSmartContractBalance() external view returns(uint) {
return address(this).balance;
}
}
ADVICE: In this case, if you want use only transfer or send, I advice you to use transfer() method instead send(), because it throws on failure if transfer didn't work. I recommend to read this thread. On the contrary for avoid reentracy attack you must to call method to transfer ether.
Answered By - Kerry99 Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.