简体   繁体   English

检测发送到合约的 ERC20 代币 -?

[英]Detection of ERC20 tokens sent to Contract -?

I'm developing a game.我正在开发一个游戏。 Energy will be purchased with my own token.能源将用我自己的代币购买。

For example, to buy energy, you will use the "X" token you purchased earlier.例如,要购买能源,您将使用之前购买的“X”代币。 It's like buying 1 energy for 1000 "X" tokens.这就像用 1000 个“X”代币购买 1 个能量。

I searched a lot but couldn't find an answer.我搜索了很多,但找不到答案。

I'm looking for a function just like receive() does.我正在寻找一个 function 就像 receive() 一样。

I want to add the amount of XXXX tokens sent to the contract and the wallet address that sent these tokens to a mapping and update the energy count.我想将发送到合约的 XXXX 代币数量和发送这些代币的钱包地址添加到映射并更新能量计数。

For example, the user has sent 1000 X tokens (X is representative only).例如,用户发送了 1000 个 X 代币(X 仅代表)。 The amount of X tokens sent will be recorded with the sending wallet: Example: mapping(address => uint) xTokenInfo;发送的 X 代币数量将记录在发送钱包中: 示例: mapping(address => uint) xTokenInfo;

And for every 1000 X tokens, energy will be given to the wallet that sent the token.每 1000 个 X 代币,就会向发送代币的钱包提供能量。

For example: Let's say 10,000 (10K) X tokens are sent.例如:假设发送了 10,000 (10K) 个 X 令牌。 That means 10 energy.这意味着 10 能量。

SAMPLE:样本:

address currentTokenAddress = 0xTOKEN;

mapping(address => uint) energyBalance;

function sendToken_and_ConvertEnergys(uint _tokenAmount){
  if(sentToken == currentTokenAddress){
    energyBalance[msg.sender] = (_tokenAmount/1000);
  } else {
    revert("Only X TOKENs are accepted");
 }
}

You need to use Standard ERC20 interface in your contract to transfer X token and in order to do so, you need to let your users to approve the same amount of token prior to it (Approve is usually done through the UI).您需要在合约中使用标准 ERC20 接口来转移 X 代币,为此,您需要让您的用户在其之前批准相同数量的代币(批准通常通过 UI 完成)。

Try this:尝试这个:

interface IERC20 {
   function transferFrom(address sender, address recipient, uint amount) external returns(bool);
   /* rest of the method */
}

contract Energy {
   address currentTokenAddress public = 0xTOKEN;
   mapping(address => uint) energyBalance;

   function sendToken_and_ConvertEnergys(uint _tokenAmount) external {
       uint calculatedEnergy = _tokenAmount/1000;
       IERC20(currentTokenAddress ).transferFrom(msg.sender,address(this),calculatedEnergy);
       energyBalance[msg.sender] += _calculatedEnergy;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM