ETH 合约常用方法

contract Test {
    
    event NFTReceived(address operator, address from, uint256 tokenId, bytes data);
    function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4) {
        //only receive the _nft staff
        if(address(this) != operator) {
            //invalid from nft
            return 0;
        }
        
        //success
        emit NFTReceived(operator, from, tokenId, data);
        return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
    }
    
// 从合约中转进账户 ERC20
   function erc20income(IERC20 asset, address account, uint256 balance) external {
        asset.transferFrom(account, address(this), balance);
    }

// 从账户转进合约中 ERC20
   function erc20withdraw(IERC20 asset, address account) external returns (uint256 balance) {
        balance = asset.balanceOf(address(this));
        asset.transfer(account, balance);
    }

// 从账户转到合约
    function nftWithdraw(IERC721 token, address account, uint256 tokenId) external {
        token.safeTransferFrom(address(this), account, tokenId);
    }

// 从账户转到合约
	function nft2Contract(IERC721 token, address account, uint256 tokenId) external {
		token.safeTransferFrom(account, address(this), tokenId);
	}
	
	
// 从合约中转出去 ETH
    function ethWithdraw(address payable account) external  {
        uint256 _currentBalance =  address(this).balance;
        account.transfer(_currentBalance);
    }
    
    
// 从合约中转出去 ETH
    function ethIncome() external payable {

    }
    
// 可以直接转账 ETH
    function () external payable {}
    
}
posted @ 2021-07-06 15:53  ShaoYL  阅读(638)  评论(0编辑  收藏  举报