0

I am new to solidity :)

I try to create a general contract which its attributes are known at run-time.

Suppose we have the following contract:

contract Product{
     string name;
     uint price;
     constrcutor(string memory _name, uint _price){
            name = _name;
            price = _price;
     }
}

And for the sake of simplicity I would like to create different Product contracts in the tests.

I know that I have to migrate the contract before deploy it, but really - no idea.

I try hard, excuse for me being newbie, I really have no idea how to do it or how to google it :(

0

You probably don't need to create a contract for every new product, as this would be expensive in terms of gas consumption.

You can try something like this:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;

contract ManageProduct {
    
    struct Product {
        string name;
        uint256 price;
    }
    
    Product[] public products;
    
    constructor(){}
     
    function addProduct(string calldata _name, uint256 _price) external {
        products.push(Product(_name, _price));    
     }
}

You just need to define a structure to store the attributes of the product (name, price, etc), and then you can save every new product into an array of products through function addProduct().

Then, you can add other functions to go through this array and retrieve the necessary information. Depending on your needs, you may use a mapping to add an ID for every Product and then access the mapping through the ID instead of looping through all the array.

3
  • My intension is to create a DApp which everyone can post their product, so this must be fully dynamic contract? Maybe it is hard for me to express myself ... – Or ben aba Feb 5 at 16:06
  • With my example, anyone can add as many products as needed. When you declare an array as example[], this is dynamic and it is extended as you add new elements. – Sergi Juanati Feb 5 at 16:18
  • Thank you, I really understand now :) – Or ben aba Feb 5 at 16: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.