visit
If you’re a Solidity developer, you’ll be excited to hear that Truffle now in Solidity smart contracts. While Truffle has long been a leader in smart contract development tooling—providing an easy-to-use environment for creating, testing, and debugging smart contracts—a directly integrated console.log was a feature it still needed.
console.log("Console Logging: The Smart Contract Developer's Best Friend");
$ npm install -g truffle
After a successful installation, I suggest that you modify the truffle configuration file (i.e. truffle-config.js) as follows:
module.exports = {
. . .
solidityLog: {
displayPrefix: ' :', // defaults to ""
preventConsoleLogMigration: true, // defaults to false
}
Now you’re ready to try it out! Import the contract.sol contract into your Solidity code as usual. Now you’re ready to use the console.log() command as you would in JavaScript.
This includes using string like %s and %f.
pragma solidity ^0.8.9;
import "truffle/console.sol";
contract BookStore {
//...
function transfer(address to, uint256 amount) external {
console.log("Transferring %s tokens to %s", amount, to);
require(balances[msg.sender] >= amount, "Not enough tokens");
balances[msg.sender] -= amount;
balances[to] += amount;
emit Transfer(amount, to, msg.sender);
}
}
The above transfer function shows console.log in action. Imagine a call to the transfer function failing with the “Not enough tokens” error. The console.log line, in this case, will show the number of tokens the call is trying to transfer. This allows the developer to see the address and amount of tokens being transferred. The message will look like this.
...
Transferring 10 tokens to 0x377bbcae5327695b32a1784e0e13bedc8e078c9c
An even better way to debug this could be to add in the balances[msg.sender]
into the console.log statement or print it out on a separate line. That way, the sender’s balance is visible in the console, too. You get the point!
While console logging is a powerful tool for debugging smart contracts, keep in mind that Truffle offers other debugging tools as well. Truffle has a powerful built-in debugger CLI tool that can be used to step through the execution of a smart contract and inspect the state of variables at different points in the execution. Additionally, events are a nice way to log messages and track the behavior of a smart contract.
The bottom line is that the console.log feature—in combination with the other debugging tools in Truffle—can provide a better developer experience, thanks to its simplicity and ease of use. It gives developers the ability to quickly and easily log messages and monitor the behavior of their smart contracts, while the other debugging tools can be used for more advanced debugging and troubleshooting.