Solidity

契約在單個源文件中創建另一個契約

  • April 17, 2016

當部署為單個源文件時,儲存在creator = TokenCreator(msg.sender)函式內變數中OwnedToken的地址是指合約TokenCreator地址還是外部帳戶地址?

contract OwnedToken {

TokenCreator creator;
address owner;
bytes32 name;

function OwnedToken(bytes32 _name) {
   owner = msg.sender;

   creator = TokenCreator(msg.sender);
   name = _name;
}
function changeName(bytes32 newName) {

   if (msg.sender == creator) name = newName;
}
function transfer(address newOwner) {
   if (msg.sender != owner) return;

   if (creator.isTokenTransferOK(owner, newOwner))
       owner = newOwner;
}


contract TokenCreator {
   function createToken(bytes32 name)
      returns (OwnedToken tokenAddress)
   {

       return new OwnedToken(name);
   }
   function changeName(OwnedToken tokenAddress, bytes32 name) {

       tokenAddress.changeName(name);
   }
   function isTokenTransferOK(
       address currentOwner,
       address newOwner
   ) returns (bool ok) {
       address tokenAddress = msg.sender;
       return (sha3(newOwner) & 0xff) == (bytes20(tokenAddress) & 0xff);
   }
}

creator = TokenCreator(msg.sender);

creator地址為msg.sender

msg.sender是創建 的帳戶的地址OwnedToken。有2種情況:

  • 創建的外部帳戶OwnedToken

或者

  • 一個契約,如TokenCreator,創建一個OwnedToken(via new OwnedToken(...))。

當部署為單個源文件時,只有最後一個合約在區塊鏈上被實例化,這是 TokenCreator 的一個實例,它獲取一個地址,呼叫它X

當交易稍後被發送到X呼叫createToken時,這是在區塊鏈上實例化 OwnedToken 並且creator在該 OwnedToken 中將是X

請注意,這X與用於部署單個源文件的外部帳戶不同。並且外部帳戶呼叫createToken可以與用於部署單個源文件的帳戶相同或不同。

引用自:https://ethereum.stackexchange.com/questions/3091