Solidity

如何從已部署的合約中呼叫函式?

  • April 20, 2017

我嘗試使用函式“Call”,如下所述:Calling function from deploy contract

但似乎它根本不起作用。

如何從現有部署的智能合約中呼叫函式?

我正在嘗試從接收地址作為參數的現有地址呼叫一個簡單的函式。

這是我用來呼叫外部函式的程式碼:

契約甲:

function CallExternalFunction(address externalContractAddress) 
{    
   externalContractAddress.call(bytes4(sha3("FunctionX(address)")),0xfffff);
   //sends 0xfffff as input parameter to the external contract
}

已經部署的合約源碼如下:

契約乙:

contract test { 

mapping (address => uint256) public balanceOf; 

function test() { 

}

function FunctionX(address _address)
{
   balanceOf[_address] = 50000;    
}
}

試試這個。部署呼叫者,它將部署測試合約以簡化事務。

contract Caller {

 test public t;

 function Caller() {
   t = new test();
 }

 function callIt(address theAddress)
   public
   returns(bool success)
 {
   t = test(t); <===== here the other contract address can be called t = test([OtherContractAddress]); example: test(0x12345);
   bool result = t.FunctionX(theAddress);
   return result;
 }
}

contract test { 

 mapping (address => uint256) public balanceOf; 

 function FunctionX(address _address) public returns(bool success)
 {
   balanceOf[_address] = 50000; 
   return true;
 }
}

在 Remix 中展示它的工作原理。

在此處輸入圖像描述

如果您有原始碼,則可以通過使用和介面契約對已經存在的契約使用類似的結構。在這裡,“呼叫者”編譯器可以看到足夠的 test {} 來管理介面。

contract Caller {

 test public t;

 // where test is deployed and the address is known
 // Pass in the address for test {}.

 function Caller(address tAddress) {
   t = test(tAddress); // address of contract t
 }

 function callIt(address theAddress)
   public
   returns(uint bal)
 {
     return t.FunctionX(theAddress);
 }
}

// This interface constant includes the function interfaces (exactly as in the "real" contract" with the fynctions undefined
// This tells the compiler how to communicate with the ABI in test{}.

contract test { 
 function FunctionX(address _address) public returns(uint balanceOf) {}
}

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