0

I have a scenario where I need to store N no. of document hashes in a smart contract with some key(id). And also fetch the particular document hash by it's key. Any help on designing the structure for storing would be appreciated. Thanks

1

Here's a rough version:

pragma solidity ^0.4.24;

contract Test {

    mapping(uint256 => string) hashes;

    function addDoc(uint256 id, string hash) public {
        hashes[id] = hash;
    }

    function getDoc(uint256 id) public view returns(string) {
        return hashes[id];
    }
}

Here you can store and retrieve the hashes based on a uint256 id. The mapping will store as many id<->hash values as you need.

What you should do next is change the string types to be something else (bytes of some length) and consider adding some mass-add function if you need to store multiple hashes at the same time.

  • Thank you for the answer. This adds one key-value pair at a time, but I need to add multiple key-value pairs at the same time which will return one transaction Id. If I run a loop from front-end it will give me different Ids on each request that means I have to run a loop at contract itself? – Anubhav Gupta Sep 10 '18 at 10:14
  • As I already stated in the answer, you can consider adding some functionality to add multiple hashes within the same transaction. There are a lot of things you can continue with to make your contract better but I can't write you all of it. – Lauri Peltonen Sep 10 '18 at 10:18
  • I understand Lauri, but it would be really helpful if you can at least guide or suggest me, what could be used here for mass-adding. – Anubhav Gupta Sep 10 '18 at 10:28
  • Add a function which accepts a string[] parameter and loop over the contents to add each separate item. Or, even better, use bytes: ethereum.stackexchange.com/questions/17094/… – Lauri Peltonen Sep 10 '18 at 10:41

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.