DeFi’s three-tiered scheme

Without a clear understanding of this three-tiered structure it would be difficult for you to visualise the whole DeFi technical ecosystem. Without that vision, you’ll still mess up metamasks, punkies, blockchains, and other unknowable stuff in your head.

Swap.Net - NFT Aggregator & Exchange
Coinmonks
Published in
12 min readMar 19, 2022

--

Blockchain — the first tier

Let’s remember what do we have:

State-oriented blockchains

  • Etherium and blockchains based on it (Polygon/Matic, BSC, etc.) are state-oriented blockchains;
  • Each address stores the value of its balance in the blockchain’s native coin (ETH, BNB, MATIC);
  • Each smart contract stores the values of its persistent variables;
  • At the current point in time (Block X), the state of the blockchain is described by the balance of all existing addresses in the network and the current persistence variable values of all smart contracts in the blockchain.

The whole essence of the blockchain is reflected in its current state; its primary purpose is to store a history of changing states, a history that is immutable, distributively stored and completely transparent.

In blockchain, it is impossible to hide anything. The only unsolvable problem within blockchain is the personification (de-anonymisation) of a particular wallet address. Everything else — balances, transactions, all transfers, contract calls and so on and so forth — can be traced, analysed and drawn some conclusions.
There are also specific tools that perform such analysis of the blockchain(s) for example to identify fraudulent schemes or other interesting interactions using specialised graph databases. Blockchain state, as discussed above, is the aggregate of all current all existing addresses in the blockchain plus the long-term (persistent) memory state of all smart contracts living (encapsulated) in the blockchain.

In other words, the state of a blockchain is an instantaneous (within the current block) snapshot of its long-term memory, in which all information is currently stored. Most importantly, apart from the blockchain, this information is not stored anywhere else.

Metamask or TrustWallet does not store your coins, it is impossible to withdraw BNB from Binance to Metamask, the fact that you first see your BNB in Binance’s balance and then in your Metamask is just a reflection of the current state of the blockchain as recorded in its current blockchain. That is, your funds were first in Binance’s custodial account, and then they have moved by transaction to your single non-custodial address, which you yourself have set up in your Metamask.

So, the blockchain is a repository of information about its state, you could say it holds a master copy. Apart from the blockchain, this information is not stored anywhere else.

Transactions

So, all the information currently available is stored in the blockchain and is called the current state of the blockchain. So how and by what does the state of the blockchain change?

The primary and only force that can change the state of a blockchain is a transaction. It is the only thing that can change wallet balances or alter the long-term memory of a smart contract. Once miners have included a particular set of transactions in the next block, smeared it and included it in the chain — the state of the blockchain has irrevocably changed.

What do we know about transactions:

  • Every transaction from your address (account) must be signed with that account’s secret key;
  • The wallet ALWAYS requires the user to confirm actions — sign the transaction, send the transaction, allow the site to access the wallet, etc.;
  • The only way to complete a transaction without user approval is to know the account’s secret key and generate the signature and transaction programmatically.

There is no such thing as an ownerless transaction. Any transaction on the network is always initiated from a wallet address. A smart contract cannot initiate a transaction, but it can (as part of the transaction request from the wallet) make so-called internal calls, pulling methods from other contracts, sending coins, etc. But all these actions will be performed within the framework of the initiating transaction and within the strict limits of the gas that the user has allocated to the original transaction.

The sender (initiator) of a transaction can always be checked for validity by signing the transaction with the wallet’s secret key. So whoever knows the secret key is the owner. This is why it is very important to keep your mnemonic phrase and private wallet keys secret.

Any transaction does one of two things — transfers a native blockchain coin between wallets (a standard transaction) or invokes some method of some smart contract (a smart contract transaction).

Or does both at the same time. In either case, the state of the blockchain changes (can change) after the transaction is executed. A smart contract transaction can entail a chain of internal calls (internal transactions) executed on behalf of the smart contract being called. But the initiator of the whole chain will still be the sender of the original transaction.

So, the state of the blockchain can only be changed by a correctly generated, signed and included transaction in the blockchain.

SmartContract— the second tier

