【Msg】

msg 代表這個 contracts 當前收到什麼訊息,

  • msg.data (bytes): 完整的 calldata

  • msg.sender (address): 誰傳遞了這個訊息,或指訊息的來源地址是什麼

  • msg.value (uint): 傳遞來的訊息,傳遞了多少 wei

  • msg.gas: 剩餘的 gas 是多少,已被 gasleft() 取代

在 Solidity 中,要執行一個函數通常會需要外部有一個 caller。如果今天沒有人呼叫這個函數,這個函數就會一直靜靜地躺在區塊鏈之中什麼都不做。反之,msg.sender 就會一直存在。

pragma solidity ^0.8.11;

contract myContract {
    mapping (address => uint) favoriteNumber;

    function setMyNumber(uint _myNumber) public {
    // Update our `favoriteNumber` mapping to store `_myNumber` under `msg.sender`
    favoriteNumber[msg.sender] = _myNumber;
    // ^ The syntax for storing data in a mapping is just like with arrays
    }

    function whatIsMyNumber() public view returns (uint) {
    // Retrieve the value stored in the sender's address
    // Will be `0` if the sender hasn't called `setMyNumber` yet
    return favoriteNumber[msg.sender];
    }
}

msg 有兩個屬性,一個是 msg.sender,另一個是 msg.value,這兩個值可以被任何 external 函數調用,包含庫裏面的函數。

calldatamsg.dataexternal 函數的參數們。

pragma solidity ^0.8.11;

contract SendMoney{
    
    uint public balanceReceived;
    
    function receiveMoney() public payable {
        balanceReceived += msg.value; // amount in wei
    }
    
    function getBalance() public view returns(uint){
        return address(this).balance;
    }
    
    function withdrawMoney() public {
        address payable to = msg.sender;
        
        to.transfer(this.getBalance()); // withdraw all money
        
        // here, you sholud avoid store balance amount in a variable
        // beacuse after withdrawMoney work, the balanceReceived won't change
        // but this.getBalance() return the real balance == 0;
        
        
        // if we transfer 1 ether, finally the to account get 100.999999...
    }
    
    function withdrawMoneyTo(address payable _to) public {
        _to.transfer(this.getBalance());
        
        // if we transfer 1 ether, finally the to account get finally 101!
        // because the gas was paid by the contract deployer
    }
}

Last updated

Was this helpful?