This question is a general design question that regards contract correctness and the functions I list here are just examples.
As I develop on Ethereum, it becomes aparent to me that it might be relatively easy to mal-design a contract that deadlocks itself because necessary key functions may suddenly become not callable anymore because their excecution suddenly exceeds the gas limit.
That leads me to the likely difficult question:
How can I assert that a specific function never uses more than a certain ammount of gas? This seems to be a crucial necessity for contract correctness.
For example
function unbound() returns (uint256) {
uint256 total = 0;
for (uint i=0; i < users.length; i++) {
total+= users[i].value;
}
return total;
}
calling this function has undeterministic gas cost and could easily at some point become uncallable. Of course in such a simple example like this it's easy to redesign and calculate this total not in a loop but by other means. But it's not always possible to avoid loops. The question is, how do you write correct functions in that case?
For example, the system might be designed such that there are never more than 6 users, in which case the loop is bound and the execution cost deterministic, so if I have:
function bound() returns (uint256) {
uint256 total = 0;
assert(users.length < 6);
for (uint i=0; i < users.length; i++) {
total+= users[i].value;
}
return total;
}
This function uses a loop but has a deterministic upper bound for gas consumption.
A: How can I calculate the maximum amount of gas calling this function will consume?
B: How can I communicate this maximum to clients of the function?
Can I somehow do something like this:
function bound() returns (uint256) {
uint256 total = 0;
for (uint i=0; i < users.length; i++) {
total+= users[i].value;
}
assert(gasConsumend < 1234);
return total;
}
?
We're writing contracts after all, and pre- and post- conditions are an integral part of design by contract. We can write preconditions with require() and postconditions with assert() - but for correctness on ethereum it seems also necessary to assert a maximum gas consumption. How?