Solidity
如果餘額發生變化,我正在嘗試編寫一個 if 條件以給出響應
pragma solidity >0.7.0 <=0.9.0; contract demoCoin { address public Owner; mapping(address => uint256) myCoin; constructor() { Owner = msg.sender; } function loadCoin(uint256 amount) public { require(Owner == msg.sender); myCoin[Owner] += amount; } function sendCoin(address receiver, uint256 amount) public returns (string memory, uint256) { require(Owner == msg.sender); if (amount > myCoin[msg.sender]) revert("Insufficient balance"); myCoin[msg.sender] -= amount; myCoin[receiver] += amount; // I want to return the alert for a successful transaction if (myCoin[receiver] += amount) { return string = "You have been credited with" + amount + "demoCoin"; } } function showBal() public view returns (uint256) { return myCoin[msg.sender]; } }
您可以使用
event
註冊智能合約中的特定操作。您必須使用以下語句聲明事件:event [NameEvent] ([typeof] [nameVariable], [typeof] [nameVariable2]);
並註冊一個事件,你可以使用這個語句:
emit [NameEvent] ([valueVariable], [valueVariable2]);
在您的情況下,您以這種方式聲明一個事件:
... constructor (){ Owner = msg.sender; } // Declare event event SuccessfullTransfer(address receiver, uint amount); function loadCoin(uint amount) public { require(Owner == msg.sender); myCoin[Owner] += amount; } ....
並且您必須以這種方式在
sendCoin()
函式中呼叫它(在這種情況下):function sendCoin(address receiver, uint amount) public { require(Owner == msg.sender); if (amount > myCoin[msg.sender]) revert ('Insufficient balance'); myCoin[msg.sender] -= amount; myCoin[receiver] += amount; // I want to return the alert for a successful transaction if (myCoin[receiver] += amount) { emit SuccessfullTransfer(receiver, amount); }
當單個使用者與
sendCoin()
函式互動並將其代幣轉移到智能合約時,您可以在交易中看到該事件。注意:如果你要使用這種方式,你必須改變
sendCoin()
函式的返回類型。有關活動的更多資訊,請點擊此處。