Withdraw balances user deposit into contract by contract owner

45 Views Asked by At

I want to create a contract where users can deposit balances into the contract. And when the user deposit, contract owner can withdraw that balances from contract meaning transfer that balance to owner's wallet. Is it possible? I just started learning Solidity so can you guys please help me?

I haven't try much yet. This is my Solidity code.

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

contract WithdrawalContract {
    mapping(address => uint256) public balances;

    function deposit(uint256 amount) public payable {
        balances[msg.sender] += amount;
    }
}

I want only the contract owner to withdraw that balance. How can I do that? Is it possible?

1

There are 1 best solutions below

0
On
pragma solidity ^0.8.20;

interface ERC20 {
    function transfer(address to, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);
    function approve(address spender, uint256 value) external returns (bool);
}

contract OnlyOwnerWithdraws {
    
    address owner;
    ERC20 asset; // not all ERC20 tokens are kind, some want to ruin your life, be careful
    error TransferFail();
    error NotOwner();

    constructor(address _asset) {
        owner = msg.sender;
        asset = ERC20(_asset);
    }

    function deposit(uint256 amount) public {
        // not all erc20 return bool, but that's a story for another day
        bool success = asset.transferFrom(msg.sender, address(this), amount);
        if(!success){ 
            revert TransferFail();
        }
    }

    function withdraw(uint256 amount) public {
        if(msg.sender != owner){
            revert NotOwner();
        }
        asset.transfer(owner, amount);
    }

}