I’ve recently been re-learning solidity, consolidating the details, and writing a “Solidity Minimalist Primer” for beginners to use (programming guys can find another tutorial), updated 1-3 times a week.
All code and tutorials are open source at github:github.com/AmazingAng/WTFSolidity
Developers write smart contracts to invoke other contracts, which allows programs on the Ethereum network to be reused, thus building a thriving ecosystem. Many web3 projects rely on invoking other contracts, such as yield farming. In this talk, we will show you how to call the function of the target contract when the contract code (or interface) and address are known.
Let’s start by writing a simple contract, OtherContract, to call it.
This contract contains a state variable x, an event log that is triggered when ETH is received, and three functions:
getBalance(): Returns the ETH balance of the contract.
setX(): external payable function, which can set the value of x and send ETH to the contract.
getX(): Reads the value of x.
We can create a reference to the contract using the address of the contract and the contract code (or interface): _Name(_Address), where _Name is the contract name and _Address is the contract address. Then call its function with a reference to the contract: _Name(_Address).f(), where f() is the function to be called.
Here are 4 examples of invoking contracts:
We can pass the target contract address into the function, generate a reference to the target contract, and then call the target function. For example, we write a callSetX function in the new contract, passing in the deployed OtherContract contract address _Address and setX’s parameter x:
We can directly pass in the contract reference in the function, and only need to change the address type of the above parameter to the target contract name, which is better than OtherContract. The following example implements the getX() function that calls the target contract.
We can create a contract variable and then use it to call the objective function. In the following example, we store a reference to the OtherContract contract for the variable oc:
If the function of the target contract is payable, then we can transfer money to the contract by calling it: _Name(_Address).f{value: _Value}(), where _Name is the contract name, _Address is the contract address, f is the name of the objective function, and _Value is the amount of ETH to be transferred (in wei).
The setX function of the OtherContract contract is payable, and in the following example, we transfer money to and from the target contract by calling setX.
After the transfer, we can observe the change of the ETH balance of the target contract through the Log event and the getBalance() function.
In this talk, we will show you how to create a reference to the contract through the target contract code (or interface) and address, so as to call the functions of the target contract.