Cache reads and delay writes in Michelson

Reading and writing to the context is one of the most gas-expensive thing a contract can do.

In some instances though, a contract may need to write an entry in a bigmap, only to have this entry erased after receiving a callback from another contract invoked during the transaction. In other instances a contract may find it easier to directly use the bigmap as working memory rather than maintain its own cache on the stack and flush it at the end of the transaction.

In practice, this is already what happens! Bigmaps are only committed to the context at the end of the transaction, but gas costs are incurred as if every intermediary write was going to end up being reflected in a write to disk.

Gas costs for writing to the context should be computed and incurred at the end of the contract invocation or, even better, at the end of the entire transaction.

It may also be beneficial to offer the same for reads. Reads from bigmaps should be cached so that subsequent reads do not incur an additional cost. Reading a value that has been newly written during this transaction should not incur any IO cost at all.

It’s already possible — but very unwiedly — to avoid much of these costs at the contract invocation level by creating an ad-hoc cache in the stack. It’s however impossible to do it across an entire transaction.

This approach would not speed up contracts (most of this caching already happens) but it would allow contracts to not pay more gas than they ought to and to avoid complex code just so they can lower their gas cost.

9 Likes

I would like to point out the problem with lack of caching of the loaded contract code during the transaction.
It looks like reentry call to a contract incurs loading/deserialization gas cost even though the contract was already being loaded.

Yeah that’s a separate problem but also an easier one to solve. This should go hand in hand with making real entry point so that only the code of the entry point is loaded when called.

For the record, this is being worked on in https://gitlab.com/cryptiumlabs/tezos/-/issues/88

1 Like

If by “this” you mean, “that other thing the person mentioned”, and not “generic caching and buffering of all reads and writes to the context”