Solidity Fast Track 2: Continue Learning Solidity Fast

Continuing to learn Solidity fast with the advanced basics

Previously we learned all of the basics in 20 minutes. If you are a complete beginner, start there and then come back here. Now we'll explore some more advanced concepts, but again as fast as possible.

Faster Meme

1. Saving money with events

We all know gas prices are out of control right now, so it's more important than ever that you learn the basics of how to use events. Events are not stored in a contract like regular storage, but rather in a special logs section of a transaction. So what is this special logs section?

Under the hood of events: Logs in Ethereum

Logs are an efficient way in Ethereum to check for specific data that's not required for the contract itself, but only for logging purposes. Examples on how those logs could be used are the web3.eth.subscribe functionality or The Graph. A bloom filter is used to improve the performance for Ethereum nodes. It basically works by hashing the specific log data, then computing modulo 2048. This is done for all logs in a given transaction (there's no limit to how many logs can exist in a single transaction).

The result will be a bunch of numbers in the range of 0 to 2047. You can create a bit array (bitmap) with mostly 0's, except on those indices where you got a number for in the previous step. Given this bitmap, a node can very efficiently check for logs in a transaction:

Looking for a specific event? Hash the event, compute the hash modulo 2048 and check if there's a 1 at this index in the bitmap. Most of the times there will be a 0, so we can quickly filter out most of the non-relevant transactions. If there's indeed a 1, we have to inspect the full logs array in detail. Since a max of 2047 numbers will mean some logs give us the same number, we'll have a 0.048% chance for a false positive. That's very low, so the overhead for false positives is close to 0.

After looking through the full logs array, we either find a match to the event we we're looking for and return the data or we don't and ignore this transaction.

Events Meme

Events in Solidity

Now that we understand the fundamentals behind events, how do you use them in Solidity?

contract MyContract {
    event MyEvent(address indexed sender, uint256 timestamp);

    function sendTransactionWithEvent() external {
        emit MyEvent(msg.sender, block.timestamp);
    }
}

You declare any event definitions at the beginning of the contract. Later you can emit events using the emit keyword and passing all parameters to it. Pretty simple and cost effective.

What's the indexed keyword?

You can add up to three parameters with the indexed keyword in one event type. Any indexed parameter will receive its own hashed place in the bitmap, meaning you'll be able to efficiently search for events with specific data in those three parameters.

2. Improving code readability with structs

A very important concept in Solidity are structs. They will allow you to greatly improve the readability of your code. Also since Solidity 0.7 the ABIEncoderV2 is the new default which fully supports structs, so you don't need to worry about passing structs to functions.

Consider our escrow example in the first fast track. It works only for one trade. We can change it to work for any number of traders by keeping the data separately using structs:

Before:

address public seller;
address public buyer;
address public arbitrator;

uint256 public purchasePrice;
uint256 public purchaseConfirmationCount;
uint256 public refundConfirmationCount;

mapping(address => bool) public hasConfirmedPurchase;
mapping(address => bool) public hasConfirmedRefund;

After:

struct EscrowTrade {
    address seller;
    address buyer;
    address arbitrator;

    uint256 purchasePrice;
    uint256 purchaseConfirmationCount;
    uint256 refundConfirmationCount;

    mapping(address => bool) hasConfirmedPurchase;
    mapping(address => bool) hasConfirmedRefund;
}

mapping(uint256 => EscrowTrade) public escrowTrades;

We can now create and access trades conveniently using a trade id. For example you may access the seller via escrowTrades[tradeId].seller. Alternatively you can store the whole trade struct data in its own variable first and later use the data directly:

EscrowTrade memory escrowTrade = escrowTrades[tradeId];
address seller = escrowTrade.seller;

You'll see this pattern all the time in contracts, so make sure to get comfortable with it.

One thing to understand is the difference between EIPs and ERCs. But first what are EIPs?

They stand for Ethereum Improvement Proposal and are just a repository on Github. Anyone can create such an EIP which is supposed to be for proposals regarding the core protocol specifications and client APIs. Very similar to that the ERC stands for Ethereum Request for Comments, the name coming from the RFCs internet standards. Those are proposals for smart contract standards.

As a beginner you probably don't need to care about EIPs too much. Some of them can have significant effects, such as EIP-1559, but only when it's actually implemented and used on Ethereum. By then you will likely read dozens of articles about it and what its implications are.

More interestingly are the ERC's which are standards that would be a good idea to follow in your contracts. Granted there are hundreds if not thousands of ERCs and not all of them are important. It can be tricky to find out which one to use. 

XKCD standards

Tthe Openzeppelin contracts are always a good reference. Let's now explore the most popular ERC of them all: ERC-20.

We already learned all the concepts in this and the previous post to build an ERC-20 contract. An ERC-20 contract is just a simple second currency (token) implementation on top of Ethereum where Ether is an existing implementation. Most popular might be the DAI token, which is a decentralized stable coin worth always about 1 USD.

At its core the the ERC-20 implementation is just this:

contract MyERC20Token {
    mapping(address => uint256) public balanceOf;

    function transfer(address to, uint256 amount) external returns (uint256) {
        require(balanceOf[msg.sender] >= amount, "Not enough balance");

        balanceOf[msg.sender] -= amount;
        balanceOf[to] += amount;

        return true;
    }
}

Pretty simple right? Now the actual standard further contains events, an approval mechanism, a totalSupply function and a few optional fields. Take a look at the standard for the details. Most importantly here the approval mechanism allows to use tokens in smart contract calls:

Imagine Alice wants to use the SuperSmartContract which requires users to pay 10 DAI. Alice can approve the DAI calling DaiToken.approve(SuperSmartContract.address, 10) and subsequently SuperSmartContract.use(). Inside the use() function, the contract can all DaiToken.transferFrom(msg.sender, address(this), 10) and since Alice set the allowance previously, this call is now allowed to transfer money on behalf of Alice to himself.

What else about ERC-20? As you've seen at its core the logic is very easy, but there's a lot more to learn:

4. Libraries

Library Meme

Libraries are special contracts that have no storage, but can be used only for implementation code. There's two different forms of libraries, those with public functions and those only with internal functions. They both serve very different purposes.

First let's talk about libraries with only internal functions. This is the most common form for libraries. You'll see them in packages like Openzeppelin contracts, Uniswap's own library repo or the quite popular ds-math lib.. This is the kind of library that you would use to make your code more readable and I highly recommend you do this yourself whenever it makes sense. Combine this with the using for syntax for maximum benefits.

The simplest example, which with Solidity 0.8+ new safe math feature wouldn't be necessary anymore, would be:

contract MyContract {
    using MyMathLib for uint256;

    function returnSub(uint256 a, uint256 b) external returns (uint256) {
        return a.safeSub(b);
    }
}

The second form with public functions allows for reusability. To quote the Solidity documentation: 'Libraries are similar to contracts, but their purpose is that they are deployed only once at a specific address and their code is reused using the DELEGATECALL.'

So in other words, those libraries can be reused by many projects. After all you might have a lot of standard code that would just be duplicated logic in the blockchain if each contract would have its own version of it. That's at least the theory,  in practice honestly the use of reusable libraries hasn't really taken off. There is at least one project aiming to provide those: https://github.com/modular-network/ethereum-libraries. Otherwise, external libraries can also help to stay below the contract size limit.

Congratulations. You've mastered level 2.

Now that you are at level 2, I can say that you know all important basics by now. After this what to explore next is really up to you. I'll give you a few ideas, but there's a whole big world out there for you to explore.

  • Inheritance: Solidity supports inheritance including polymorphism. A great way to structure your contracts.
  • Hacks: Always a great way to learn about smart contract security.
  • Downsizing contracts to keep below the max contract size (its own EIP-170 btw)
  • Avoiding stack too deep errors
  • Toolings
  • Study more ERC's (+ EIPs)
  • Best coding practices in general! My colleague has a great blog post about naming (important) and another great resource currently 66% discounted is the book Dive Into DESIGN PATTERNS. Or really any other book you can find. Solidity might be a bit strange due to running  on the blockchain, but most programming concepts still apply of course. 

Markus Waas

Solidity Developer

More great blog posts from Markus Waas

© 2024 Solidity Dev Studio. All rights reserved.

This website is powered by Scrivito, the next generation React CMS.