solidity

Smart Contract Withdrawal from contract owner


For example I don't want to store ETH on Smart Contract but to the contract owner. Then how to implement withdrawal from the contract owner?

pragma solidity ^0.8.7;

    contract WDfromContractOwner {
    
       address public owner;
    
        constructor() {
         owner=msg.sender;
        }
    
        function deposit() external payable returns (bool) {     
        payable(owner).transfer(msg.value);
        return true;
        }
    
        function withdrawal() external returns (bool) {     
         
          // Witdrawal from owner address....???

        return true;
        }
    
    }

Solution

  • A smart contract is not able to pull ETH from an address (other than the address sending the ETH to the contract). The transfer needs to always be originated from and signed by the sender (in your case the owner).


    However, it can pull tokens owned by an address. The sender (owner) needs to approve() the amount at first, interacting with the token contract from their address. Then your contract can invoke the token's transferFrom() function.

    pragma solidity ^0.8;
    
    interface IERC20 {
        function transferFrom(address, address, uint256) external returns (bool);
    }
    
    contract WDfromContractOwner {
        address public owner;
    
        function withdrawToken() external {
            // Only reachable from the mainnet.
            // Transfers from other networks (such as Remix VM) will fail.
            address mainnetUSDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
            address receiver = msg.sender; // address of the user executing the `withdrawToken()`
            uint256 amount = 5 * 1e6; // 5 USDT, 6 decimals
            require(
                // the `owner` needs to execute `approve()` on the token contract directly from the `owner` address
                // so that the `WDfromContractOwner` contract can spend their tokens
                IERC20(mainnetUSDT).transferFrom(owner, receiver, amount)
            );
        }
    }
    

    You can get the approved amount using web3.js:

    const USDTAddress = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
    const ownerAddress = "0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF";
    
    // just the `balanceOf()` is sufficient in this case
    const ABI = [
        {"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}
    ];
    
    const USDTContract = new web3.eth.Contract(ABI, USDTAddress);
    const approved = await USDTContract.methods.balanceOf(ownerAddress).call();
    console.log(approved);