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?
1 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);
}
}
-
what would be USDT_ABI? can I test this contract at ropsten? thanks Commented Feb 22, 2021 at 10:26
-
And my FrontEnd you refer javascript? In my website Commented Feb 22, 2021 at 10:42
-
@AugustoFurlan By USDT_ABI I meant the ABI contract for USDT (you can get it from etherscan for example, or use any generic ERC20). Front end will be the part that interact with your users.– Ismael ♦Commented Feb 22, 2021 at 13:35
-
Alredy, do you have a contract with this function that you want to share? I'm trying to 3 days and to no avail ... Commented Feb 22, 2021 at 17:51
-
@AugustoFurlan If you share your code we can analyse what is wrong with it. A common error is trying to call
approve
from the contract.– Ismael ♦Commented Feb 22, 2021 at 20:43