Skip to main content

Use Interfaces Instead Of Importing Full Code

Description

When developing smart contracts, it's common to interact with other contracts on the blockchain. In Solidity, you can import other contract code into your contract using the import statement. However, importing full code can add unnecessary bloat to your contract, which can increase gas costs and slow down deployment.

Instead, you can use an interface to interact with the necessary functions of the other contract. An interface is a contract-like definition that specifies the functions that can be called, but it doesn't contain any implementation code. By using interfaces, you can reduce the size of your contract and minimize gas costs.

Example Code

import "./Token.sol";

contract MyContract {
Token token;

constructor() {
token = Token(address(0x123...));
}

function transferTokens(address to, uint256 amount) public {
token.transfer(to, amount);
}
}

Instead, you can create an interface for the transfer function in the Token contract:

interface TokenInterface {
function transfer(address to, uint256 amount) external returns (bool);
}

contract MyContract {
TokenInterface token;

constructor() {
token = TokenInterface(address(0x123...));
}

function transferTokens(address to, uint256 amount) public {
token.transfer(to, amount);
}
}

Recommendation

Using interfaces instead of importing full code can help optimize your contract and reduce gas costs. When interacting with other contracts, consider creating an interface that specifies only the necessary functions you need to call. By doing so, you can reduce the size of your contract and minimize deployment and execution costs.