Basics

  • A smart contract is software code that is executed on blockchain nodes, and the result of the execution (if spelled out in the software) is stored in the blockchain in a special repository. Let’s call the data stored in the blockchain persistence data.
  • The smart contract code, once poured into the blockchain, is additionally fixed to prevent any accidental or intentional alteration of the code.
  • Smart contract functions can be triggered externally (from the user’s wallet or from another contract) and divided into two large groups:
    - Not changing the state of persistent data (read only);
    - Changing the state of persistent data.

Calling the functions of the first group costs no gas or money and goes no further than the nearest node to which we are hooked (Balance Of, TotalSupply, Allowance). In blockchain scanners, these functions are listed in the READ tab of the contract.

A call to the second group of functions becomes a full-fledged transaction, which is mined, included in the block and the result written to the blockchain. (Approve, Transfer, TransferFrom). In blockchain scanners, these functions are listed in the WRITE tab of the contract.

Advanced

  • Since the contract code is fixed, we cannot change it, but we can change the state of the variables stored in the persistence store.
  • The contract can read the value of these variables and make a decision based on the values read — whether or not to execute the code, whether or not to execute the transaction, etc.
  • If there are external functions in the contract that change the value of such variables, let’s call these functions “levers” by which the administrator (usually the current owner or “owner” of the contract) can change the behaviour of the contract.
  • All such levers will necessarily be present on the WRITE tab of the contract.
  • The contract itself never initiates anything. It lives passively in the blockchain and waits to be called. All contract functions are called externally, either by a transaction from a regular address or from another contract, but also only as a continuation of the initial transaction.
  • Ordinary transactions to a contract are visible on the TRANSACTIONS tab, while contract-to-contract requests (Message calls) live on the INTERNAL TRANSACTIONS tab.

So what have smart contracts brought?

Living in a blockchain where only transactions-transfers between wallets are possible is quite boring and reminiscent of regular accounting. However, BTC exists quite successfully and looks down on all these newfangled smart contracts, bridges, parachains and other interesting things.

So what have smart contracts brought to a quieter accounting life? They have transformed blockchain from an accounting ledger into a cloud data centre. Each smart contract is essentially hard-determined software code that has an address (blockchain domicile) and an ABI — a described format for calling smart contract functions.

As a reminder, a smart contract embedded in a blockchain is by definition an immutable entity. It will continue to work even if half the earth is in ruins, as long as the blockchain’s nodes live. Just imagine — at the moment, there are hundreds and thousands of programs on the blockchain, ready to run, that can be accessed by anyone, as long as they know their interface (ABI).

For example on Ethereum, you can even now call the cryptokitties contract to read some data from it, you can trigger a contract method that has not been called in a couple of years — and if the call is valid, the contract will wake up, execute the request and give you the result.

For example, you can pull a pancake factory contract and ask it for a particular LP pair — whether it exists or not. If it exists, then you can ask the contract of the already specific pair for the current reserves — get them and calculate the instantaneous price.
Then you can go to the contract pancake router and request him to exchange your BNBs for this token, with slippage, specifying the required minimum amount, etc. Then send him your BNB and get the tokens back.
Doesn’t that remind you of anything? Well of course — it’s the classic version of buying tokens on the pancake via the web interface. Only we have done it all by hand, calling up certain functions of the various contracts.

Next, you need to sell your token there on the pancake.
Again, we go to the TOKEN contract, look for the APPROVE function in the WRITE tab and call it with the parameters of the router’s pancake address and the number of tokens we are allowing to be deducted from our balance. Then we go to the router contract again and call the reverse buy function — change our tokens to BNB. We start the transaction, wait, the tokens are sold and the BNB has arrived at our address.

Note that we do all this manually, without using the web interface, either through the WRITE tab of the respective contract in the blockchain explorer (bscan, polygonscan, etc. ) with confirmation and signature of our transaction in metamask, or generally from a script in anything with signing and sending through program code without using metamask in principle.

So, a smart contract is a program that lives in a blockchain and is capable of doing more intelligent work than simply transferring coins from wallet to wallet. Called smart contract methods are capable of changing the state of the blockchain, and can be called from either a blockchain explorer or high-level language program code.

Web Interface — the top level

So why do we need a web interface?
We are used to communicating with the DeFi / DApp world through various web faces — swap sites, farming sites (similar to each other like two peas in a pod), bridges and so on and so forth. Very convenient, all at the click of a button, all clear and beautiful.

