windranger-io / windranger-mass-delegation-contracts

Mass Delegation
Apache License 2.0
1 stars 1 forks source link

[Feature] Reduce gas cost #13

Open cyraxred opened 2 years ago

cyraxred commented 2 years ago

https://github.com/windranger-io/windranger-mass-delegation-contracts/blob/main/contracts/MerkleDelegation.sol#L13

considering that DelegateeRecord.percentage is limited to 100_000, it can be changed to uint24. And as DelegateeRecord.delegate is address ( == uint160), then DelegateeRecord will take only 1 slot (24 + 160 < 256) instead of 2 slots, hence write and read gas will be 2 times less

jio-gl commented 2 years ago

Thanks, I think we can use uint64 and leave the whole number as a fraction of 2**64 in case we are delegating to more than 100,000 addresses. Also, there is a thing with precision, because we are using BigNumber off-chain and fractions on-chain we have to double check there are no discrepancies due to the hashing. If we do both on-chain and off-chain (currently on-chain only fraction is checked, not net balance, but can be added).

On-chain calculation vs Off-chain calculation floor(delegator_balance * total_weight * 2^64 / weight_fraction_uint64) == floor(delegator_balance * weight_BigNumber / delegator_total_weight

For example, the total_weight is 100, if the delegator is splitting into 60,28,12 between 3 delegatees.

jio-gl commented 2 years ago

Another solution is to store the total weight also on-chain and then we have the exact BigNumber data to compare with off-chain data.

jio-gl commented 2 years ago

Also, the percentage or weight is only used in the verification that is a view function, so not sure it will impact gas costs.

https://github.com/windranger-io/windranger-mass-delegation-contracts/blob/jo-delegate2/contracts/MerkleDelegation.sol