I am building an escrow smart contract, i would like the escrow to be able to receive ERC20 tokens preferably stable coins like USDT OR USDC and not ether.
Is there a way to implement this to my contract please ?
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityYes, it is possible to implement the ability to receive ERC20 tokens in an escrow contract. Here is an example of how this could be done:
Import the ERC20 contract:
import "https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v3.0.0/contracts/token/ERC20/SafeERC20.sol";
Define the ERC20 token you want to receive in the contract
contract Escrow {
SafeERC20 public token;
constructor(SafeERC20 _token) public {
token = _token;
}
}
Add a function to the contract to allow the user to deposit ERC20 tokens:
function deposit(uint256 _amount) public {
// Transfer the tokens from the user's account to the contract
require(token.transferFrom(msg.sender, address(this), _amount), "Transfer failed");
// Store the deposited tokens in a mapping
// You can use a struct or any other data structure to store the deposited tokens
depositedTokens[msg.sender] += _amount;
}
Add a function to the contract to allow the user to withdraw the deposited tokens:
function withdraw(uint256 _amount) public {
// Check if the user has enough deposited tokens
require(depositedTokens[msg.sender] >= _amount, "Not enough deposited tokens");
// Transfer the tokens from the contract to the user's account
require(token.transfer(msg.sender, _amount), "");
I am trying to implement a similar function. Try this. I am not sure if it'll work but give it a try.
pragma solidity ^0.8.0;
interface IERC20 {
function transferFrom(address _from, address _to, uint256 _amount) external returns (bool);
}
contract ABC{
function enter() public payable {
IERC20 token = IERC20(`0x123`); // Insert the token contract address instead of `0x123`
require(token.transferFrom(msg.sender, address(this), .01 ether));
}
}