首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何确保您的合同收到ETH

如何确保您的合同收到ETH
EN

Ethereum用户
提问于 2021-09-07 23:12:16
回答 1查看 80关注 0票数 0

我正在玩一个测试合同&正在学习如何转移和持有资金。我现在已经设置了一个池,它被设置为接收ETH &没有其他东西。但是,在编写第一个检查池的测试时,我的映射(为了测试而监视余额的方式)正在更新,但我检查池余额的函数仍然返回零。

我是不是做错了什么,还是我完全错过了什么?这里的任何帮助都将是非常感谢的,它一整天都在做,结果却很少。有关守则如下:

合同:

代码语言:javascript
运行
复制
contract Pool {
  mapping(address => uint256) public stakerAmt;

  function stake(uint256 _amount, address payable _from) public payable {
    _amount = _amount * 1 ether;
    stakerAmt[_from] += _amount;
    payable(address(this)).transfer(msg.value);
  }

  function getPoolBalance() public view returns (uint256) {
    console.log("Contract balance: ", address(this).balance);
    return address(this).balance;
  } 

}

测试:

代码语言:javascript
运行
复制
describe('Pool', function () {
    it('Should accept staked eth', async function () {
        const Pool = await ethers.getContractFactory('Pool');
        const pool = await Pool.deploy();
        await pool.deployed();

        const [user] = await ethers.getSigners();

        const stake = await pool.connect(user).stake(20, user.address);

        await stake.wait();
        console.log(stake);
        console.log(await pool.getPoolBalance().toString());

        assert.equal(20, 20);
    });

谢谢你!!

EN

回答 1

Ethereum用户

发布于 2021-09-07 23:42:25

你在用Remix吗!你的合同在Remix上有效吗?!在稳定的情况下,我们没有console.log(),是您声明的函数吗?!

函数你想写,它写不好!我会给你看一个更好的:

代码语言:javascript
运行
复制
//You do not need those parameters
function stake() public payable {
  //Here you make sure caller sends some ETH.
  require(msg.value >= PRICE_YOU_WANT, "You did not send enough ETH");

  //Add stake amount into the stakerAmt by the caller address. msg.value is in wei and you
  //store it in wei because other paying functions also are in wei (for example address.transfer)
  stakerAmt[msg.sender] += msg.value;
  
  //Then you do not need those functions! Because when the caller calls this function
  //it automatically send ETH! So those functions are not usefull!
}
票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

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

复制
相关文章

相似问题

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