Calling Other Contracts
Contracts become powerful when they work together: an exchange calls token contracts, a vault calls a price feed, a game calls an NFT contract. You have already done this many times in Main. This lesson looks at the options in detail: typed calls, low-level calls, staticcall, and what can go wrong.
Typed calls
If you know the target's type (its contract or interface), call it like an object. The compiler checks argument types, encodes the call, and decodes the return values:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
interface IInventory {
function stockOf(string calldata item) external view returns (uint256);
function take(string calldata item, uint256 qty) external;
}
contract Inventory is IInventory {
mapping(string => uint256) private stock;
constructor() {
stock["apple"] = 10;
stock["pear"] = 2;
}
function stockOf(string calldata item) external view returns (uint256) {
return stock[item];
}
function take(string calldata item, uint256 qty) external {
require(stock[item] >= qty, "out of stock");
stock[item] -= qty;
}
}
contract Shop {
IInventory public immutable inventory;
constructor(IInventory inv) {
inventory = inv;
}
function order(string calldata item, uint256 qty) external returns (uint256 left) {
inventory.take(item, qty); // external call
return inventory.stockOf(item);
}
}
contract Main {
function main() external {
Inventory inv = new Inventory();
Shop shop = new Shop(inv);
console.log("apples left:", shop.order("apple", 3));
console.log("pears left :", shop.order("pear", 1));
shop.order("pear", 5);
}
}apples left: 7
pears left : 1
main() failed: reverted with reason: out of stock
When inventory.take reverts, the revert bubbles up through Shop to Main, with the original message.
Sending ether and gas with a call
Call options in braces set the ether sent and, optionally, a gas limit: target.deposit{value: 1 ether, gas: 50_000}(). Limiting gas is rarely needed; the main use is with untrusted callees.
Low-level call
address.call(data) sends arbitrary bytes. It never reverts by itself: it returns (bool success, bytes memory returnData), and you decode the result yourself with abi.decode.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Converter {
function toCelsius(int256 fahrenheit) external pure returns (int256) {
return (fahrenheit - 32) * 5 / 9;
}
}
contract Main {
function main() external {
address conv = address(new Converter());
bytes memory data = abi.encodeCall(Converter.toCelsius, (212));
(bool ok, bytes memory ret) = conv.call(data);
require(ok, "call failed");
int256 celsius = abi.decode(ret, (int256));
console.logInt(celsius);
(bool ok2, ) = conv.call(abi.encodeWithSignature("missing()"));
console.log("call to missing function ok?", ok2);
}
}100
call to missing function ok? false
abi.encodeCall is type-checked, so prefer it over abi.encodeWithSignature("toCelsius(int256)", 212), where a typo in the string compiles fine and fails at runtime.
Warning: A low-level
callto an address without code succeeds and returns empty data. Typed calls protect you by checking that the target has code first; with low-level calls, checktarget.code.length > 0yourself when it matters.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
interface IThing {
function ping() external;
}
contract Main {
function main() external {
address empty = address(0xDEAD); // nothing deployed here
(bool ok, bytes memory ret) = empty.call(abi.encodeCall(IThing.ping, ()));
console.log("low-level call ok?", ok, "returned bytes:", ret.length);
IThing(empty).ping(); // typed call: reverts
}
}low-level call ok? true returned bytes: 0
main() failed: reverted without a reason
The typed call reverts without a reason: the compiler-generated check found no code at the address.
staticcall
staticcall is a call that is forbidden to change state. The compiler uses it automatically when you call a view or pure function. If the callee tries to write anyway, the call fails, which guarantees read-only behaviour:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Box {
uint256 private value = 7;
function get() external view returns (uint256) { return value; }
function setValue(uint256 v) external { value = v; }
}
contract Main {
function main() external {
address box = address(new Box());
(bool readOk, bytes memory r) = box.staticcall(abi.encodeCall(Box.get, ()));
console.log("read ok?", readOk, "value:", abi.decode(r, (uint256)));
(bool writeOk, ) = box.staticcall(abi.encodeCall(Box.setValue, (99)));
console.log("write in staticcall ok?", writeOk);
console.log("value still:", Box(box).get());
}
}read ok? true value: 7
write in staticcall ok? false
value still: 7
External calls are trust boundaries
Every external call hands control to code you don't control:
- It can revert, so your function may fail with it.
- It can use a lot of gas.
- It can call back into your contract before your function has finished (reentrancy).
- If its address came from user input, it can be any code.
Write calls so that your contract is in a consistent state before the call, and validate returned values. The security lessons go deeper.
Test yourself
What does (bool ok, ) = target.call(data); do when the callee reverts?
- Reverts the caller too
- Returns ok = false and continues
- Retries the call
- Returns ok = true with empty data
Why prefer abi.encodeCall(C.f, (x)) over abi.encodeWithSignature("f(uint256)", x)?
- It produces shorter data
- The compiler checks the function and argument types
- It works without an ABI
- It's the only way to send ether
What does a low-level call to an address with no code return?
- It reverts
success = truewith empty return datasuccess = false- The address's balance