Open Protocols

The real beauty of Web 3.0 ecosystem we are building are open protocols. Anyone can tap into dharma loan protocol or 0x protocol exchange contract and get into shared liquidity pool for free. You can mix and match these too, creating completely unique products and markets.

A protocol for fungible tokens (ERC-20) is probably the most successful thus far. It secures about $13 billion across a thousand assets. This protocol is quite simple actually, it defines a transfer function which updates balances in token contract and emits a Transfer event.

But what allows to tap into it is the concept of allowance . A user can approve another account to transfer some amount on her behalf. For example, an exchange calls transferFrom user wallet when the order is filled. It’s programmed not to transfer more than the signed amount even though the allowance is set to -1 (meaning infinity).

Optimization

Like a good Unix tool, Disperse contract does a simple job and does it well, that’s why we shaved off every single bit to optimize for gas costs. A naive implementation of Disperse function might look like this:

disperseTokenSimple(token, recipients, values)

However, it’s not an optimal solution because the aforementioned transferFrom updates allowance on each call in addition to balances. That’s an additional 5000 gas on each transfer.

A better way would be to calculate the total, transferFrom it to the contract address and then distribute the tokens using transfer function. There is no risk of funds being stuck because transactions work in “all or nothing” manner and the state will revert if anything goes wrong.

disperseToken(token, recipients, values)

The cost also depends heavily on whether each recipient has previously had any balance. Zero balance is the worst case because storing a new state entry costs 20,000 gas as opposed to 5000 gas for changing the value.