0

I'm trying to find the "best practice" to return a JSON formatted string from a view function.

Basically, I plan to loop through a set of data stored in contract state, build it all into a single JSON string, and return the JSON string for further processing with web3.js. The format would be: "{'address': ['dataTiedToAddress','balance'], 'address2': ['dataTiedToAddress2','balance'], ...}"

I've found a couple question/answers on SO that relate to converting bytes values and addresses to strings (such as here: How to convert an address to bytes in Solidity?), but using the separate conversion functions in addition to string building seems a bit messy. I wasn't sure if there was a better way to do what I'm trying to achieve.

The following are the data types:

address : address

dataTiedToAddress : bytes

balance : uint256

I'm trying to optimize as much as possible; however, since this is a view function only called by an administrative account in a back end process, a larger gas amount/longer processing is not a huge issue. In fact, I anticipate it will take a while due to the size of the data set.

4
  • Without really answering the question, have you considered just doing the processing off-chain? You could get the raw data and do the work off-chain, since your function is not needed(?) on-chain anyway Commented Oct 13, 2021 at 18:40
  • I had considered that to an extent. I still have to get all the addresses in the data set from the chain. Once I have the addresses, I can use other functions in the same contract to pull the data and use web3 to get the balance. Basically it would turn one big function into MANY small calls to the chain. I'm not sure which is more optimal. We're talking potentially hundreds to thousands of addresses and associated data.
    – pdmoerman
    Commented Oct 13, 2021 at 19:14
  • I would guess that 95% of the cases it's better to just download the data and process off-chain. Don't have any references for that, though. And it of course depends on your needs: whether to download 100k items or process on-chain and download 1 item in the end (as an example) Commented Oct 14, 2021 at 4:36
  • Well, the question revolves around getting the data. The data manipulation will be done off-chain, but the issue is getting the giant data set. I was going to try to return the data as JSON, so I easily massage it in JS. The alternative is the one giant view function on-chain returning JSON turns into hundreds of individual calls to get the data piecemeal from view functions. It's the same returned data but a difference of returning it all in one call using JSON or having to get every bit of data with hundreds to thousands of calls.
    – pdmoerman
    Commented Oct 14, 2021 at 19:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.