Search code examples
blockchainethereumsoliditysmartcontractstruffle

Call a function in another contract - Solidity


I need to call a function in another contract using Truffle. This is my sample contract:

Category.sol:

contract Category {
  /// ...
  /// @notice Check if category exists
  function isCategoryExists(uint256 index) external view returns (bool) {
    if (categories[index].isExist) {
      return true;
    }
    return false;
  }
}

Post.sol:

contract Post {
  /// ...
  /// @notice Create a post
  function createPost(PostInputStruct memory _input)
    external
    onlyValidInput(_input)
    returns (bool)
  {
    /// NEED TO CHECK IF CATEGORY EXISTS
    /// isCategoryExists() <<<from Category.sol>>>
  }
}

Deploy.js

const Category = artifacts.require("Category");
const Post = artifacts.require("Post");

module.exports = function (deployer) {
  deployer.deploy(Category);
  deployer.deploy(Post);
};

What can I do?


Solution

  • You can inherit from other contract. Let's say you want to import from Post contract.

    contract Category is Post {
      /// ...
      /// @notice Check if category exists
      function isCategoryExists(uint256 index) external view returns (bool) {
        if (categories[index].isExist) {
          return true;
        }
        return false;
      }
      // you can call createPost
      createPost(){}
    }