首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何构建接受usdt、usdc等ERC20令牌的代管合同,而不仅仅是以太

如何构建接受usdt、usdc等ERC20令牌的代管合同,而不仅仅是以太
EN

Ethereum用户
提问于 2022-12-04 15:40:07
回答 2查看 151关注 0票数 0

我正在建立一个托管智能合同,我希望代管能够接收ERC20代币最好是稳定的硬币,如USDT或USDC,而不是以太。

有什么办法在我的合同上执行吗?

EN

回答 2

Ethereum用户

发布于 2022-12-04 16:05:06

我正在尝试实现类似的功能。尝尝这个。我不确定它是否会起作用,但试试看。

代码语言:javascript
运行
复制
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));
}


}
票数 0
EN

Ethereum用户

发布于 2022-12-05 01:48:30

是的,在托管合同中实现接收ERC20令牌的能力是可能的。下面是如何做到这一点的一个例子:

导入ERC20合同:

代码语言:javascript
运行
复制
import "https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v3.0.0/contracts/token/ERC20/SafeERC20.sol";

定义您希望在合同中接收的ERC20令牌

代码语言:javascript
运行
复制
contract Escrow {
    SafeERC20 public token;

    constructor(SafeERC20 _token) public {
        token = _token;
    }
}

向合同中添加一个函数,允许用户存放ERC20令牌:

代码语言:javascript
运行
复制
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;
}

向合同中添加一个函数,允许用户撤回已存放的令牌:

代码语言:javascript
运行
复制
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), "");
票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/140552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档