【问题标题】:Solidity: How to test if a function is called from another contract?Solidity:如何测试一个函数是否被另一个合约调用?
【发布时间】:2022-10-25 03:59:12
【问题描述】:

我想知道如何测试是否使用 chai 从另一个合约调用函数。

合同将类似于:

contract ContractA {
  function shouldBeCalledByOthers() { // some code... };
}

contract ContractB {
  ContractA contractA;

  constructor(address addr) {
    contractA = ContractA(addr);
  }

  function shouldCallA() {
    contractA.shouldBeCalledByOthers();
  }
}

那我想测试一下在调用ContractB的shouldCallA方法时是否调用了ContractA的shouldBeCalledByOthers方法。

chai spy 可以用于此目的吗? https://www.chaijs.com/plugins/chai-spies/

【问题讨论】:

    标签: blockchain solidity chai


    【解决方案1】:

    在 Solidity 中,您可以验证函数调用者是否为合约:

    modifier callerIsUser() {
      require(tx.origin == msg.sender, "The caller is another contract");
      _;
    }
    
    function example() callerIsUser {
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-16
      • 2021-08-25
      • 2020-05-13
      • 2021-09-11
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 2021-03-06
      相关资源
      最近更新 更多