Solidity
將乙太幣發送到 Solidity 中的支付功能不會減少發件人在 Ganache 中的乙太幣
我有以下智能合約:
pragma solidity ^0.8.0; import "./IERC20.sol"; import "./MyCoinSupply.sol"; contract MyCoinDEX { IERC20 public token; event Bought(uint256 amount); event Sold(uint256 amount); constructor() public { token = new MyCoinSupply(); } function getSenderAddress() public view returns (address) // for debugging purposes { return (msg.sender); } function getAddress() public view returns (address) { return address(this); } function getTokenAddress() public view returns (address) { return address(token); } function buy() payable public // send ether and get tokens in exchange; 1 token == 1 ether { uint256 amountTobuy = msg.value; uint256 dexBalance = token.balanceOf(address(this)); require(amountTobuy > 0, "You need to send some ether"); require(amountTobuy <= dexBalance, "Not enough tokens in the reserve"); token.transfer(msg.sender, amountTobuy); emit Bought(amountTobuy); } function sell(uint256 amount) public // send tokens to get ether back { require(amount > 0, "You need to sell at least some tokens"); uint256 allowance = token.allowance(msg.sender, address(this)); require(allowance >= amount, "Check the token allowance"); token.transferFrom(msg.sender, address(this), amount); // https://stackoverflow.com/questions/67341914/error-send-and-transfer-are-only-available-for-objects-of-type-address-payable payable(msg.sender).transfer(amount); emit Sold(amount); } }
如果我從 呼叫該
buy()
方法truffle console
,它將毫無例外地執行:truffle(development)> MyCoinDEX.buy({value: 1})
我驗證了呼叫該
buy()
方法的帳戶收到了令牌。**但是,呼叫該buy()
方法的帳戶的 Ganache 中的 Ether 餘額並沒有減少。**因此,從本質上講,該帳戶是免費獲得代幣的。這裡發生了什麼?我如何解決它?
先感謝您!
你混淆了乙太和魏。
truffle(development)> MyCoinDEX.buy({value: 1})
value 屬性在 Wei 中,就像乙太坊網路上的所有東西一樣,所以你發送一個 Wei 或 0.000000000000000001 Ether。
ganache 顯示精度不一定涵蓋 18 位小數,因此您甚至可能看不到任何變化…
因此,從本質上講,該帳戶是免費獲得代幣的。
不完全是,但至少非常便宜!
如果要發送 1 ETH,請設置值:1000000000000000000 Wei。