gpt4 book ai didi

solidity - 在智能合约中接受以太币

转载 作者:行者123 更新时间:2023-12-02 21:45:50 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的智能合约来学习可靠性以及以太坊的工作原理。

据我了解,在方法上使用修改应付金额将使其接受一个值。然后我们从发送者那里扣除并添加到其他地方,在这段代码中我试图将其发送给契约(Contract)的所有者。

contract  AcceptEth {
address public owner;
uint public bal;
uint public price;
mapping (address => uint) balance;

function AcceptEth() {
// set owner as the address of the one who created the contract
owner = msg.sender;
// set the price to 2 ether
price = 2 ether;
}

function accept() payable returns(bool success) {
// deduct 2 ether from the one person who executed the contract
balance[msg.sender] -= price;
// send 2 ether to the owner of this contract
balance[owner] += price;
return true;
}
}

当我通过 remix 与此合约交互时,出现“VM 异常处理交易时出现异常:气体耗尽”的错误,它创建了一个交易,当我尝试执行操作时,气体价格为 21000000000,值(value)为 0.00 ETH从执行此方法的任何人处获得 2 个以太币。

代码有什么问题吗?或者,我可以添加一个变量来输入他们想要发送的值,以及提款方法,对吧?但为了学习,我想保持简单。但即使是这段代码也感觉有点简单,感觉缺少了一些东西。

最佳答案

我认为你迷失的地方是合约内置了接收和持有以太币的机制。例如,如果您想让您的 accept() 方法恰好接收 2 个以太币(或您设置的 price 的值),您可以执行以下操作:

contract  AcceptEth {
address public owner;
uint public price;
mapping (address => uint) balance;

function AcceptEth() {
// set owner as the address of the one who created the contract
owner = msg.sender;
// set the price to 2 ether
price = 2 ether;
}

function accept() payable {
// Error out if anything other than 2 ether is sent
require(msg.value == price);

// Track that calling account deposited ether
balance[msg.sender] += msg.value;
}
}

现在,假设您有两个帐户,其余额如下:

0x01 = 50 ether

0x02 = 20 ether

该合约已部署,地址为 0xc0。所有地址都可以持有以太币,因此即使合约本身也有余额。由于它刚刚部署(并且没有使用任何初始以太币进行部署),因此它的余额为 0。

现在假设 0x01 调用 accept() 发送 2 个以太币。交易将执行,我们示例中的 3 个地址将具有以下余额:

0x01 = 48 ether

0x02 = 20 ether

0xc0 = 2 ether

现在,假设 0x02 调用 accept() 两次,两次传递 2 个以太币:

0x01 = 48 ether

0x02 = 16 ether

0xc0 = 6 ether

合约持有发送给它的所有以太币。但是,您的合约还保存状态(您在代码中定义的余额映射),该状态跟踪谁存入了什么。因此,从该映射中您可以知道 0x01 存入了 2 个以太币,0x02 存入了 4 个以太币。如果你想引入一个将以太币发回的 refund() 方法,你可以这样写

function refund(uint amountRequested) public {
require(amountRequested > 0 && amountRequested <= balance[msg.sender]);

balance[msg.sender] -= amountRequested;

msg.sender.transfer(amountRequested); // contract transfers ether to msg.sender's address
}

关于solidity - 在智能合约中接受以太币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48351077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com