[Ethereum] swap token for usdt, create function send 1 usdt and receive 1 token

erc-20etherremixsolidityusdt

I need to create a smart contract where each token of mine will be exchanged for 1 usdt, that is, a person sends 1 usdt to the function and he adds 1 token to his balance sheet.
How can I do it? with eth it is simple but usdt is being a challenge for me.
Does anyone have an example?
How can I test on the ropsten network?

Best Answer

For ERC20 the usual approach is to require the user to approve your contract.

You have to do something like this from the front end.

// USDT parameters
const erc20Token = new web3.eth.Contract(USDT_ABI, USDT_ADDRESS)

// Contract that will receive USDT
const recipient = new web3.eth.Contract(RECIPIENT_ABI, RECIPIENT_ADDRESS)

// Require user approval
await erc20Token.approve(AMOUNT, RECIPIENT_ADDRESS).send({from: USER_ADDRESS})

// Call function on recipient to retrieve USDT
await recipient.deposit(AMOUNT).send({from: USER_ADDRESS})

Smart contract


contract Recipient {
    // USDT token
    IERC20 usdt = IERC20(USDT_ADDRESS);

    // Token to send for USDT
    IERC20 token = IERC20(token);

    function deposit(uint256 amount) public {
        // Transfer amount USDT tokens from msg.sender to contract
        usdt.transferFrom(msg.sender, address(this), amount);

        // Send amount tokens to msg.sender
        token.transfer(msg.sender, amount);
    }
}

Related Topic