Ethereum smart contracts lifecycle

In the previous article we saw how to deploy our first smart contract to the blockchain. In this article we’ll learn a little bit more about smart contracts in Ethereum.

Birth of a contract

When we write a smart contract we might have some operations to do when it is deployed to the blockchain. For example set some variables. Same as classes in an object oriented programing language, smart contracts have also a constructor . The constructor is a function with the same name as the contract.

If you try to deploy this contract, you will see that you have to provide the two arguments to the transactions.

If we deploy the contract to the blockchain, we’ll be able to see that the contract executed the code and when we read the value stored it is equal to our power.

The constructor  is really helpful to customize your contracts at the time you deploy it. A traditional class has most of the the time a destructor which is called when the object is destructed. It’s also possible with contracts.


Who’s who?

When you create a smart contract, you might need to know who is interacting with it at runtime. In the Ethereum blockchain, actors (smart contracts or wallets) are identified by their address . If you want to know the address  that called a function you can access it by using msg.sender . Storing addresses can let you implement logic depending on the transaction creator.

Let’s say we want to improve our Counter contract from the Hello World tutorial and only allow the creator of the contract to be able to update the counter. We’ll need to add two steps, a constructor that will store the address of the creator and a condition in the increment function to make sure it is the creator that call the function.

Here is our Counter contract updated:

So we secured our contract to only allow the initial creator to increment the counter. You can learn more about solidity data types like address here.


Death of a contract

Even the best things have an end and smart contracts can die too! When a contract is killed using the kill function it will not be possible to interact with it anymore. To kill a contract you need to to call selfdestruct(address) . Providing an address as the parameter let you transfer the remaining founds stored in the contract to the address.

When you implement a kill function to destroy a contract, checking the identity of the caller let you protect the contract from getting destroyed by anyone.

In some tutorials you can see people using suicide()  instead of selfdestruct() . The suicide()  function has been renamed in order to have a more healthy language.

So let’s call our kill function:

After few seconds if you try to access your contract, you’ll see that you can no longer interact with it anymore.

We learnt how to write really simple smart contracts. In the next tutorial we’ll see how to create a lottery contract and how to store more data thanks to mapping type.