Solidity Contract Invocation – How to Store a 300+ Character String

bytes32contract-invocationsolidityweb3js

I'm trying to store the following string in a contract

5030480389847504049639477069961901518251822532055915812015454717740961852942027334498786032153069913846973579859702642411497486328669598344496363306620763652362226170692287240855050713537819594000868803228735504934019483458523068727831434237837325563417285328158635879852481735301070609988900677951635437637299660610442447448957534545817

Its size is 337 bytes.

The relevant contract code is

contract User {
    bytes32 publicKey;

    function setPublicKey(bytes32 _publicKey)
        onlyOwner
    {
        publicKey = _publicKey;
    }

    function getPublicKey() returns (bytes32 _publicKey) {
        return publicKey;
    }

}

When I call getPublicKey() after setting it already, using (again only showing the relevant part)

contract.getPublicKey.call((err, res) => {
        if (err) {
            console.log(err);
        } else {
            const k = web3.toAscii(res);
            console.log(k);
        }
    })
}

I just get back 50304803898475040496394770699619, which is the beginning of the string/key. I figure this to be related to exceeding the bytes32 size, but what's the recommended way to get around this?

Also, I should mention I don't want to store this offchain. And also, I'm aware that gas costs to store large data in the blockchain are high but (1) I figure this would still be within an acceptable size and (2) it's a private chain for testing so I am not too concerned with that, for now.

Best Answer

My suggestion would be to use either string or bytes and just to mention there is no limit on the number of characters to store. If you are storing a lot of characters then you may consider increasing gas value. Once you increase gas value then string or bytes both should work.

If you would want to estimate Gas of a transaction then you can take a look at this web3js API -

https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethestimategas