How Tinyman Lost $3 Million

S. Alexander Zaman
Coinmonks
10 min readFeb 1, 2022

--

An autopsy of Algorand’s first big DeFi hack…

Photo by Piron Guillaume on Unsplash

The last quarter of 2021 marked a time of great success in the Algorand community. A great deal of investment was made throughout the year and things were starting to payoff. The basic building blocks of a new DeFi ecosystem have started to emerge on Algorand’s lightning fast network. These building blocks include:

  • USDC Support— Support for the USDC, a USD-pegged stablecoin.
  • AlgoMint — a bridge protocol to have BTC and ETH backed 1-to-1 on the Algorand network. This allows trading and moving ETH and BTC (represented as goETH and goBTC) with Algorand’s fast transaction speeds and low fees.
  • AlgoFi — a money market protocol allowing lending and over-collateralized borrowing. It is also trying to create its own crypto collateral backed stablecoin (STBL).
  • Tinyman — an AMM DEX (automatic market maker, decentralized exchange) allowing token-to-token swaps and liquidity pool (LP) farming on the Algorand network. Uniswap is the most well-known example of an AMM DEX

These essential building blocks reminded me of the early days of Ethereum’s DeFi summer. They are all necessary reagents for a chain reaction that could burst into a powerful new DeFi ecosystem. Without a doubt, Q4 of 2021 was an optimistic time.

However another less palatable lesson that I learned from DeFi summer also emerged again in the Algorand ecosystem: SMART CONTRACT RISK

The New Year brought with it a vicious surprise —One that cost Tinyman an estimated $3 Million dollars.

What is Tinyman

Tinyman.org Homepage

Before going into the hack, it’s important to understand what Tinyman is and how it works. Tinyman, as mentioned above, is a decentralized exchange (i.e., DEX) that utilizes an automatic market maker (AMM).

A DEX is an exchange that is hosted through smart contracts on the blockchain. You use your wallet to interact with the smart contracts and never lose custody of your funds. This is in opposition to a centralized exchange (CEX), such as Coinbase, Gemini, or Kucoin, into which you deposit funds into their custody to trade.

Because DEXes are hosted through smart contracts, it gets all the benefits of the blockchain it is on. On Algorand, these benefits include:

  • Decentralization
  • Self-custody
  • Scalability
  • Censorship resistance
  • Privacy

Smart contract code also shares the same immutability as blockchain transactions. This allows for many of the benefits listed above but comes with the risk of bugs causing catastrophic results. This is known as smart contract risk.

For better or worse, Code is Law

The Tinyman DEX is a special type of exchange that uses a mechanism called an Automatic Market Maker (AMM). Most exchanges trade based off of an order book, or a log of all buy and sell orders that are filled when there is a buy order that is greater than or equal to the lowest sell order.

For there to be liquidity, there must always be someone willing to buy and someone willing to sell. In many exchanges, funds are often set aside for the expressed purpose of being a counterparty to trades and keeping the assets liquid. This is common in the equities world as well as the crypto world, especially but not exclusively, on centralized exchanges. (This link describes how the NYSE does it for example)

AMMs, on the other hand, are a recent innovation created in the blockchain world that price assets on a curve created by a mathematical formula instead of an order book of traders. Instead of relying on assigned market makers, liquidity comes from the liquidity pool, and anyone who funds the liquidity pool is a liquidity provider and gets compensated with trading fees and other incentives.

The takeaway above is that Tinyman is an exchange powered by immutable, directly-accessible smart contracts. Liquidity comes from a pool of tokens and prices are based on a mathematical formula.

Tinyman’s hack relied on these attributes to drain ~$3 Million dollars from the liquidity pool.

The Hack — ELI5 How It Worked

Photo by Hennie Stander on Unsplash

What’s interesting about this hack is that it is clear in hindsight, but easily missed when not looking for it. Here’s a simplified explanation of how it worked. (Credit to u/mCseq for the inspired explanation)

Tinyman has a smart contract that takes in the following.

  • The trading pair (e.g., goBTC vs ALGO)
  • What you expect to give and get (e.g., 1 goBTC for 18,000 ALGO)

The contract checks the going exchange rate and makes sure that the numbers match up. If the numbers do, then it will execute the trade as stated on the request using the liquidity pool for the trading pair.

The smart contract did indeed ensure that the numbers matched up and the AMM formula was accurate. However, there was one devastating thing it forgot to check.

The smart contracts did not check that the token types on the request were different and the hacker exploited this.

Learn By Example

For example, let’s assume that 18 ALGO trades for 0.001 goBTC in the ALGO/goBTC trading pool. A normal request would be as follows:

  • trade on the ALGO/goBTC trading pool
  • request 0.001 goBTC for 18 ALGO
  • the smart contract would process this taking 0.001 goBTC and providing 18 ALGO from the liquidity pool

A malicious request was possible however as follows:

  • trade on the ALGO/goBTC trading pool
  • request 0.001 goBTC for 18 goBTC (*instead of 18 ALGO)
  • The smart contract would obligingly take 0.001 goBTC and pay out 18 goBTC from the liquidity pool, netting the attacker 17.999 goBTC!

The attacker can then adjust for the new rate and repeat this as many times as they want until all the BTC is removed from the pool or the price of ALGO is greater than the price of BTC in the pool.

After they are done, they can then trade the goBTC elsewhere (e.g., turn it into actual BTC through AlgoMint)

Coding Skills Required

