Linking and initializing contracts on deploy automatically

First, you should get familiar with the truffle migrate command that helps you deploy your contracts but also upgrade and redeploy the changed contracts only.

But what about the contracts that depend on other contracts that you are deploying as well? Contracts that are dependencies should be updated with the newly deployed address. You can do this manually during production but what about tests? Let’s dive into a solution.

For example, we have a smart contract called Application that interacts with Storage smart contract. The goal is to deploy them both and update Application contract with the Storage contract’s address.

Here is our Application.sol file:

Example of Application smart contract

And our migration file:

Deployment of Application and Storage smart contracts

The code above creates 4 transactions:

Deployment of the Application contract Deployment of the Storage contract Updating storage address in Application contract Updating Truffle’s Migrations contract that tracks migrations onchain

To save up some gas, you could add constructor to Application contract which would accept address of storage contract as function parameter. Then our example would look like this:

Upgraded Application smart contract

Migration of Storage contract:

Simple deployment of Storage smart contract

And migration of Application contract:

Simple deployment of Application smart contract

This way we will make one transaction less than before and thus save some gas.