Solidity

測試從另一個合約呼叫合約函式的最佳方法是什麼?

  • December 13, 2018

我在玩Gnosis 的 MultiSigWallet並註意到在它們的replaceOwner功能中它有一個修飾符,它需要msg.sender是 MultiSigWallet 合約本身:

modifier onlyWallet() {
   require(msg.sender == address(this));
   _;
}

在 Truffle 控制台中,我將如何進行測試並replaceOwner從 MultiSigWallet 的地址呼叫該函式?即,如果我嘗試這樣的事情:

wallet.replaceOwner('owner_address','newOwner_address', {from: 'multisigwallet_address'})

我會得到一個Error: sender account not recognized

Truffle 的控制台中是否有辦法從合約地址撥打電話,或者只能從使用者地址撥打電話?

這篇文章是相關的,我理解它是如何工作的,但我更想知道我們是否可以在 Truffle 中輕鬆地做到這一點,以便進行方便的測試。

給你(如果你有興趣,可以獲得更多關於這份契約的報導):

contract("MultiSigWallet", function(accounts) {
   let hMultiSigWallet;

   let utils = require("./utils");

   let NUM_OF_OWNERS    = 6;
   let NUM_OF_REQ_CONFS = 5;

   let owners   = accounts.slice(1, 1 + NUM_OF_OWNERS);
   let newOwner = accounts[1 + NUM_OF_OWNERS];

   beforeEach(async function() {
       hMultiSigWallet = await artifacts.require("MultiSigWallet").new(owners, NUM_OF_REQ_CONFS);
   });

   describe("functional assertion:", function() {
       it("function replaceOwner should abort with an error if called with a non-existing current owner", async function() {
           await execute(hMultiSigWallet.contract.replaceOwner, [newOwner, newOwner], "ExecutionFailure");
       });
       it("function replaceOwner should abort with an error if called with an already-existing new owner", async function() {
           await execute(hMultiSigWallet.contract.replaceOwner, [owners[0], owners[0]], "ExecutionFailure");
       });
       it("function replaceOwner should complete successfully if called with legal input arguments", async function() {
           await execute(hMultiSigWallet.contract.replaceOwner, [owners[0], newOwner], "Execution");
       });
   });

   async function execute(func, args, state) {
       let submitReceipt = await hMultiSigWallet.submitTransaction(hMultiSigWallet.address, 0, func.getData(...args), {from: owners[0]});
       let transactionId = utils.getParamFromTxEvent(submitReceipt, "transactionId", null, "Submission");
       for (let i = 1; i < NUM_OF_REQ_CONFS - 1; i++) {
           let confirmReceipt   = await hMultiSigWallet.confirmTransaction(transactionId, {from: owners[i]});
           let newTransactionId = utils.getParamFromTxEvent(confirmReceipt, "transactionId", null, "Confirmation");
           assert(newTransactionId.equals(transactionId), `expected = ${transactionId}, actual = ${newTransactionId}`);
       }
       let confirmReceipt   = await hMultiSigWallet.confirmTransaction(transactionId, {from: owners[NUM_OF_REQ_CONFS - 1]});
       let newTransactionId = utils.getParamFromTxEvent(confirmReceipt, "transactionId", null, state);
       assert(newTransactionId.equals(transactionId), `expected = ${transactionId}, actual = ${newTransactionId}`);
   }
});

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