[Ethereum] Breaking one large contract to multiple smaller contracts

oraclessolidity

I'm building a project which has the following artifacts:

  1. the complete code for Oraclize API, inline, (1329 lines of code
    including comments and description)
  2. SafeMath Library, inline, (114 lines of code)
  3. a contract called Ownable which has codes to change owner, modifiers
    related to owner etc. this contract is small (around 80 lines)
  4. the main project contract which is large (around 1300 lines of code,
    including comments and function description)

all these four artifacts are inline in the same file called ProjectName.sol.

I'm unable to deploy this project using truffle as I believe the size limit of the project has been exceeded (24576 bytes). Can you please tell me what would be the industry standard (best practice) to break this code into multiple contracts?

Best Answer

Having all contracts in a single file is most probably not the problem. It looks like your contract with 1300 lines of code is too large.

Moreover, you should look for your new statements, since they will include all the code of the contract to be instantiated. Factory pattern is a possibility to navigate around this.

contract A {}

contract AFactory {
    function createA() public returns(A) {
        return new A();
    }
}

contract B {
    AFactory fac;
    constructor(AFactory _fac) {fac = _fac;}
    ...
        fac.createA()
    ...
}

This will reduce the code size of the B contract since A code is not included, because new statement is in AFactory.

UPDATE another way to reduce the code size of a contract is to use delegation instead of inheritance. See https://refactoring.guru/replace-inheritance-with-delegation

It's difficult to tell more without seeing the code.

Related Topic