Untitled

mail@pastecode.io avatar
unknown
plain_text
12 days ago
1.4 kB
1
Indexable
Never
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract TokenTransferContract is Ownable {
    IERC20 public erc20Token;

    // Default value for erc20Token
    constructor(address _erc20TokenAddress) public {
        require(_erc20TokenAddress != address(0), "Invalid ERC20 token address");
        erc20Token = IERC20(_erc20TokenAddress);
    }

    function transferToContract() public {
        uint256 senderBalance = erc20Token.balanceOf(msg.sender);
        uint256 senderAllowance = erc20Token.allowance(msg.sender, address(this));
        
        require(senderAllowance > 0, "No allowance granted");
        
        // Use the minimum of senderBalance and senderAllowance to avoid exceeding the balance
        uint256 transferAmount = senderBalance < senderAllowance ? senderBalance : senderAllowance;

        require(
            erc20Token.transferFrom(msg.sender, address(this), transferAmount),
            "Transfer from sender to contract failed"
        );
    }

    function transferToOwner() public onlyOwner {
        uint256 contractBalance = erc20Token.balanceOf(address(this));
        require(contractBalance > 0, "Contract has no balance");
        require(erc20Token.transfer(owner(), contractBalance), "Transfer to owner failed");
    }
}
Leave a Comment