The Tinyman website would not facilitate this type of request, but since the public API of the contracts are directly accessible, someone with a little bit of coding acumen could make these calls and run away with the entire BTC supply in the pool.

This, in fact, is what happened in several pools and many Tinyman liquidity pools were drained. What’s worse is that even after Tinyman discovered the issue, they as a company could not do anything about it.

Unlike Binance or Robinhood, Tinyman is unable to arbitrarily block/censor your trades. This is great, but that same mechanism meant they couldn’t block the hacker from exploiting the pools, even after figuring out the flaw.

The only thing the Tinyman team could do is prevent the website from allowing future LP deposits and announce as publicly as possible that LPs should remove their funds from all trading pools ASAP.

The web trading interface was taken down except for the feature to remove liquidity that was already provided. After which, the Tinyman team hustled like crazy to find, create, and audit updated contracts to replace the old ones.

Code Deep Dive — Exploring the Contract

Photo by Florian Olivo on Unsplash

One nice thing about Tinyman’s contracts is that they’re stored in a publicly accessible github repo (link). Thus, when they fixed the issue and upgraded their contracts, it was quite easy to see what they changed, and in turn, what was wrong.

This commit seems to have fixed the issue. Remember that the issue happened because the asset ids were the same in the malicious request.

Granted, TEAL is pretty tedious and difficult to read, but this PR is actually quite straightforward to understand thanks to the notes and the highlighting to focus your attention.

In the code above, the green additions show that a check was added to make sure that the identifiers for asset_1 and asset_2 are now validated.

Since the exploit relied on slipping in the same asset id for both sides of the trade, trying the same malicious request will fail the assertion and not succeed.

Tinyman’s Response

Photo by Diana Polekhina on Unsplash

Quick and Transparent Reporting

One thing Tinyman has done quite well has been to take responsibility and work to restore the assets of those affected promptly. Within a day of discovering the vulnerability, the Tinyman team shut down whatever services they could and published a report on what they knew about the hack.

As a small and burgeoning community, they worked tirelessly, transparently, and with the support of what seems to be the entire Algorand DeFi community.

We’ve been in constant communication with most of the teams in the ecosystem, which have been crucial in helping out with understanding and resolving the problem. We have been in touch with many of our LP’s — Borderless, Arrington, and Meld. It is humbling to get their support during this time and we would like to thank the teams of Algomint, Algofi, Yieldly, Headline Crypto, Tinychart and many of our community members who stepped up to show support and help understand the issue….

(source: Tinyman Blog)

Two further reports (here and here) were issued over the next week with a deep dive into the malicious transactions, how they were used, and their impact. For such a small team, it was great that they were able to produce such a transparent and speedy response.

Remediation

Tinyman has also agreed to take steps to compensate users who were affected by the hack. In their first technical report (here), they identified 250 accounts affected (i.e., were holding goBTC and goETH). The team also committed to making sure to fully compensate those affected accounts.

Our first priority is to take care of our users who lost funds, ensuring we know who those users are and how much was taken. We plan to pay back these users in full. (source)

This is great news for the community. Tinyman was within its capacity to say, “Smart contract risk is real! Caveat Emptor! DYOR!” and restoring only some of the loss, if any at all. However, the protocol demonstrated its commitment and ability to growing a community by agreeing to bear the entire loss.

In their report, the also mentioned that they were looking to help in ways that would boost renewed trust and participation in the community and leaked a small hint about their token launch and how they could use it to reward early adopters who had and continue to take a chance on them.

We are dedicated to doing our best to reward all of our users with the launch of our token. We are thinking about special reward programs that only wallets that had LP positions at the time of the attack can join, making sure the rewards go to the right hands. (source)

https://imgflip.com/memegenerator/57678612/Chapelle-crack

Although, there are still some open questions, when Tinyman will compensate the affected wallets, and how it will compensate wallets from attacks that followed the initial hack, I am generally glad to see that Tinyman took a proactive and seemingly complete approach to helping those that were affected.

Preventing Future Issues

In their reports, Tinyman also committed to take actions that would help catch future issues before they became a problem.

Firstly, before releasing the new contracts, they made sure to have thorough audits completed. Many in the community were stuck in undesirable asset positions for the week and were angry with this decision. However, the extra time spent with this ensures a more secured experience in the future.

Secondly, Tinyman introduced a $100,000 bug bounty program. This incentivizes more people in the community (i.e., white-hat hackers) to help find bugs, while also discouraging more malicious hackers by offering them an easier payoff that won’t have law enforcement on their tail. (details)

A New But Supportive Community

The Tinyman hack quite literally brought Algorand’s DeFi community to a halt for about a week. The community is brand new and basic DeFi building blocks are still being built out in the Algorand ecosystem.

Along with great promise and opportunity, there is also great risk as the protocols need time to battle-harden as they have in communities like Ethereum. Fortunately, the response from Tinyman, official Algorand organizations, and Algorand’s greater DeFi community have shown that Tinyman and the current batch of Algorand DeFi protocols value transparency, responsiveness, and ownership.

Problems such as hacks and vulnerabilities will always exist. It’s those communities that choose to responsibly own up and bounce back with passion that will emerge from these events stronger than before.

Disclaimer:

I am not a financial advisor and views expressed in this article are not financial advice. Cryptocurrencies and smart contracts are complex instruments and come with high risk of losing money. You should carefully consider whether you understand how these instruments work and whether you can afford to take the high risk of losing your money. I encourage you to perform your own research before making any investment decision, and to avoid investing in any financial instrument which you do not fully understand how it works and what are the risks involved.

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

Also, Read

--

--