In order to understand the essence of what is going on, you need to realise and remember two simple things:

  • Any web interface is merely a window visualising the state of the blockchain;
  • Any web interface is just a convenient layer to call up the functions of the various smart contracts.

There is essentially nothing else in the web interface. There is no information stored there (all information is stored in the blockchain), there is nothing but some template to visualise the state of the blockchain and code to call certain functions of certain contracts when the user does something (clicks a button, etc.). And the confirmation of these actions (signing and sending the transaction) must be provided explicitly by the user by pressing the buttons in the metamask pop-up window.

There lurks one danger here, which we’ve already discussed— if you connected to a scam site, clicked “GIVEAWAY 100 BTC” and confirmed the transaction in metamask, and then all the money flew off your account somewhere — you’ve shot yourself in the knee. Scam site can put any transaction on this button, by confirming it you have actually signed off on the actions that led to the zeroing of the balance. How to prevent this from happening you can read here.

So, any web interface is just a convenient window for displaying the state of the blockchain and invoking various smart contract functions to change it (the state).

Let’s summarise

So, a look at DApps and blockchains tells us that:

  • State blockchains store all available information in a snapshot of their current state, recorded in the current blockchain;
  • This information includes account balances and persistence memory status of all smart contracts living on the blockchain;
  • All state information is stored in blockchain and only in blockchain. Neither wallets, nor websites, nor anyone else;
  • From this rule, by the way, all the previous ones are easily derived, e.g. that some token’s wallet balances are stored in that token’s smart contract, etc.;
  • The only method of changing the state of the blockchain is to have a transaction signed and included in the current mined block;
  • A transaction may involve the transfer of a native blockchain coin from address to address and/or the calling of some function of some smart contract;
  • Execution of a smart contract function can lead to changes in the state of its persistent memory, and generate additional transactions, which in turn can also lead to changes in state;
  • Any web interface is nothing more than a window for visualising the current state of the blockchain, as well as a convenient interface for calling up the various functions of the various contracts;
  • All actions you perform with smart contracts through the interface can also be performed by direct calls to the relevant smart contract functions using blockchain explorers or high-level language scripts.

Let’s look at the last point in more detail. In simple terms, you can do the following without using the slow and often glitchy web interface:
- Buy token on exchange;
- Sell token on exchange;
- Approve the token contract to the router to be able to sell;
- Approve coin contract (BUSD, USDC) to presale contract to buy tokens at presale more quickly;
- Claim your tokens.

All you need to know is the address of the contract and its ABI (application binary interface) or in other words the name of the contract methods with their parameters and return values. For established contracts such as swap router, LP pair, token contract, etc. ABI can easily be found on google or (if the contract source is posted) in explorer under the CONTRACT tab.

For custom contracts, if the source code and ABI are loaded, then all the information is also in the explorer tab CONTRACT. But if the source code is missing and we do not have tabs WRITE and how to get directly to this contract is unclear. But two things can be done here:

  • Decode the binary code of the contract (we discussed this in the first workshop) and pull out the name and parameters of the function of interest;
  • Or look in the explorer at a legitimate transaction with a legitimate function call and the correct parameters already executed by someone (via the web, for example).

In any case, you can write your own ABI for this function with a couple of simple conversions and a little patience and load it into the script and use the script to call this function. The explorer won’t work anyway, but the script will.

Note:

Sometimes, however, a web interface is needed. This happens if the transaction body (its parameters and contents) is generated according to some secret rules in the backend of the interface and transmitted to the contract in encrypted form.

If, at the same time, the contract is posted without source code and decompiling it to reverse the validation function is quite a challenge — then we have a situation where we need a web face to get the correct payload of the transaction.

No, you can perform the transaction itself to the contract method, but without this secret piece of data you will simply be rejected. An example is LZPad, which generates just such a tricky transaction when subsuming a presale. DXSale, for example, is simpler, you can easily write a bot for quick purchase, KoalaPad also without any frills, the main thing is to find a presale contract, etc.

To be continued…

In the next section, we will look at how to get around without an interface, just knowing the code and the necessary functions. Strongly advise you to take a basic programming course to be able to to read a minimum amount of code and understand at least what a particular piece of code does.

A huge thanks from Swap.net team to Alex Kruegger (TG @kruegger), Channel — https://t.me/ak74lab

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

Join Coinmonks Telegram Channel and Youtube Channel learn about crypto trading and investing

Also, Read

--

--