0

Is there a way to change the value of address literals in solidity source code before migrating to a local test chain using Truffle? Currently, if a contract A needs to know the address of another contract B, you must pass B's address to A's constructor, which means the address must be stored as a state variable in A's storage. This is very expensive, costing 20,000 gas for initialization plus 200 gas for every read. Ideally B's address could be stored in A as a constant state variable, but constant's cannot be set in a constructor, only hardcoded into the source code.

For example, here, creation of C uses 20,000 more gas than D. And D's get() can be pure rather than view. I'd like to be able to change D's value of a before compiling and migrating to a test network.

contract C {
    address a;
    constructor(address _a) public {
        a = _a;
    }

    function get() external view returns (address) {
        return a;
    }
}
contract D {
    address constant a = 0x1111111111111111111111111111111111111111;

    function get() external pure returns (address) {
        return a;
    }
}
  • 1
    I'm a bit confused by the question. Of course you can change the source code before compiling it... are you asking about how to automate such a process? Or maybe whether Truffle has some built-in mechanism for doing so? – smarx Apr 27 at 18:43
  • A little perspective. You would opt for the variable if you want configuration. A quick check at ethgasstation suggests it adds USD $0.003 to the one-time release cost, assuming you would only migrate to mainnet one time. Admittedly more if you also for fast confirmation. Still, I wouldn't call that "very expensive" or compromise my process over that. As a heuristic, I would concentrate on optimizing user-facing functions and making sure costs are scale-invariant. – Rob Hitchens - B9lab Apr 27 at 19:12
  • @smarx yes I would like to know if truffle has anything built-in doe this – Jonah Apr 27 at 19:42
  • Rob, it would save 200 gas each call to get() since it doesn't have to do an SLOAD plus maybe some other benefits of having a getter that's pure. And sure it's only $0.003 but in some cases that's 20% the cost of deploying a contract! And if a user is expected to pay the cost of contract creation, which is true in my case, it's a user-facing issue. – Jonah Apr 27 at 19:53
  • 1
    If you were a client I would explore the goals and constraints with a mind to optimizing the architecture. To answer your earlier question directly, truffle does not have such a thing but truffle isn't relevant in the case that users are deploying contracts from your templates. You may have heard of libraries and something similar but I don't think it applies here. – Rob Hitchens - B9lab Apr 28 at 3:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.