Initialize a contract

更新时间:
复制 MD 格式

To perform initialization operations when you deploy a contract, you must implement a dedicated method for the initialization logic and explicitly call this method during deployment. The smart contract platform does not perform a default initialization when a contract is deployed.

The following example shows how to use this method.

#include<mychainlib/contract.h>
using namespace mychain;
class DemoContract : public Contract {
public:
  INTERFACE void DemoInit(int32_t a, std::string b) {
    //do something...
  }
};
INTERFACE_EXPORT(DemoContract,(DemoInit))

When you deploy this contract, use the SDK to specify the DemoInit method as the initialization method and provide values for the a and b parameters. The DemoInit method can also be called as a regular contract method.

  • If an exception occurs when DemoInit is executed during deployment, the transaction receipt contains the exception information.

  • If DemoInit executes successfully during deployment, the transaction receipt contains the contract bytecode. For this reason, do not define a return value for DemoInit. The return value cannot be retrieved.

Note: A new contract instance is created and its constructor is called each time a transaction invokes a contract method. For this reason, do not place the deployment initialization logic in the contract constructor. Otherwise, the initialization operation will be executed repeatedly.