0

Would it be optimal to set variables within a smart contract using the constructor or using different set methods? Where would you use each case? I'm assuming setting them in the constructor would save fees since you don't need to keep calling functions within the smart contract.

1 Answer 1

0

It's not a single solution for every situation. Consider what the contract is intended to finalize and where the users are required to place their trust.

Here's a simple example. Consider a contract that is meant to split all incoming funds according to a ratio, e.g. 80/20.

Consider the two options:

  1. Everyone knows it's 80/20 and everyone is powerless to change it.
  2. It starts out as 80/20 but someone, somewhere can change it later.

It might be sane to pass those numbers into the constructor in any case and have a little check to ensure the input is valid so we don't ever end up with a nonsense contract. You could squeeze the last drop of gas out it, but the more cautious approach might be to check that two inputs add up to 100. I also omitted SafeMath intentionally for brevity.

contract SplitIt {

  uint aPercent;
  uint bPercent;

  function SplitIt(uint aPortion, uint bPortion) public {
    require( aPortion+bPortion == uint(100));
    aPercent = aPortion;
    bPercent = bPortion;
  }
...
}

That might be a good start for both scenarios. In the first scenario, you could simplify the initial deployment by hard coding the defaults:

function SplitIt() public {
  aPercent = uint(80);
  bPercent = uint(20);
}

Now, the question is, should anyone be able to change it later? If so, then you'll need a function that can do it, probably protected by guards to ensure only a privileged user can do it.

Hope it helps.

1
  • 2
    I’d like to add a side note to Rob’s answer: if ever in your life you shall need to split 80/20 funds, be sure to have aPortion = (80*funds)/100; and bPortion = funds-aPortion; NEVER use bPortion = (20*funds)/100; or a little amount of funds may be lost at every run for problems related to roundup.
    – Rick Park
    Dec 22, 2018 at 5:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.