2

A typical ERC20 token will store account balances in a mapping, something like this:

mapping(address => uint) public balances;

Does this mean that, to do a transaction or check a balance on this contract, I have to have the complete state available? Do I need to have every single balance for this token on my system?

With a blockchain-native token, like Ether or Bitcoin, a light client uses techniques like bloom filters to sync just a small subset of the universe of address balances. But this doesn't seem to be possible for tokens that store balances in a single mapping. What strategies can be employed by contract developers to get similar performance characteristics to a native token?

2

The same "light client" techniques that work for getting ether balances works fine for getting data from a smart contract's storage. See https://github.com/ethereum/wiki/wiki/Light-client-protocol for how this works in Ethereum.

The first use case covers this:

A light client wants to know the state of an account (nonce, balance, code or storage index) at a particular time. The light client can simply recursively download trie nodes from the state root until it gets to the desired value.

  • Does this just apply to mappings? Are there any special considerations when designing a contract? For example, it sounds like a bad idea to iterate over a large array if elements would have to be fetched on demand. – Peter Hall Apr 25 '18 at 15:06
  • Most clients interacting with a contract will do so via JSON-RPC to a remote node, so iteration would already be expensive. The cost of retrieving x[i] is constant, and the cost of retrieving all elements of x is linear with respect to the number of elements. Your node being local/remote and light/full only matters with respect to the constant time of looking up x[i]. – smarx Apr 25 '18 at 15:11
  • I meant Solidity code doing the iteration, perhaps summing them or finding the maximum value. My understanding was that a light client would execute EVM bytecode itself when calling a constant method. Would it have to make remote calls for each element during iteration? – Peter Hall Apr 25 '18 at 15:17
  • I'm not sure. It could be that a light client downloads the full storage for the contract before executing, or it could be that it fetches it on demand, or it could be that it asks the full node to send all the storage necessary to execute the function. (And it could be that it uses a heuristic to decide which strategy to take, and it could be that future versions of node software will change their approach.) – smarx Apr 25 '18 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.