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: MITpragmasolidity^0.8.3;contractCallContractOne{functionsetValueX(){}}contractContractOne{uintpublicx;functionsetX()external{//we will want to set the value of x from CallContractOne}}
The first thing to know is, we need to mark the visibility of any function we want to call from outside the contract asexternal
.
To call the smart contractContractOne
from the smart contractCallContractOne
. We can decided to initialize the contract we want to call. Let see how this is done :
// SPDX-License-Identifier: MITpragmasolidity^0.8.3;contractCallContractOne{functionsetValueXByInitializing(address_contractOneAddress,uint_x)public{ContractOne(_contractOneAddress).setX(_x);}functionsetValueXByType(ContractOne_contract,uint_x)public{_contract.setX(_x);}functionsetValueXByPassingValue(ContractOne_contract,uint_x)publicpayable{_contract.setXAndReceiveEther{value:msg.value}(_x);}}contractContractOne{uintpublicx;uintpublicvalue;functionsetX(uint_x)external{//we will want to set the value of x from CallContractOnex=_x;}functionsetXAndReceiveEther(uint_x)externalpayable{//we will want to set the value of x from CallContractOnex=_x;value=msg.value;}}
Looking at the function abovesetValueXByInitializing
we used the address thatContractOne
is deployed to initialize the contract. Once we have initializeContractOne
, 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 abovesetValueXByType
. We are passingContractOne
as a type. This is the address in whichContractOne
is deployed.
Passing value to an external contract call
We can pass ether when we call an external contract. Take a look at the functionsetValueXByPassingValue
. This function calls the functionsetXAndReceiveEther
insideContractOne
and forwards ether to it.
You can copy the code and try out on Remix. Deploy both of the contracts and copy the address ofContractOne
to use inside the smart contractCallContractOne
.
Thanks for reading.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse