How to Read Smart Contracts

The first part in a series of articles on how to read smart contracts. This tutorial is made primarily for enthusiasts who want to learn how to understand the crypto world, but do not have a deep knowledge of protocols, the inner mechanisms of blockchains, etc.

Swap.Net - NFT Aggregator & Exchange
Coinmonks
Published in
9 min readMar 5, 2022

--

This material was created by Alex Kruegger (Telegram: @kruegger), author of the AK74-Lab Telegram Channel. Translated by the swap.net project team.

DeFi basics

Smart Contracts

A smart contract is a code that is executed on blockchain nodes, and the result of the execution (if spelled out in the program) is stored in the blockchain in a special repository — persistence data. The smart contract code, once uploaded to the blockchain, is additionally locked to prevent any accidental or intentional changes to the code.

The smart contract functions can be called from the outside (from the user’s wallet or from another contract) and divide into two large groups:
- Not changing the persistence data (only read from the blockchain)
- Changing the persistence data

Calling the first group of functions does not cost any gas or money and does not go further than the nearest node (Balance of, TotalSupply, Allowance). In BSC scan these functions are under the “READ” tab.

Calling the second group of functions turns into a full-fledged transaction, which is mined, included in the block and the result of which is written to the blockchain (Approve, Transfer, TransferFrom). In BSC scan these functions are under the “WRITE” tab.

State blockchains

Ethereum and Ethereum-based blockchains (Polygon, BSC, etc.) are state blockchains. Each address stores in the blockchain the value of its balance in the native coin of the blockchain (ETH, BNB, MATIC, etc.). Each smart contract stores in the blockchain the values of its persistent variables. The current state of the blockchain is described by the balance of all existing addresses in the network and the current values of persistence variables of all smart contracts in the blockchain.

Accounts

The Seed-Phrase (12 words) that you wrote down when you first created your wallet is turned into a private key using the BIP 39 protocol, which is turned into a public key using the ECDSA (Elliptic Curve Digital Signature Algorithm), which is turned into your address in the blockchain using hashing and trimming.

Seed-Phrase →Private Key →Public Key →Address

You will always get the same address with your balance from the same seed phrase. To transfer your account to another wallet (MetaMask, Trust Wallet, SafePal, Coin98, etc.) you just need to restore your account on the new wallet using the saved seed phrase. Keep this phrase carefully, because it gives full access to your account.

Where are the tokens?

For each account (address), the blockchain stores only the balance of that address in native blockchain coin and that’s it. The balance of your address in each purchased token is stored in the smart contract of that token in the balances table — the address/balance in tokens.

In BSC scan this table is displayed on the “HOLDERS” tab.

Token must be added to your wallet in order for the balance to appear. After adding, the wallet queries the token’s smart contract for the current balance of your account and displays it in the interface.

One address — many chains

Ethereum was the first blockchain built around the ideology of smart contracts. It has spawned many clones that differ from each other only by consensus algorithm and transaction gas. That’s why you can use the same address for BSC, Ethereum, Polygon blockchains.

Imagine standing on the train station holding the 0x…bc19 ticket. There are a lot of platforms around you named Ethereum, BSC, Polygon, etc. Near them are different railroads and trains: on coal, a nuclear reactor, some still pulled by horses. But each stands on rails, there are locomotives and wagons everywhere. And your ticket always sticked to a seat in any wagon on any platform.

To summarize the above

  • The key to account is a Seed Phrase / Secret Key that identifies online address and gives full access to account
  • Token balance is in the Smart Contract of that token
  • You can use one address for all Ethernet-based blockchains
  • A Smart Contract is an inchangable program + variable data stored in a blockchain
  • A Smart Contract has two groups of functions that can be called from the outside — those that do not change the state of the blockchain (READ) and those that change (WRITE)

ERC 20/BEP 20 interface as the basis of a token contract, a breakdown of contract functions.

What is an Interface

Interface — a description of external influences (controls) on some object and object’s reactions to this control.

For example, car driving. The interface is a set of controls (steering wheel, pedals, gear box) and car’s responses to the use of these controls.

ERC-20 Interface

At the moment, many tokens have already been created and are being created every day. We can interact with any token in the same way — send, swap, approve, etc. So how does this unification come?

Token has to “implement” the ERC 20/BEP 20 interface. Implementing means that a smart token contract must contain a define set of functions and parameters with an unambiguous reaction (what a smart contract should do) to each of these functions.

Interface of the ERC20 standard as defined in the EIP.

FUNCTIONS

EVENTS

Each function call has two more parameters:
msg.sender
— address from which the transaction came (who called the function)
msg.value —the amount of tokens (ETH/BNB) sent with the transaction

EVENT — a way to pass information from a smart contract outward, to the web3 program that called the contract. As a checkbox to say that such operation has been made.

Description of ERC-20 functions

Let’s divide 6 functions into two groups:

READ functions (only reading on blockchain):

WRITE functions (changing the blockchain):

To summarize the above

  • There is an ERC-20 standard describing the interface (functions, their parameters and return values) that must implement a smart contract in order to be called a token.
  • If a smart contract implements the ERC-20 interface, then we can use it wherever we can use the token — swap it to DEX, forward it to each other, burn it, etc. And it doesn’t matter at all what the contract actually is.
  • If something looks like a duck, walks like a duck and quacks like a duck, we can use it as a duck, no matter what it actually is

What happens when working with a contract / Example

Example:

  • Ben decides to create his own token. He takes the most standard implementation of ERC20, changes the name, number (1,000), prescribes that all 1,000 tokens must be intended (transferred) to him when creating the contract, and deploys the smart contract into the blockchain.

