Untitled
unknown
plain_text
8 months ago
1.8 kB
1
Indexable
Never
// SPDX-License-Identifier: MIT pragma solidity 0.5.17; contract IERC20 { function balanceOf(address account) public view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) public returns (bool); function transfer(address recipient, uint256 amount) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); } contract Ownable { address public owner; modifier onlyOwner() { require(msg.sender == owner, "Not the owner"); _; } constructor() public { owner = msg.sender; } } 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