I am building out an Ethereum smart contract that allows users to create listings. Here is part of my contract, the part thatis the culprit of the gas usage:

 struct LiveListing {
     uint id;
     string name;
     string description;
     string condition;
     uint price;
     address buyer;
     address seller;       

 mapping(uint => LiveListing) public liveListingsMapping;
 uint id;

     function createListing(string _name, string _description, string _condition, uint _price) public  { 
         LiveListing memory listing = LiveListing({name: _name, 
         description: _description, 
         condition: _condition, 
         price: _price, 
         seller: msg.sender, 
         id: id,
         buyer: 0x0,
         liveListingsMapping[id] = listing;

When the mapping and my assignment of a listing to an id is commented out, the gas goes from over 1,000,000 to 300,000. Also, the create listing goes from 300,000 to around 21,000-22,000. Any advice? Thank you!


It's not the Mapping that takes a lot of gas; it's the fact that you are storing a lot of data in a large object.

A concept that you should be clear about is that when you store data in Ethereum, it currently has to be stored by every node in the network (excluding light nodes). Therefore, there is a gas cost associated with storing data that increases as the amount of data you want to store increases. The idea is to decentivize storing lots of data on-chain.

Potential solutions Here are some potential solutions to consider:

  1. Think about the datatypes you are using

For example uint is an alias for uint256 - which would allow you to have around 1.1579209e+77 listings.

Do you expect there to be more than 18,446,744,073,709,551,615 listings? If not then perhaps uint64 would be more suitable.

Similarly, is condition more like an enum; could you store 1-2 characters in bytes2 instead of requiring all of the memory used to store a string?

  1. Store some of the data off chain

Do other contracts need to read all of the data? If not, then perhaps the data doesn't have to be stored in Ethereum and can be stored off-chain in IPFS or something similar.

Maybe you could take some inspiration from ERC-721 - that defines a tokenMetadata function and storage standard, for storing token metadata off-chain - and some of the implementing tokens (e.g. CrytoKitties).

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.