A Smart Contract performs a builder function (a special function that is executed once when a contract is deployed) that initializes internal variables, creates two empty tables — balances and allowances, then calls the mint function, which creates the first line in the balances:
-
BEN — 1000

And he is finishes the work. The contract is ready.

  • Ben decides to give his friends Ivan and Jake 100 tokens each.

Ben’s wallet initiates two transactions to the smart token contract: transfer(Ivan, 100) and transfer(Jake, 100). In this case, who should be debited with the coins is determined by who sent the transaction — Ben’s balance (msg.sender).

The smart contract simply changes the table by adding two new lines and changing the amount at Ben:
- BEN— 800
- IVAN— 100
- JAKE— 100

  • Ben decides to put the token on the DEXchange, so he goes to the pancake (for example) and creates a Token-BNB liquidity pair (800 tokens — 2 BNB).

Pancake router creates a liquidity pair, Ben transfers 800 tokens and 2 BNB into it, as a result somewhere in the other universe a line CAKE-LP-Token — 2 appears in the BNB contract, and the token contract table now looks like this:
- BEN — 0
- IVAN — 100
- JAKE— 100
- CAKE-LP-Token/Pancake Router — 800
(In BSC scan we can see the liquidity in the holders)

  • Ivan decides to buy another 100 tokens, he goes to Pancake, says “I want to buy 100 tokens for BNB”

The pancake router asks the liquidity pair for the current exchange rate of the token to BNB (using the AMM algorithm) and tells Ivan“It will cost you 0.25 BNB + fee.”

  • Ivan sends 0.25 BNB to Pancake and waits for his tokens.

The panckake router sees that the money has arrived and creates a transaction on the smart token contract: transfer(Kolya, 100) on behalf of the LP pair.

The smart contract fulfils the request by debiting the pair’s account and crediting Ivan’s account. The result:
- BEN— 0
- IVAN— 200
- JAKE— 100
- CAKE-LP-Token — 700

The panckake router sends 0.25 BNB to the other end of the universe and on the other part of the LP pair in the BNB contract the value of the CAKE-LP-Token pair balance increases from 2 to 2.25

  • At this time Jake decides to sell all the tokens and buy Binamon. He goes to the pancake and says: “I want to sell 100 tokens”.

The pancake router asks the LP for the current exchange rate of the token to BNB (using the AMM algorithm) and tells JakeThis will cost you 0.37 BNB + fee.

Then the Pancake asks the smart token contract whether Jake has allowed him (the Pancake) to debit tokens from his account, to do this it asks the smart token contract for the result of the: allowance(JAKE, Pancake-router) function

*Pancake router logically trusts no one, so all debit transactions take place in his name, which is why Jake has to say that he trusts Pancake to debit his token balance*

Jake has not sold anything before, the result = 0. Pancake sees this and draws an “APPROVE” button for Jake in the swap interface.

  • Jake pushes “APPROVE”

Jake’s wallet initiates a transaction to the smart token contract: approve(pancake router, 999999999999999999999), allowing the router to debit his account with as many tokens as he (the router) needs.

*Actually it would be more correct to give permission for each transaction only for the amount of that transaction, but people are lazy creatures and so usually no one bothers and puts the maximum possible number as the number of tokens allowed to be debited. In our example, for simplicity, that’s a lot of 9s.*

The smart token contract performs the operation by adding a line to the allowance table:
JAKE— (Pancake router, 999999999) and generates an Approval event

The Pancake router sees this event and requeries again the smart contract for the result of the function: allowance(JAKE, punk router).

If the smart contract returns 9999999999 and this value is greater than or equal to the amount of the current transaction, then the router will remove the “APPROVE” button from the interface and enable the “SWAP” button. If 0 is returned, the “APPROVE” button does not disappear, the “SWAP” button is still inactive.

  • Jake pushes “SWAP”

The Panckake router commands the LP pair’s BNB part to send 0.37 BNB to Jake and creates a transaction on the smart token contract by calling the transferFrom(JAKE, punk ruther, 100) function.

The Smart Contract checks for an allowance line table allowing Pancake to debit coins from Jakes’ address, finds it and executes the operation.

The table now looks like this:
- BEN— 0
- IVAN— 200
- JAKE— 0
- CAKE-LP-Token — 800

  • Everything worked out, everyone is happy, all the operations have been carried out

To sum up:

  • The tokens are transferred from the balance of the sender of the transaction (usually the user’s wallet) to any other address using the transfer function.
  • The tokens can be sent from any address to any address, only if there is permission through the approve function to debit the address of the debtor.
  • The function approve is called by the owner of the address, who gives permission for another address to debit tokens from his balance.
  • Permission can be viewed via the allowance function.
  • With any transfers, the tokens simply move from one line of the balancesheet to another, never leaving the confines of their smart contract.
  • If you want to pre-approve token sell, then go into the TOKEN smart contract, WRITE tab, look for the APPROVE function there and insert the address of the smart ROUTER contract of the place where you want to swap. In our case this is the address of the Pancake Router: 0x10ED43C718714eb63d5aA57B78B54704E256024E

In this tutorial we have looked at the fundamental things about your accounts, contracts, and seen the main points of interaction between them.
Strongly advise you to take a basic programming course in order to be able to read contract code at a minimum level and understand at least approximately what a particular piece of code does.

A huge thanks from Swap.net team to Alex Kruegger

Author: Alex Kruegger (TG @kruegger), Channel — https://t.me/ak74lab

Translated by SWAP.NET Team
Official site — https://swap.net/
Twitter — https://twitter.com/NFTSwapnet
Discord — https://t.co/uzz0Qt12tf
Medium — https://medium.com/@NFTSwapnet
Docs&WhitePaper — http://docs.swap.net

--

--