PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 28, 2022

[FIXED] How to send() or transfer() from the contract address to an account address in solidity (I mean to deduct from address(this).balance)

 July 28, 2022     blockchain, ethereum, smartcontracts, solidity     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing