如何在 Remix IDE 中设置 msg.value
How to set msg.value in Remix IDE
这可能是我遗漏的一个简单错误,但我终究无法弄清楚如何在此合同中设置 msg.value 变量。我在网上看到这个值是与交易关联的wei的数量,但是我作为合约的调用者具体怎么设置这个值。这是我正在努力处理的合同。
pragma solidity 0.8.7;
合同自动售货机{
// Declare state variables of the contract
address public owner;
mapping (address => uint) public cupcakeBalances;
// When 'VendingMachine' contract is deployed:
// 1. set the deploying address as the owner of the contract
// 2. set the deployed smart contract's cupcake balance to 100
constructor() {
owner = msg.sender;
cupcakeBalances[address(this)] = 100;
}
// Allow the owner to increase the smart contract's cupcake balance
function refill(uint amount) public {
require(msg.sender == owner, "Only the owner can refill.");
cupcakeBalances[address(this)] += amount;
}
// Allow anyone to purchase cupcakes
function purchase(uint amount) public payable {
require(msg.value >= amount * 1 ether, "You must pay at least 1 ETH per cupcake");
require(cupcakeBalances[address(this)] >= amount, "Not enough cupcakes in stock to complete this purchase");
cupcakeBalances[address(this)] -= amount;
cupcakeBalances[msg.sender] += amount;
}
}
每次输入金额时,我都会收到错误消息“您必须为每个纸杯蛋糕支付至少 1 ETH”
我没有地方可以具体输入我要为此支付多少钱,任何帮助都会很好
here's what I'm able to input when I deploy the contract on Remix
部署按钮顶部您可以看到值字段:
当您想调用 purchase
时,首先填写值字段,然后 select Ether
调用您的函数。
我用你的代码尝试了这种方式,它工作正常。
这可能是我遗漏的一个简单错误,但我终究无法弄清楚如何在此合同中设置 msg.value 变量。我在网上看到这个值是与交易关联的wei的数量,但是我作为合约的调用者具体怎么设置这个值。这是我正在努力处理的合同。
pragma solidity 0.8.7;
合同自动售货机{
// Declare state variables of the contract
address public owner;
mapping (address => uint) public cupcakeBalances;
// When 'VendingMachine' contract is deployed:
// 1. set the deploying address as the owner of the contract
// 2. set the deployed smart contract's cupcake balance to 100
constructor() {
owner = msg.sender;
cupcakeBalances[address(this)] = 100;
}
// Allow the owner to increase the smart contract's cupcake balance
function refill(uint amount) public {
require(msg.sender == owner, "Only the owner can refill.");
cupcakeBalances[address(this)] += amount;
}
// Allow anyone to purchase cupcakes
function purchase(uint amount) public payable {
require(msg.value >= amount * 1 ether, "You must pay at least 1 ETH per cupcake");
require(cupcakeBalances[address(this)] >= amount, "Not enough cupcakes in stock to complete this purchase");
cupcakeBalances[address(this)] -= amount;
cupcakeBalances[msg.sender] += amount;
}
}
每次输入金额时,我都会收到错误消息“您必须为每个纸杯蛋糕支付至少 1 ETH”
我没有地方可以具体输入我要为此支付多少钱,任何帮助都会很好
here's what I'm able to input when I deploy the contract on Remix
部署按钮顶部您可以看到值字段:
当您想调用 purchase
时,首先填写值字段,然后 select Ether
调用您的函数。
我用你的代码尝试了这种方式,它工作正常。