How to Call Another Contract Using Solidity
{{learn-solidity}}
It is possible on Solidity to create smart contracts that borrow functions of other contracts. We call the smart contract that does the borrowing the caller smart contract and the smart contract whose function is borrowed the called smart contract.
This article will explain when developers should call another contract and a tutorial through example code.
Why Call Another Contract
One of the biggest advances that Ethereum brought to blockchains was the ability to upload and compute code on-chain. Once these programs, known as smart contracts, are uploaded to the blockchain, they cannot be edited. Anyone can view them and, if coded right, they can be interacted with by smart contracts, even if their owners do not know one another, effectively turning smart contracts into reusable libraries. A smart contract whose owner intended its code to be used for one purpose can be reused by thousands of others for their own use cases via calling.
Another reason that people call other smart contracts is because while programming, their original smart contract reached the size limitation of 24,577 bytes before completion. To workaround this, developers move enough of the functions to a new smart contract such that they are below the byte limit.
Calling Another Smart Contract Example
We have created two example smart contracts below to teach you how one contract can call another smart contract.
Call Contract And Update Values
In this first contract, the value contained in CalledContract is updated by the CallerContract.
Sending ETH with a Call
In this second contract, not only is the x value in CalledContractReceivesEther updated by CallerContractAndSendEther, but ETH will also be sent with the call.
How to learn more about Solidity
Want to learn more Solidity? With the recent acquisition of ChainShot, a Solidity education platform, Alchemy University is offering a 7-week Ethereum developer crash course, originally a $3,000 certification bootcamp, for free to the public. Secure your spot today!
If you are new to development in general, Alchemy's 3-week JavaScript crash course is a great prerequisite before starting an Ethereum bootcamp.