3

i created smart contract and i created contructor like this:

public:
        TestContract(account_name self): contract(self) {
            method1();
            method2();
            print("CONSTRUCTOR\n");
        }

where method1 and method2 are used to set some initial state in table, and since i noticed weird behaviour i put this print inside, and constructor is called whenever action is called via cleos. This is really weird for me, if this is intended behaviour, is there another way to set this initial state in db, only when contract is called for the first time?

1

The contract's runtime environment is created each time an action is triggered, so yeah, your constructor would be called again each time. What you can do to set initial state is a typical programming trick: Check if the data is there already, and if it's not, then set it. That way next time it's called it will see that the data is already there and will leave it as it is.

You can check it using the find method on the table and then comparing the result with the iterator that points to the end of the table. If the iterator returned by find is equal to the end of the table, then it means that it didn't find the data in there.

Documentation of find: https://developers.eos.io/eosio-cpp/reference#find

As shown in that documentation page:

auto itr = addresses.find(N(dan));
eosio_assert(itr != addresses.end(), "Couldn't get him.");
| improve this answer | |

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.