[英]what is the differnce between msg.sender and address(this) in below code?
我是初學者,最近我開始學習 Solidity 請幫助我理解下面的代碼 下面代碼中 msg.sender 和 address(this ) 之間的區別是什么
**pragma solidity ^0.8.0;
contract Escrow{
address public payer;
address payable public payee;
address public lawyer;
uint public amount;
constructor(
address _payer,
address payable _payee,
uint _amount) {
payer = _payer;
payee = _payee;
lawyer = msg.sender;
amount = _amount;
}
function deposit() payable public {
require(msg.sender == payer, 'Sender must be the payer');
require(address(this).balance <= amount, 'Cant send more than escrow amount');
}
function release() public {
require(address(this).balance == amount, 'cannot release funds before full amount is sent');
require(msg.sender == lawyer, 'only lawyer can release funds');
payee.transfer(amount);
}
function balanceOf() view public returns(uint) {
return address(this).balance;
}
}**
msg.sender
是合約調用者的地址。
address(this)
是智能合約本身的地址。
它們都是msg.sender
address(this)
,但是msg.sender
和address(this)
之間有很大的區別。
請允許我使用下面的簡化智能合約來強調差異。 所有屏幕截圖均來自 Remix-Ethereum IDE(單擊此處)。
pragma solidity ^0.8.0;
contract Escrow {
address public owner;
constructor() {
owner = msg.sender;
}
function depositNothing() public view {
require(msg.sender == owner, 'You are not the owner!');
}
function balanceOf() view public returns(uint) {
return address(this).balance;
}
}
msg.sender
我們正在談論調用智能合約中的函數的帳戶地址。 例如,假設在 Remix Ethereum (IDE) 中, Escrow
智能合約是從 ACCOUNT 地址部署的:
0x5B38Da6a701c568545dCfcB03FcB875f56beddC4
在這種情況下,狀態變量owner
將擁有與上述相同的地址。 這是因為constructor
函數是從該地址調用的。
現在,假設我們將 ACCOUNT 地址更改為:
0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2
然后我們從之前部署的智能合約中調用功能depositNothing
。 但是,您將收到以下錯誤:
這是因為msg.sender
在depositNothing
功能等同於第二個帳戶地址。 這顯然不等同於第一個 ACCOUNT Address- owner
。 因此, require
函數中的第二個參數與錯誤一起返回。
地址(這個)
這與前面討論的 ACCOUNT 地址不同。 這嚴格指的是智能合約部署到以太坊區塊鏈時提供給它的地址。
這可以在這里找到:
0xd8b934580fcE35a11B58C6D73aDeE468a2833fa8
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.