DEV Community

Jamiebones
Jamiebones

Posted on

How To Call Other Contracts In Solidity

This blog post will show how to call the functions of a smart contract from another smart contract. Assuming we have two smart contracts defined below:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;

contract CallContractOne {
  function setValueX() {

  }

}

contract ContractOne {
  uint public x;

 function setX() external {
  //we will want to set the value of x from CallContractOne
 }

}

Enter fullscreen mode Exit fullscreen mode

The first thing to know is, we need to mark the visibility of any function we want to call from outside the contract as external .

To call the smart contract ContractOne from the smart contract CallContractOne. We can decided to initialize the contract we want to call. Let see how this is done :

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;

contract CallContractOne {

function setValueXByInitializing( address _contractOneAddress, uint _x ) public {
     ContractOne(_contractOneAddress).setX(_x);
  }

function setValueXByType(ContractOne _contract, uint _x ) public {
     _contract.setX(_x);
  }

function setValueXByPassingValue(ContractOne _contract, uint _x ) public payable {
     _contract.setXAndReceiveEther{value: msg.value }(_x);
  }
}

contract ContractOne {
  uint public x;
  uint public value;

 function setX(uint _x ) external {
  //we will want to set the value of x from CallContractOne
  x = _x;
 }

function setXAndReceiveEther(uint _x ) external payable {
  //we will want to set the value of x from CallContractOne
   x = _x;
   value = msg.value;
 }

}

Enter fullscreen mode Exit fullscreen mode

Looking at the function above setValueXByInitializing we used the address that ContractOne is deployed to initialize the contract. Once we have initialize ContractOne, we can then call the external methods defined on it.

Another way we can also call external function of another contract is by using the contract we want to call as a type. Take a look at the function above setValueXByType. We are passing ContractOne as a type. This is the address in which ContractOne is deployed.

Passing value to an external contract call

We can pass ether when we call an external contract. Take a look at the function setValueXByPassingValue. This function calls the function setXAndReceiveEther inside ContractOne and forwards ether to it.

You can copy the code and try out on Remix. Deploy both of the contracts and copy the address of ContractOne to use inside the smart contract CallContractOne.

Thanks for reading.

Top comments (0)