helix-onchain / filecoin

Collection of libraries to implement common patterns and standards on the Filecoin Virtual Machine
Other
16 stars 14 forks source link

Optimise allowance data into same HAMT as balances #188

Open anorth opened 1 year ago

anorth commented 1 year ago

Instrumentation and profiling of the built-in datacap actor has revealed that the gas cost of token transfers is dominated by OnBlockLink, which is a mostly-fixed charge associated with writing a new storage block. This and associated charges vary only very little with the number of bytes written.

The fungible token's TransferFrom operation loads and mutates two HAMTs with the same key: the owner's balance, and the owner's approvals. We could nearly halve this component of gas cost by moving the items into the same HAMT. The cost of writing redundant bytes when updating only one of the values would be fairly negligible, but the saving from writing the HAMT root and intermediate blocks only once is quite large.

There's another HAMT of delegate->amount values in there too. I expect for nearly all cases, we'd be better off just moving this inline as a vector. Only one entry would typically be updated at a time, but redundantly writing the others back would be nearly free, compared with writing another HAMT node. The set of delegates for an owner is likely to be typically small (~10s or less). A powerful implementation would be able to fall back to an HAMT once there were too many entries for the vector to be efficient, but I don't think we need to block on that. For the datacap actor at least, the vector will probably be fine.