// SPDX-License-Identifier: MIT

pragma solidity 0.8.14;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract ERC20Exchange is Ownable {
    IERC20 public trxToken;
    IERC20 public usdtToken;
    AggregatorV3Interface public priceFeed;

    constructor(address _trxToken, address _usdtToken, address _priceFeed) {
        trxToken = IERC20(_trxToken);
        usdtToken = IERC20(_usdtToken);
        priceFeed = AggregatorV3Interface(_priceFeed);
    }

    function depositTRX() external payable {
        trxToken.transferFrom(msg.sender, address(this), msg.value);
    }

    function depositUSDT(uint256 amount) external {
        usdtToken.transferFrom(msg.sender, address(this), amount);
        uint256 trxAmount = convertUSDTtoTRX(amount);
        require(trxAmount <= trxToken.balanceOf(address(this)), 'Insufficient TRX balance');
        trxToken.transfer(msg.sender, trxAmount);
    }

    function convertUSDTtoTRX(uint256 amount) internal view returns (uint256) {
        (,int256 price,,,) = priceFeed.latestRoundData();
        require(price > 0, 'Invalid price');
        uint256 trxAmount = (amount * uint256(price)) / 1e8;
        return trxAmount;
    }

    function withdrawTRX(uint256 amount, address recipient) external onlyOwner {
        require(amount <= trxToken.balanceOf(address(this)), 'Insufficient TRX balance');
        trxToken.transfer(recipient, amount);
    }

    function withdrawUSDT(uint256 amount, address recipient) external onlyOwner {
        require(amount <= usdtToken.balanceOf(address(this)), 'Insufficient USDT balance');
        usdtToken.transfer(recipient, amount);
    }

    function getTRXBalance() external view returns (uint256) {
        return trxToken.balanceOf(address(this));
    }

    function getUSDTBalance() external view returns (uint256) {
        return usdtToken.balanceOf(address(this));
    }
} 
ERC20 智能合约:USDT/TRX 兑换桥

原文地址: https://www.cveoy.top/t/topic/pdRt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录