Solidity

Solidity

Contract-oriented, high-level language for implementing smart contracts.
Teagan  Taylor

Teagan Taylor

1673650560

Hardhat-based Template for Developing Solidity Smart Contracts

Hardhat Template

A Hardhat-based template for developing Solidity smart contracts, with sensible defaults.

Getting Started

Click the Use this template button at the top of the page to create a new repository with this repo as the initial state.

Features

This template builds upon the frameworks and libraries mentioned above, so for details about their specific features, please consult their respective documentations.

For example, for Hardhat, you can refer to the Hardhat Tutorial and the Hardhat Docs. You might be in particular interested in reading the Testing Contracts section.

Sensible Defaults

This template comes with sensible default configurations in the following files:

├── .commitlintrc.yml
├── .editorconfig
├── .eslintignore
├── .eslintrc.yml
├── .gitignore
├── .prettierignore
├── .prettierrc.yml
├── .solcover.js
├── .solhintignore
├── .solhint.json
├── .yarnrc.yml
└── hardhat.config.ts

GitHub Actions

This template comes with GitHub Actions pre-configured. Your contracts will be linted and tested on every push and pull request made to the main branch.

Note though that to make this work, you must use your INFURA_API_KEY and your MNEMONIC as GitHub secrets.

You can edit the CI script in .github/workflows/ci.yml.

Conventional Commits

This template enforces the Conventional Commits standard for git commit messages. This is a lightweight convention that creates an explicit commit history, which makes it easier to write automated tools on top of.

Git Hooks

This template uses Husky to run automated checks on commit messages, and Lint Staged to automatically format the code with Prettier when making a git commit.

Usage

Pre Requisites

Before being able to run any command, you need to create a .env file and set a BIP-39 compatible mnemonic as an environment variable. You can follow the example in .env.example. If you don't already have a mnemonic, you can use this website to generate one.

Then, proceed with installing dependencies:

$ yarn install

Compile

Compile the smart contracts with Hardhat:

$ yarn compile

TypeChain

Compile the smart contracts and generate TypeChain bindings:

$ yarn typechain

Test

Run the tests with Hardhat:

$ yarn test

Lint Solidity

Lint the Solidity code:

$ yarn lint:sol

Lint TypeScript

Lint the TypeScript code:

$ yarn lint:ts

Coverage

Generate the code coverage report:

$ yarn coverage

Report Gas

See the gas usage per unit test and average gas per method call:

$ REPORT_GAS=true yarn test

Clean

Delete the smart contract artifacts, the coverage reports and the Hardhat cache:

$ yarn clean

Deploy

Deploy the contracts to Hardhat Network:

$ yarn deploy --greeting "Bonjour, le monde!"

Tips

Syntax Highlighting

If you use VSCode, you can get Solidity syntax highlighting with the hardhat-solidity extension.

Using GitPod

GitPod is an open-source developer platform for remote development.

To view the coverage report generated by yarn coverage, just click Go Live from the status bar to turn the server on/off.


Download details:

Author: paulrberg
Source code: https://github.com/paulrberg/hardhat-template

License: MIT license

#solidity #smart-Contracts #blockchain #bitcoin #web3 

Hardhat-based Template for Developing Solidity Smart Contracts
Keith  Evans

Keith Evans

1673527140

Web3j Sokt: A Kotlin Wrapper for The Solidity Compiler (solc)

Sokt

Sokt is a Kotlin wrapper for the Solidity compiler (solc). Given a solidity file, it can identify the ideal compiler version to use from the pragma statement at the top of the file. It can then download, install and invoke the compiler. Rather than using Dockerized versions of Solc, Sokt uses native builds and is compatible with Mac, Windows and Linux (x86/64 only). This means that the only dependency is a Java installation. Sokt also plays nicely with GraalVM, eliminating the Java dependency if necessary.

Sokt is currently under active development. You can use it in one of your own projects by adding the following dependency to your build.gradle:

dependencies {
    compile group: 'org.web3j', name: 'web3j-sokt', version: '0.2.1'
}

For other build systems, see here.

Example usage:

val fileName = filePath.substringAfterLast("/")
println("sokt Processing $fileName")
val solidityFile = SolidityFile(filePath)

println("Resolving compiler version for $fileName")
val compilerInstance = solidityFile.getCompilerInstance()

println("Resolved ${compilerInstance.solcRelease.version} for $fileName")

val result = compilerInstance.execute(
    SolcArguments.OUTPUT_DIR.param { "/tmp" },
    SolcArguments.BIN,
    SolcArguments.OVERWRITE
)

println("Solc exited with code: ${result.exitCode}")
println("Solc standard output:\n${result.stdOut}")
println("Solc standard error:\n${result.stdErr}")

.gitignore


# Created by https://www.gitignore.io/api/kotlin
# Edit at https://www.gitignore.io/?templates=kotlin

### Kotlin ###
# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

# End of https://www.gitignore.io/api/kotlin

# Created by https://www.gitignore.io/api/gradle
# Edit at https://www.gitignore.io/?templates=gradle

### Gradle ###
.gradle
build/

# Ignore Gradle GUI config
gradle-app.setting

# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar

# Cache of project
.gradletasknamecache

# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties

### Gradle Patch ###
**/build/

# End of https://www.gitignore.io/api/gradle

*.asc
*.project
*.settings
.idea

build.gradle

buildscript {
    ext.kotlin_version = '1.3.61'
    repositories { jcenter() }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

plugins {
    id 'org.jetbrains.kotlin.jvm' version "1.3.61"
    id 'idea'
    id 'jacoco'
    id "com.jfrog.bintray" version "1.8.4"
    id "com.diffplug.gradle.spotless" version "3.25.0"
    id 'io.codearte.nexus-staging' version '0.21.1'
    id "de.marcphilipp.nexus-publish" version "0.4.0"
    id "de.undercouch.download" version "4.0.0"
}

description 'web3j-sokt - Kotlin-based wrapper for multiple installations of the solidity compiler (solc)'

apply {
    [
        'bintray',
        'jacoco',
        'java',
        'javadoc',
        'repositories',
        'publish',
        'spotless',
        'junit'
    ].each { buildScript ->
        download {
            src "https://raw.githubusercontent.com/web3j/build-tools/master/gradle/$buildScript/build.gradle"
            dest "$rootDir/gradle/$buildScript/build.gradle"
            overwrite false
            quiet true
            onlyIfModified true
        }
        from("$rootDir/gradle/$buildScript/build.gradle")
    }
}


apply plugin: 'kotlinx-serialization'

group 'org.web3j'

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8",
            "org.apache.commons:commons-lang3:3.0",
            "com.github.zafarkhaja:java-semver:0.9.0",
            "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.14.0"
    testImplementation "org.junit.jupiter:junit-jupiter-engine:$junitVersion",
            "org.junit.jupiter:junit-jupiter-api:$junitVersion",
            "org.junit.jupiter:junit-jupiter-params:$junitVersion"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Download details:

Author: web3j
Source code: https://github.com/web3j/web3j-sokt

#web3 #blockchain #solidity 

Web3j Sokt: A Kotlin Wrapper for The Solidity Compiler (solc)
Kevin  Taylor

Kevin Taylor

1673491500

Example on Solidity and Web3.js to Store IPFS Hash

IPFS hash (multihash) with Solidity and web3.js

Example of using Solidity and web3.js to store and retrieve IPFS hash and more generally multihash.

IPFS hash is often represented using 46 character long Base58 encoding(e.g. QmahqCsAUAw7zMv6P6Ae8PjCTck7taQA6FgGQLnWdKG7U8). It might be attempting to store IPFS hash using bytes or string which are dynamically sized byte array since it cannot fit in the largest fixed-size byte arrays bytes32.

However this can be both expensive and challenging to use IPFS hashes in arrays. Luckily as one might notice that IPFS hashes commonly start with Qm, they in fact follow the multihash self describing hash format:

 <varint hash function code><varint digest size in bytes><hash function output>

This makes it possible to break down IPFS hash into a struct like so:

  struct Multihash {
    bytes32 digest;
    uint8 hashFunction;
    uint8 size;
  }

This repository gives an end-to-end example on how to store IPFS hash in Solidity as well as how to call the smart contract using web3.js to get and set IPFS hash.

IPFSStorage.sol is a smart contract that stores IPFS hash in a mapping from address key to Multihash struct. Because web3.js ABI doesn't support passing tuple as parameter and return type, additional care is taken to normalize the function interface to be web3.js friendly.

multihash.js contains the Javascript code that converts base58 encoded multihash string to and from smart contract friendly arguments and responses.

Refer to test cases for additional example code how to interact with the contract.

Reference

Multihash Format: https://github.com/multiformats/multihash

zeppelin-solidity for project setup and test helpers.

Previous discussions and examples:

How to store IPFS hash using bytes?

A practical guide to cheap IPFS hash storage in an Ethereum smart contract

OriginProtocol Demo Code


Download details:

Author: saurfang
Source code: https://github.com/saurfang/ipfs-multihash-on-solidity

License: MIT license

#web3 #solidity #blockchain 

Example on Solidity and Web3.js to Store IPFS Hash

Web3 OpenAPI Compliant Service Generator for Solidity Smart Contracts

Web3j Open API

Web3j-OpenAPI is a OpenAPI client and server generator from Solidity smart contracts. it provides a way to interact with the Ethereum blockchain via simple and intuitive HTTP requests, abstracting the coding layer. These interactions can be done using :

  • Plain HTTP requests
  • Via the Swagger-UI, which is generated with every project
  • A client application using the webj3-openapi-client implementation

The workflow can be summed in the following steps:

  • Writing a Solidity smart contract
  • Generating the corresponding OpenAPI project using Web3j-OpenAPI
  • Running the generated project as a standalone server
  • Sending HTTP requests using Swagger-UI, client application or Curl request.

Getting started with Web3j-OpenAPI

To generate an OpenAPI project using the Web3j-OpenAPI generator, you need to have the Epirus-CLI installed on your machine (Note - the Epirus CLI has replaced the Web3j CLI). It’s easy to do (for Windows instructions head here):

$ curl -L get.epirus.io | sh

Create a Hello World project

To create a base OpenAPI project using a Hello World contract, run the following :

$ epirus openapi new

You can also generate a Web3j-OpenAPI project using the Web3j-OpenAPI-gradle-plugin.

Configure the project

After having the generated project, you can use the Epirus-CLI to run it using the following command (Note: You will need to create an Epirus Account).

$ epirus login
$ epirus run rinkeby|ropsten

Alternatively, you can configure your application with the following environment variables:

$ export WEB3J_ENDPOINT=<link_to_your_Ethereum_node>
$ export WEB3J_PRIVATE_KEY=<your_private_key>
$ export WEB3J_OPENAPI_HOST=localhost
$ export WEB3J_OPENAPI_PORT=9090

Run the project

If you aren't using the Epirus-CLI, you may run the project using the following Gradle target:

$ cd <project_folder>
$ ./gradlew run

Then, you should be seeing the server logs.

Interact with the project

SwaggerUI

The easiest way to interact with the generated project is via the generated Swagger-UI which can be found on http://<host>:<port>/swagger-ui.

image

Web3j-OpenAPI client

Also, you can use our client implementation via adding the following dependency to your project:

dependencies {
    implementation "org.web3j.openapi:web3j-openapi-client:4.7.1"
}

Then, within the application:

val service = ClientService("http://localhost:9090")
val app = ClientFactory.create(<AppNameApi>::class.java, service)

// Then you have access to all the API resources
val receipt = app.contracts.contractName.deploy()

println("Deployment receipt: ${receipt.contractAddress}")

// ...

For more information, please refer to the documentation.


Download details:

Author: web3j
Source code: https://github.com/web3j/web3j-openapi

#web3 #solidity #openapi #smartcontract 

Web3 OpenAPI Compliant Service Generator for Solidity Smart Contracts
Yvette  Bell

Yvette Bell

1673105227

How to Write A DAPP with Flutter + Solidity

IntroIn this Flutter tutorial we will learn about How to Write A DAPP with Flutter + Solidity. We are living interesting times in terms of economy, it seems that we are in the frontier of a new era of decentralized economy based on cryptocurrencies and blockchain. Every day we are discovering new ways to use blockchain technologies to write pieces of software that change the way of create “value” from it.

Decentralized Apps

They are normal apps, they offer similar functions, but the key difference is they run on a peer-to-peer network, such as a blockchain.

Benefits

  • Open source: This encourages the widespread development of the dapp ecosystem enabling developers to build better dapps with more useful or interesting functions.
  • Blockchain based: As they are made of smart contracts, they can easily integrate cryptocurrencies into the basic functionalities of the Dapp.
  • No downtime: Relying on a peer-to-peer system ensures the dapps continue to work even if individual computers or parts of the network go down.
  • Censorship-resistant: With no single point of failure, it’s very difficult for governments or powerful individuals to control the network.

Fluthereum: A practical example

Contract

First of all we need a Smart contract to interact with from the app, the way to program a contracts is by using some programming language oriented to these kind of programs. In this example we will use Solidity, that is an Object oriented programming language with similar syntax to Javascript and Typescript.

We also will use Remix as the development environment to compile and deploy our contract.

IMPORTANT: You should deploy your contract to one of the several testing chains provided by remix, in my case it’s rinkeby. You shouldn’t use the main Ethereum chain to test your app.

// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;

contract Fluthereum {
    int public balance;
    
    constructor() {
        balance = 0;
    }
    
    function deposit(int amount) public {
        balance += amount;
    }
    
    function withdraw(int amount) public {
        balance -= amount;
    }
}

As you can see, the code is pretty simple and easy to read, even if you’re not familiar with Solidity, it’s easy to tell that the contract is like a class with functions and attributes inside.

In this example we only have a balance starting in 0, then we can increment it with deposit() and decrement with withdraw() with a given amount provided from the frontend app.

API access

Once we have the contract deployed and running we can create an endpoint to make it accessible from the Flutter app, an easy way to do that is by using Infura.

Infura provides us an API endpoint to interact with our deployed contracts in a simple way and without needing any server side application. After creating and setting up the account you just have to provide the contract ID and they will give you an endpoint to access to your deployed contract.

Flutter App

Once we have our endpoint we can start working on the fronted part. In this case I will run a normal Flutter App.

To be able to interact with the smart contract through the API we need to add the web3dart dependency to setup the connection.

Once installed we can fetch our contract interface by using the following code:

  Future<DeployedContract> getContract() async {
    // abi.json is the contract metadata, you can download it from the remix IDE
    String abi = await rootBundle.loadString("assets/abi.json");
    String contractAddress = "my_contract_address"; // e.g. 0xd66C81d9b781152e2D9be07Ccdf2303A77B7163c
    String contractName = "my_contract_name"; // you must set your own contract name here
    
    DeployedContract contract = DeployedContract(
      ContractAbi.fromJson(abi, contractName),
      EthereumAddress.fromHex(contractAddress),
    );

    return contract;
  }

In order to create a point of interaction with the smart contract, we can create a generic dart function to send and receive data from it.

  Future<List<dynamic>> query(String functionName, List<dynamic> args) async {
    DeployedContract contract = await getContract();
    ContractFunction function = contract.function(functionName);
    List<dynamic> result = await ethereumClient.call(
        contract: contract, function: function, params: args);
    return result;
  }

And now we can interact with all the public functions and attributes within our deployed contract :).

  Future<void> getBalance() async {
    setState(() => {loading = true});
    List<dynamic> result = await query('balance', []);
    balance = int.parse(result[0].toString());
    setState(() => {loading = false});
  }

  Future<void> deposit(int amount) async {
    BigInt parsedAmount = BigInt.from(amount);
    await transaction("deposit", [parsedAmount]);
  }

  Future<void> withdraw(int amount) async {
    BigInt parsedAmount = BigInt.from(amount);
    await transaction("withdraw", [parsedAmount]);
  }

If you want to see a full example with integrated UI please visit this github repo and leave a star ;)

Conclusion

Even though this is a silly example, the goal of this article was to show how to build a pipeline to interact with Smart Contracts from Flutter apps, creating DAPPs that interact directly with decentralized blockchain networks and this way allowing much more interesting applications.

Original article sourced at: https://itnext.io

#flutter #dart #solidity 

How to Write A DAPP with Flutter + Solidity

Invoke a Call and Transfer Function in Solidity

What is a call?

  • Invoking a smart contract function without broadcasting to the network.
  • It does not change any blockchain or contract state.
  • Read only operation.
  • Since it is read only operation it does not need any gas.

Call and Transfer Function

What is a transaction?

  • Transaction is something that is broadcasted to the entire network.
  • It changes the state of blockchain or contract.
  • It is a write operation so; it requires signing from user wallet. That's why whenever we do a transaction, we need to sign the transaction in order make the payment successful.
  • Transaction can not be done without private key.
  • Needs gas and these gases are paid in native tokens like ETH for Ethereum, SOL for Solana, MATIC for polygon.

Call and Transfer Function

When to use either of them?

If we want to read data, then we need to use call.

For Example,

If we want to check the balance of the contract then we use call.

If we want to write data, then we need to use transaction.

For Example,

If we want to transfer a token or send an ETH from one contract to another, then we need to use Transaction.

Original article source at: https://www.c-sharpcorner.com/

#function #transfer #solidity #web3 #blockchain 

Invoke a Call and Transfer Function in Solidity
Blockchain Dev

Blockchain Dev

1672373141

Blockchain Programing for Beginners - Full Course in 10 Hours

Learn about Blockchain programing in this full course for beginners. Intro to Blockchain Programing [FULL COURSE ]

🎞️TABLE OF CONTENTS:

00:00 INTRO
👉 01:28 CODE A WEB 3.0 REAL ESTATE APP LIKE ZILLOW STEP-BY-STEP (SOLIDITY, ETHEREUM, HARDHAT, REACT)
💻 CODE: https://github.com/dappuniversity/millow 

06:09 Create Project
15:34 Escrow Contract
37:37 List Property
56:35 Earnest Deposit
01:02:51 Finish Contract
01:19:06 Deploy Contracts
01:30:17 Create Front End
01:35:35 Connect to Blockchain
01:42:53 Navbar
01:47:37 Search Bar
01:52:06 List Properties
02:04:03 Buy Property

👉 02:36:18 ULTIMATE SOLIDITY TUTORIAL: DEFI, FLASH LOANS, HACKING, NFTS & MORE!
💻 CODE: https://github.com/dappuniversity/solidity_tutorial 

02:37:42  First Contract
03:05:55 Testing Contracts
03:36:21 NFT Real Estate Escrow
04:48:31 Flash Loans
05:42:15 Hacking: Reentrancy

👉 06:19:28 CODE AN NFT MARKETPLACE LIKE OPENSEA STEP-BY-STEP [ERC-721, SOLIDITY]
💻 CODE: https://github.com/dappuniversity/nft_marketplace 

06:24:51 System Dependencies
06:26:34Project Dependencies
06:30:40 Project Setup
06:34:56 NFT contract
06:55:19 Marketplace contract setup
07:15:09 Make Items
07:25:39 Purchase Items
07:39:10 Front End Setup
07:51:29 Home (Front End)
07:58:53 Create (Front End)
08:07:50 My Listed Items (Front End)
08:14:10 Purchases (Front End)

👉 08:20:34 CODE A WEB 3.0 DOMAIN SITE LIKE GODADDY STEP-BY-STEP (SOLIDITY, ETHEREUM, HARDHAT, REACT)
💻 CODE: https://github.com/dappuniversity/eth_daddy 

08:20:34 Project Overview
08:23:16 Project Setup
08:28:54 Smoke Test
08:38:48 NFT Contract
09:02:38 List Domains
09:28:10 Buy NFTs
09:45:17 Deploy Contracts
09:50:57 Create Website
10:07:42 Navbar
10:17:58 UI Scaffolding
10:21:29 List Domains
10:42:48 Buy Domains

10:56:55 CONCLUSION

#blockchain #web3js #solidity 

Blockchain Programing for Beginners - Full Course in 10 Hours
Lawson  Wehner

Lawson Wehner

1672220820

DeFiHackLabs: Reproduce DeFi hacked incidents using Foundry

DeFi Hacks Reproduce - Foundry

Reproduce DeFi hack incidents using Foundry.

143 incidents included.

This repo is only for the educational purpose.

Let's make Web3 secure! Join Discord

Notion: root cause analysis

Getting Started

Follow the instructions to install Foundry.

Clone and install dependencies:git submodule update --init --recursive


20221225 - Rubic - Arbitrary External Call Vulnerability

Lost: $1.5M

Testing

forge test --contracts ./src/test/Rubic_exp.sol -vvv

Contract

Rubic_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1606993118901198849

https://twitter.com/peckshield/status/1606937055761952770


20221223 - Defrost - Reentrancy

Lost: $170k

Testing

forge test --contracts ./src/test/Defrost_exp.sol -vvv

Contract

Defrost_exp.sol

Link reference

https://twitter.com/PeckShieldAlert/status/1606276020276891650


20221212 - BGLD - FlashLoan price manipulation

Lost: $18k

Testing

forge test --contracts ./src/test/BGLD_exp.sol -vvv

Contract

BGLD_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1602335214356660225


20221211 - Lodestar - FlashLoan price manipulation

Lost: $4M

Testing

forge test --contracts ./src/test/Lodestar_exp.sol -vvv

Contract

Lodestar_exp.sol

Link reference

https://twitter.com/SolidityFinance/status/1601684150456438784

https://blog.lodestarfinance.io/post-mortem-summary-13f5fe0bb336


20221210 - MU&MUG - FlashLoan price manipulation

Lost: $57k

Testing

forge test --contracts ./src/test/MUMUG_exp.sol -vvv

Contract

MUMUG_exp.sol

Link reference

https://twitter.com/BeosinAlert/status/1601422462012469248


20221210 - TIFIToken - FlashLoan price manipulation

Lost: 87 WBNB

Testing

forge test --contracts ./src/test/TIFI_exp.sol -vvv

Contract

TIFI_exp.sol

Link reference

https://twitter.com/peckshield/status/1601492605535399936


20221209 - NOVAToken - Malicious Unlimted Minting

Lost: 330 $BNB

Testing

forge test --contracts ./src/test/NovoExchange_exp.sol -vvv

Contract

NovoExchange_exp.sol

Link reference

https://twitter.com/BeosinAlert/status/1601168659585454081


20221207 - AES - Business Logic Flaw & FlashLoan price manipulation

Lost: $60k

Testing

forge test --contracts ./src/test/AES_exp.sol -vvv

Contract

AES_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1600442137811689473

https://twitter.com/peckshield/status/1600418002163625984


20221205 - RFB - Predicting Random Numbers

Lost: 12BNB

Testing

forge test --contracts ./src/test/RFB_exp.sol -vvv

Contract

RFB_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1599991294947778560


20221205 - BBOX - FlashLoan price manipulation

Lost: 12k

Testing

forge test --contracts ./src/test/BBOX_exp.sol -vvv

Contract

BBOX_exp.sol

Link reference

https://twitter.com/AnciliaInc/status/1599599614490877952


20221202 - OverNight - FlashLoan Attack

Lost: 170k

Testing

forge test --contracts ./src/test/Overnight_exp.sol -vvv

Contract

Overnight_exp.sol

Link reference

https://twitter.com/peckshield/status/1598704809690877952


20221201 - APC - FlashLoan & price manipulation

Lost: $6k

Testing

forge test --contracts ./src/test/APC_exp.sol -vvv

Contract

APC_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1598262002010378241


20221129 - MBC - Business Logic Flaw & Access Control

Lost $5.6k

Testing

forge test --contracts ./src/test/MBC_exp.sol -vvv

Contract

MBC_exp.sol

Link reference

https://twitter.com/AnciliaInc/status/1597742575623888896

https://twitter.com/CertiKAlert/status/1597639717096460288


20221129 - SEAMAN - Business Logic Flaw

Lost $7k

Testing

forge test --contracts ./src/test/SEAMAN_exp.sol -vvv

Contract

SEAMAN_exp.sol

Link reference

https://twitter.com/peckshield/status/1597493955939405825

https://twitter.com/CertiKAlert/status/1597513374841044993

https://twitter.com/BeosinAlert/status/1597535796621631489


20221123 - NUM - Protocol Token incompatible

Lost $13k

Testing

forge test --contracts ./src/test/NUM_exp.sol -vvv

Contract

NUM_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1595346020237352960


20221122 - AUR - Lack of Permission Check

Lost: $13k

Testing

forge test --contracts ./src/test/AUR_exp.sol -vvv

Contract

AUR_exp.sol

Link reference

https://twitter.com/AnciliaInc/status/1595142246570958848


20221121 - sDAO - Business Logic Flaw

Lost: $13k

Testing

forge test --contracts ./src/test/SDAO_exp.sol -vvv

Contract

SDAO_exp.sol

Link reference

https://twitter.com/8olidity/status/1594693686398316544

https://twitter.com/CertiKAlert/status/1594615286556393478


20221119 - AnnexFinance - Verify flashLoan Callback

Lost: $3k

Testing

forge test --contracts ./src/test/Annex_exp.sol -vvv

Contract

Annex_exp.sol

Link reference

https://twitter.com/AnciliaInc/status/1593690338526273536


20221117 - UEarnPool - FlashLoan Attack

Lost: $24k

Testing

forge test --contracts ./src/test/UEarnPool_exp.sol -vvv

Contract

UEranPool_exp.sol

Link reference

https://twitter.com/CertiKAlert/status/1593094922160128000


20221116 - SheepFram - No input validation

Lost: ~1BNB

Testing

forge test --contracts ./src/test/SheepFram_exp.sol -vvv

Contract

SheepFram_exp.sol

Link reference

https://twitter.com/AnciliaInc/status/1592658104394473472

https://twitter.com/BlockSecTeam/status/1592734292727455744


20221110 - DFXFinance - Reentrancy

Lost: $4M

Testing

forge test --contracts ./src/test/DFX_exp.sol -vvv

Contract

DFX_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1590960299246780417

https://twitter.com/BeosinAlert/status/1591012525914861570

https://twitter.com/AnciliaInc/status/1590839104731684865

https://twitter.com/peckshield/status/1590831589004816384


20221109 BrachTOPG - Arbitrary External Call Vulnerability

Lost: $89k

Testing

 forge test --contracts ./src/test/BrahTOPG_exp.sol -vvv

Contract

BrahTOPG_exp.sol

Link reference

https://twitter.com/SlowMist_Team/status/1590685173477101570


20221108 Kashi - Price-caching Design Defect

Lost: $110k

Testing

forge test --contracts ./src/test/Kashi_exp.sol -vvv

Contract

Kashi_exp.sol

Link reference

https://eigenphi.substack.com/p/casting-a-magic-spell-on-abracadabra

https://twitter.com/BlockSecTeam/status/1603633067876155393


20221107 MooCAKECTX - FlashLoan Attack

Lost: $140k

Testing

forge test --contracts ./src/test/MooCAKECTX_exp.sol -vvv

Contract

MooCAKECTX_exp.sol

Link reference

https://twitter.com/BeosinAlert/status/1589501207181393920

https://twitter.com/CertiKAlert/status/1589428153591615488


20221105 BDEX - Business Logic Flaw

Lost: 16WBNB

Testing

forge test --contracts ./src/test/BDEX_exp.sol -vvv

Contract

BDEX_exp.sol

Link reference

https://twitter.com/BeosinAlert/status/1588579143830343683


20221027 VTF Token - Incorrect Reward calculation

Lost: $50k

Testing

forge test --contracts ./src/test/VTF_exp.sol -vvv

Contract

VTF_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1585575129936977920

https://twitter.com/peckshield/status/1585572694241988609

https://twitter.com/BeosinAlert/status/1585587030981218305


20221027 Team Finance - Liquidity Migration Exploit

Lost: Multiple Tokens ~$15.8M US$

Testing

forge test --contracts ./src/test/TeamFinance.exp.sol -vvv

Contract

TeamFinance.exp.sol

Link reference

https://twitter.com/TeamFinance_/status/1585770918873542656

https://twitter.com/peckshield/status/1585587858978623491

https://twitter.com/solid_group_1/status/1585643249305518083

https://twitter.com/BeosinAlert/status/1585578499125178369


20221026 N00d Token - Reentrancy

Lost $29k

Testing

forge test --contracts src/test/N00d_exp.sol -vvv

Contract

N00d_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1584959295829180416

https://twitter.com/AnciliaInc/status/1584955717877784576


20221026 ULME - Access Control

Lost ~200k US$ which resulted in ~50k profit

Testing

forge test --contracts ./src/test/ULME.sol -vvv

Contract

ULME.sol

Link reference

https://twitter.com/BlockSecTeam/status/1584839309781135361 https://twitter.com/BeosinAlert/status/1584888021299916801


20221024 Market - Read-only Reentrancy

Lost: $220k

Testing

forge test --contracts ./src/test/Market_exp.t.sol -vv

Contract

Market_exp.t.sol

Link reference

https://quillaudits.medium.com/decoding-220k-read-only-reentrancy-exploit-quillaudits-30871d728ad5


20221024 MulticallWithoutCheck - Arbitrary External Call Vulnerability

Lost $600

Testing

forge test --contracts ./src/test/MulticallWithoutCheck_exp.sol -vvv

Contract

MulticallWithoutCheck_exp.sol


20221021 OlympusDAO - No input validation

Lost ~$292K (30500 OHM)

Testing

forge test --contracts ./src/test/OlympusDao.exp.sol -vvv

Contract

OlympusDao.exp.sol

Link reference

https://twitter.com/peckshield/status/1583416829237526528


20221020 HEALTH - Transfer Logic Flaw

Lost 16 BNB

Testing

forge test --contracts ./src/test/HEALTH_exp.sol -vvv

Contract

HEALTH_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1583073442433495040


20221020 BEGO - Incorrect signature verification

Lost 12 BNB

Testing

forge test --contracts ./src/test/BEGO_exp.sol -vvv

Contract

BEGO_exp.sol

Link reference

https://twitter.com/AnciliaInc/status/1582828751250784256

https://twitter.com/peckshield/status/1582892058800685058


20221018 HPAY - Access Control

Lost: 115 BNB

Testing

forge test --contracts ./src/test/HPAY_exp.sol -vvv

Contract

HPAY_exp.sol

Link reference

https://twitter.com/Supremacy_CA/status/1582345448190140417


20221018 PLTD - Transfer Logic Flaw

Lost: $ 24k

Testing

forge test --contracts ./src/test/PLTD_exp.sol -vvv

Contract

PLTD_exp.sol

Link reference

https://twitter.com/BeosinAlert/status/1582181583343484928


20221017 Uerii Token - Access Control

Lost: $2.4 k

Testing

forge test --contracts ./src/test/Uerii_exp.sol -vvv

Contract

Uerii_exp.sol

Link reference

https://twitter.com/peckshield/status/1581988895142526976


20221014 INUKO - FlashLoan price manipulation

Lost: $50k

Testing

forge test --contracts ./src/test/INUKO_exp.sol -vvv

Contract

INUKO_exp.sol

Link reference

https://twitter.com/AnciliaInc/status/1587848874076430336


20221014 EFLeverVault - Verify flashLoan Callback

Lost: 750 ETH

Testing

 forge test --contracts ./src/test/EFLeverVault_exp.sol -vvv

Contract

EFLeverVault_exp.sol

Link reference

https://twitter.com/Supremacy_CA/status/1581012823701786624

https://twitter.com/MevRefund/status/1580917351217627136

https://twitter.com/danielvf/status/1580936010556661761


20221014 MEVBOTa47b - MEVBOT a47b

Lost: $241 k

Testing

forge test --contracts ./src/test/MEVa47b_exp.sol -vvv  

Contract

MEVa47b_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1580779311862190080

https://twitter.com/AnciliaInc/status/1580705036400611328

https://etherscan.io/tx/0x35ecf595864400696853c53edf3e3d60096639b6071cadea6076c9c6ceb921c1


20221012 ATK - FlashLoan manipulate price

Lost: $127 k

Testing

forge test --contracts ./src/test/ATK_exp.sol -vvv

Contract

ATK_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1580095325200474112


20221011 Rabby Wallet SwapRouter - Arbitrary External Call Vulnerability

Lost: ~200,000 US$

Testing

forge test --contracts src/test/RabbyWallet_SwapRouter.exp.sol -vv

Contract

RabbyWallet_SwapRouter.exp.sol

Link reference

https://twitter.com/Supremacy_CA/status/1579813933669486592

https://twitter.com/SlowMist_Team/status/1579839744128978945

https://twitter.com/BeosinAlert/status/1579856733178331139


20221011 Templedao - Insufficient access control

Lost: $2.3 million

Testing

forge test --contracts src/test/Templedao_exp.sol -vv

Contract

Templedao_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1579843881893769222

https://etherscan.io/tx/0x8c3f442fc6d640a6ff3ea0b12be64f1d4609ea94edd2966f42c01cd9bdcf04b5


20221010 Carrot - Public functionCall

Testing

forge test --contracts src/test/Carrot_exp.sol -vv

Contract

Carrot_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1579908411235237888

https://bscscan.com/tx/0xa624660c29ee97f3f4ebd36232d8199e7c97533c9db711fa4027994aa11e01b9


20221009 Xave Finance - Malicious Proposal Mint & Transfer Ownership

Testing

forge test --contracts src/test/XaveFinance_exp.sol -vv

Contract

XaveFinance_exp.sol

Link reference

https://twitter.com/BeosinAlert/status/1579040051853303808

https://etherscan.io/tx/0xc18ec2eb7d41638d9982281e766945d0428aaeda6211b4ccb6626ea7cff31f4a


20221006 RES-Token - pair manipulate

Testing

forge test --contracts src/test/RES_exp.sol -vv

Contract

RES_exp.sol RES02_exp.sol

Link reference

https://twitter.com/AnciliaInc/status/1578119778446680064

https://bscscan.com/tx/0xe59fa48212c4ee716c03e648e04f0ca390f4a4fc921a890fded0e01afa4ba96d


20221002 Transit Swap - Incorrect owner address validation

Testing

forge test --contracts src/test/TransitSwap_exp.sol -vv

Contract

TransitSwap_exp.sol

Link reference

https://twitter.com/TransitFinance/status/1576463550557483008

https://twitter.com/1nf0s3cpt/status/1576511552592543745

https://bscscan.com/tx/0x181a7882aac0eab1036eedba25bc95a16e10f61b5df2e99d240a16c334b9b189


20221001 BabySwap - Parameter Access Control

Testing

forge test --contracts ./src/test/BabySwap_exp.sol -vvv

Contract

BabySwap_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1576441612812836865


20221001 RL Token - Incorrect Reward calculation

Testing

forge test --contracts src/test/RL_exp.sol -vv

Contract

RL_exp.sol

Link reference

https://twitter.com/CertiKAlert/status/1576195971003858944


20221001 Thunder Brawl - Reentrancy

Testing

forge test --contracts src/test/THB_exp.sol -vv

Contract

THB_exp.sol

Link reference

https://twitter.com/peckshield/status/1575890733373849601

https://bscscan.com/tx/0x57aa9c85e03eb25ac5d94f15f22b3ba3ab2ef60b603b97ae76f855072ea9e3a0


20220928 BXH - Flashloan & Price Oracle Manipulation

Lost: $40,305

Testing

forge test --contracts src/test/BXH_exp.sol -vv

Contract

BXH_exp.sol

Link reference

https://www.jinse.com/lives/319392.html

https://bscscan.com/tx/0xa13c8c7a0c97093dba3096c88044273c29cebeee109e23622cd412dcca8f50f4


20220910 DPC - Incorrect Reward calculation

Lost: $103,755

Testing

forge test --contracts ./src/test/DPC_exp.sol -vvv 

Contract

DPC_exp.sol

Link reference

https://twitter.com/BeosinAlert/status/1568429355919089664

https://bscscan.com/address/0x2109bbecB0a563e204985524Dd3DB2F6254AB419

https://learnblockchain.cn/article/4733


20220928 MEVBOT - Badc0de

Lost: $1,469,700

An anonymous attacker noticed a flaw in the bots arbitrage contract code, and stole not only the recently acquired 800 ETH, but the entire 1,101 ETH in 0xbad’s wallet.

Testing

forge test --contracts ./src/test/MEVbadc0de_exp.sol -vvv 

Contract

MEVbadc0de_exp.sol

Link reference

https://rekt.news/ripmevbot/

https://etherscan.io/tx/0x59ddcf5ee5c687af2cbf291c3ac63bf28316a8ecbb621d9f62d07fa8a5b8ef4e


20220923 RADT-DAO - pair manipulate

Lost: 94,304 USDT

Testing

forge test --contracts ./src/test/RADT_exp.sol -vvv 

Contract

RADT_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1573252869322846209

https://bscscan.com/tx/0xd692f71de2768017390395db815d34033013136c378177c05d0d46ef3b6f0897


20220913 MevBot private tx

Lost: $140 K

Testing

forge test --contracts ./src/test/BNB48MEVBot_exp.sol -vvv 

Contract

BNB48MEVBot_exp.sol

Link reference

https://blocksecteam.medium.com/the-two-sides-of-the-private-tx-service-on-binance-smart-chain-a76917c3ce51

https://twitter.com/1nf0s3cpt/status/1577594615104172033

https://bscscan.com/tx/0xd48758ef48d113b78a09f7b8c7cd663ad79e9965852e872fdfc92234c3e598d2


20220909 YYDS - pair manipulate

Lost: 742,286.27 BUSD

Testing

forge test --contracts ./src/test/Yyds_exp.sol -vvv 

Contract

Yyds_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1567928377432051713

https://bscscan.com/tx/0x04a1f0d1694242515ecb14faa71053901f11a1286cd21c27fe5542f9eeb62356


20220908 Ragnarok Online Invasion - Broken Access Control

Lost: 157.98 BNB (~44,000 US$)

Testing

forge test --contracts ./src/test/ROI_exp.sol -vvv 

Contract

ROI_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1567746825616236544

https://twitter.com/CertiKAlert/status/1567754904663429123

https://www.panewslab.com/zh_hk/articledetails/mbzalpdi.html

https://medium.com/quillhash/decoding-ragnarok-online-invasion-44k-exploit-quillaudits-261b7e23b55


20220908 NewFreeDAO - Flashloans Attack

Lost: 4,481 BNB (~125M US$)

Testing

forge test --contracts ./src/test/NewFreeDAO_exp.sol -vvv 

Contract

NewFreeDAO_exp.sol

Link reference

https://twitter.com/SlowMist_Team/status/1567854876633309186

https://bscscan.com/tx/0x1fea385acf7ff046d928d4041db017e1d7ead66727ce7aacb3296b9d485d4a26


20220906 NXUSD - flashloan price oracle manipulation

Lost 50,000 USD

Testing

forge test --contracts ./src/test/NXUSD_exp.sol -vvv 

Contract

NXUSD_exp.sol

Link reference

https://medium.com/nereus-protocol/post-mortem-flash-loan-exploit-in-single-nxusd-market-343fa32f0c6

https://snowtrace.io/tx/0x0ab12913f9232b27b0664cd2d50e482ad6aa896aeb811b53081712f42d54c026


20220905 ZoomproFinance - Flashloans & Price Manipulation

Lost: 61,160 USDT

Testing

forge test --contracts ./src/test/ZoomproFinance_exp.sol -vvv 

Contract

ZoomproFinance_exp.sol

Link reference

https://twitter.com/blocksecteam/status/1567027459207606273

https://bscscan.com/tx/0xe176bd9cfefd40dc03508e91d856bd1fe72ffc1e9260cd63502db68962b4de1a


20220902 ShadowFi - Access Control

Lost: 1,078 BNB

Anyone can burn $SDF

Testing

forge test --contracts ./src/test/Shadowfi_exp.sol -vvv 

Contract

Shadowfi_exp.sol

Link reference

https://twitter.com/PeckShieldAlert/status/1565549688509861888

https://bscscan.com/tx/0xe30dc75253eecec3377e03c532aa41bae1c26909bc8618f21fb83d4330a01018


20220902 Bad Guys by RPF - Business Logic Flaw : Missing Check For Number of NFT to Mint

Lost: Bad Guys by RPF(400 NFTs)

Testing

forge test --contracts ./src/test/BadGuysbyRPF_exp.sol -vvv

Contract

BadGuysbyRPF_exp.sol

Link reference

https://twitter.com/RugDoctorApe/status/1565739119606890498

https://etherscan.io/tx/0x27e64a8215ae1528245c912bcca09883fdd7cce69249bd5d5d1c0eecf5297b96


20220824 LuckeyTiger NFT - Predicting Random Numbers

Testing

forge test --contracts ./src/test/LuckyTiger_exp -vvv 
forge script script/LuckyTiger_s_exp.sol:luckyHack --fork-url http://127.0.0.1:8545 --private-key $PRIVATE_KEY --broadcast

Contract

LuckyTiger_exp.sol | LuckyTiger_s_exp.sol

Link reference

https://twitter.com/1nf0s3cpt/status/1576117129589317633

https://etherscan.io/tx/0x804ff3801542bff435a5d733f4d8a93a535d73d0de0f843fd979756a7eab26af


20220810 XSTABLE Protocol - Incorrect Logic Check

Testing

forge test --contracts ./src/test/XST.exp.sol -vvv 

Contract

XST.exp.sol XST02_exp.sol

Link reference

https://mobile.twitter.com/BlockSecTeam/status/1557195012042936320


20220809 ANCH - Skim token balance

Testing

forge test --contracts ./src/test/ANCH_exp.sol -vvv

Contract

ANCH_exp.sol

Link reference

https://twitter.com/AnciliaInc/status/1557527183966408706


20220807 EGD Finance - Flashloans & Price Manipulation

Lost: 36,044 USDT

Testing

forge test --contracts ./src/test/EGD-Finance.exp.sol -vvv 

Contract

EGD-Finance.exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1556483435388350464

https://twitter.com/PeckShieldAlert/status/1556486817406283776


20220802 Nomad Bridge - Business Logic Flaw : Incorrect acceptable merkle-root checks

Lost: Multiple ERC-20 Tokens (~152M US$)

Testing

forge test --contracts ./src/test/NomadBridge.exp.sol -vvv 

Contract

NomadBridge.exp.sol

Link reference

https://twitter.com/samczsun/status/1554252024723546112

https://www.certik.com/resources/blog/28fMavD63CpZJOKOjb9DX3-nomad-bridge-exploit-incident-analysis

https://blog.coinbase.com/nomad-bridge-incident-analysis-899b425b0f34


20220801 Reaper Farm - Business Logic Flaw : Lack of access control mechanism

Lost: Multiple ERC-20 Tokens (~1.7M US$)

Testing

forge test --contracts ./src/test/ReaperFarm.exp.sol -vvv 

Contract

ReaperFarm.exp.sol

Link reference

https://twitter.com/Reaper_Farm/status/1554500909740302337

https://twitter.com/BeosinAlert/status/1554476940593340421


20220725 LPC - Business Logic Flaw : Incorrect recipient balance check, did not check sender!=recipient in transfer

Lost: 178 BNB (~45,715 US$)

Testing

forge test --contracts ./src/test/LPC.exp.sol -vvv 

Contract

LPC.exp.sol

Link reference

https://www.panewslab.com/zh_hk/articledetails/uwv4sma2.html

https://twitter.com/BeosinAlert/status/1551535854681718784


20220723 Audius - Storage Collision & Malicious Proposal

Lost: 704 ETH (~1.08M US$)

Testing

forge test --contracts ./src/test/Audius.exp.sol -vvv 

Contract

Audius.exp.sol

Link reference

https://twitter.com/AudiusProject/status/1551000725169180672

https://twitter.com/1nf0s3cpt/status/1551050841146400768

https://blog.audius.co/article/audius-governance-takeover-post-mortem-7-23-22


20220713 SpaceGodzilla - Flashloans & Price Manipulation

Lost: 25,378 BUSD

Testing

forge test --contracts ./src/test/SpaceGodzilla.exp.sol -vvv 

Contract

SpaceGodzilla.exp.sol

Link reference

https://mobile.twitter.com/BlockSecTeam/status/1547456591900749824

https://medium.com/numen-cyber-labs/spacegodzilla-attack-event-analysis-d29a061b17e1

https://learnblockchain.cn/article/4396

https://learnblockchain.cn/article/4395 *** math behind such attack


20220710 Omni NFT - Reentrancy

Lost: $1.4M

Testing

forge test --contracts ./src/test/Omni_exp.sol -vv

Contract

Omni_exp.sol

Link reference

https://twitter.com/SlowMist_Team/status/1546379086792388609

https://etherscan.io/tx/0x05d65e0adddc5d9ccfe6cd65be4a7899ebcb6e5ec7a39787971bcc3d6ba73996


20220706 FlippazOne NFT - Access control

The ownerWithdrawAllTo() without onlyOwner can call it.

Testing

forge test --contracts ./src/test/FlippazOne.sol -vvvv

Contract

FlippazOne.sol

Link reference

https://twitter.com/bertcmiller/status/1544496577338826752

https://etherscan.io/tx/0x8bded20c1db5a1d5f595b15e682a95ce11d3c895d6031147fa49c4ffa5729a30


20220701 Quixotic - Optimism NFT Marketplace

Lost: $100K

fillSellOrder function only check seller signature.

ECDSA signature combined with v r s, if recoveredAddress == sellOrder.seller; sellorder execute.

Testing

forge test --contracts ./src/test/Quixotic_exp.sol -vv

Contract

Quixotic_exp.sol

Link reference

https://twitter.com/1nf0s3cpt/status/1542808565349777408

https://twitter.com/SlowMist_Team/status/1542795627603857409

https://optimistic.etherscan.io/tx/0x5dc519726e1236eb846271f6699e03cdd1a8fd593a2900c71cd2aabbdb7c92e6


20220626 XCarnival - Infinite Number of Loans

Lost: 3087 ETH (~$3.87M)

Testing

forge test --contracts ./src/test/XCarnival.exp.sol -vv

Contract

XCarnival.exp.sol

Link reference

https://twitter.com/XCarnival_Lab/status/1541226298399653888

https://twitter.com/peckshield/status/1541047171453034501

https://twitter.com/BlockSecTeam/status/1541070850505723905


20220624 Harmony's Horizon Bridge - Private key compromised

Lost: $100 million

Private key compromised case of Multisig wallet

Testing

forge test --contracts ./src/test/Harmony_multisig.sol -vvvv

Contract

Harmony_multisig.sol

Link reference

https://twitter.com/harmonyprotocol/status/1540110924400324608

https://twitter.com/0xIvo/status/1540165571681128448

https://twitter.com/1nf0s3cpt/status/1540139812715261952


20220618 SNOOD - Miscalculation on _spendAllowance

Lost: 104 ETH

On _spendAllowance function they use _getStandardAmount and should be _getReflectedAmount

Testing

forge test --contracts ./src/test/Snood_poc.t.sol -vv

Contract

Snood_poc.t.sol

Link reference

https://ethereum.stackexchange.com/questions/130472/attack-on-erc-777-smart-contract-and-uniswapv2pair-resulting-in-104-eth-liquidit

https://etherscan.io/tx/0x9a6227ef97d7ce75732645bd604ef128bb5dfbc1bfbe0966ad1cd2870d45a20e

https://ethtx.info/mainnet/0x9a6227ef97d7ce75732645bd604ef128bb5dfbc1bfbe0966ad1cd2870d45a20e/


20220616 InverseFinance - Flashloan & Price Oracle Manipulation

Lost: 53.2445 WBTC and 99,976.29 USDT

Testing

forge test --contracts ./src/test/InverseFinance_exp.sol -vv

Contract

InverseFinance_exp.sol

Link reference

https://twitter.com/peckshield/status/1537382891230883841

https://twitter.com/SlowMist_Team/status/1537602909512376321

https://blocksecteam.medium.com/price-oracle-manipulation-attack-on-inverse-finance-a5544218ea91

https://www.certik.com/resources/blog/6LbL57WA3iMNm8zd7q111R-inverse-finance-incident-analysis

https://etherscan.io/tx/0x958236266991bc3fe3b77feaacea120f172c0708ad01c7a715b255f218f9313c


20220608 GYMNetwork - Access control

Lost: $2.1 million

Testing

forge test --contracts ./src/test/Gym_2_exp.sol -vv

Contract

Gym_2_exp.sol

Link reference

https://twitter.com/peckshield/status/1534423219607719936

https://twitter.com/1nf0s3cpt/status/1534464698069884929

https://www.jinse.com/news/blockchain/1658455.html


20220608 Optimism - Wintermute - Signature replay

Lost: 20 million Optimism (OP) tokens returned 17 million of them

Testing

forge test --contracts ./src/test/Optimism_exp.sol -vv

Contract

Optimism_exp.sol

Link reference

https://inspexco.medium.com/how-20-million-op-was-stolen-from-the-multisig-wallet-not-yet-owned-by-wintermute-3f6c75db740a

https://optimistic.etherscan.io/tx/0x75a42f240d229518979199f56cd7c82e4fc1f1a20ad9a4864c635354b4a34261

https://optimistic.etherscan.io/tx/0x00a3da68f0f6a69cb067f09c3f7e741a01636cbc27a84c603b468f65271d415b


20220606 Discover - Flashloan & Price Oracle Manipulation

Lost: 49 BNB

Testing

forge test --contracts ./src/test/Discover_exp.sol -vv

Contract

Discover_exp.sol

Link reference

https://www.twitter.com/BeosinAlert/status/1533734518623899648

https://www.anquanke.com/post/id/274003

https://bscscan.com/tx/0x8a33a1f8c7af372a9c81ede9e442114f0aabb537e5c3a22c0fd7231c4820f1e9

https://bscscan.com/tx/0x1dd4989052f69cd388f4dfbeb1690a3f3a323ebb73df816e5ef2466dc98fa4a4


20220529 NOVO Protocol - Flashloan & Price Oracle Manipulation

Lost: 279 BNB

Testing

forge test --contracts ./src/test/Novo_exp.sol -vvv

Contract

Novo_exp.sol

Link reference

https://www.panewslab.com/zh_hk/articledetails/f40t9xb4.html

https://bscscan.com/tx/0xc346adf14e5082e6df5aeae650f3d7f606d7e08247c2b856510766b4dfcdc57f

https://bscscan.com/address/0xa0787daad6062349f63b7c228cbfd5d8a3db08f1#code


20220524 HackDao - Skim token balance

Testing

forge test --contracts ./src/test/HackDao_exp.sol -vvv

Contract

HackDao_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1529084919976034304


20220517 ApeCoin (APE) - Flashloan

Lost: $1.1 million

buys vault token -> redeems NFTs -> claims airdrop of 60k APE -> re-supply's the pool Testing

forge test --contracts ./src/test/Bayc_apecoin_exp.sol -vvv

Contract

Bayc_apecoin_exp.sol

Link reference

https://etherscan.io/tx/0xeb8c3bebed11e2e4fcd30cbfc2fb3c55c4ca166003c7f7d319e78eaab9747098

https://news.coincu.com/73892-the-flashloan-attack-on-the-ape-airdrop-to-claim-1-1-million-of-ape-tokens/


20220508 Fortress Loans - Malicious Proposal & Price Oracle Manipulation

Lost: 1,048.1 ETH + 400,000 DAI (~$3.00M)

Testing

forge test --contracts ./src/test/FortressLoans.exp.sol -vvv

Contract

FortressLoans.exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1523530484877209600

https://www.certik.com/resources/blog/k6eZOpnK5Kdde7RfHBZgw-fortress-loans-exploit


20220430 Rari Capital/Fei Protocol - Flashloan Attack + Reentrancy

Lost: $80 million

Testing

forge test --contracts ./src/test/Rari_exp.t.sol -vv

Contract

Rari_exp.t.sol

Link reference

https://certik.medium.com/fei-protocol-incident-analysis-8527440696cc

https://twitter.com/peckshield/status/1520369315698016256

https://etherscan.io/tx/0xab486012f21be741c9e674ffda227e30518e8a1e37a5f1d58d0b0d41f6e76530


20220424 Wiener DOGE - Flashloan

Lost: 78 BNB

Testing

forge test --contracts ./src/test/Wdoge_exp.sol -vvv

Contract

Wdoge_exp.sol

Link reference

https://coinyuppie.com/four-combinations-of-hackers-analysis-of-attacks-on-wiener-doge-last-kilometer-medamon-and-pidao-projects/

https://twitter.com/solid_group_1/status/1519034573354676224

https://bscscan.com/tx/0x4f2005e3815c15d1a9abd8588dd1464769a00414a6b7adcbfd75a5331d378e1d


20220428 DEUS DAO - Flashloan & Price Oracle Manipulation

Lost: $13 million

Testing

forge test --contracts ./src/test/deus_exp.sol -vv

Contract

deus_exp.sol

Link reference

https://twitter.com/peckshield/status/1519531866109317121

https://ftmscan.com/tx/0xe374495036fac18aa5b1a497a17e70f256c4d3d416dd1408c026f3f5c70a3a9c


20220423 Akutar NFT - Denial of Service

Lost: 34M USD

Testing

forge test --contracts ./src/test/AkutarNFT_exp.sol -vv  

Contract

AkutarNFT_exp.sol

Link reference

https://blocksecteam.medium.com/how-akutar-nft-loses-34m-usd-60d6cb053dff

https://etherscan.io/address/0xf42c318dbfbaab0eee040279c6a2588fa01a961d#code


20220421 Zeed Finance - Reward distribution flaw

Lost: $1 million

Testing

forge test --contracts ./src/test/Zeed_exp.sol -vv

Contract

Zeed_exp.sol

Link reference

https://www.cryptotimes.io/hacker-leaves-1m-to-self-destruct-after-zeed-protocol-exploit/

https://medium.com/@zeedcommunity/the-solution-for-the-yeed-lp-pool-attack-a120c53948cd

https://bscscan.com/tx/0x0507476234193a9a5c7ae2c47e4c4b833a7c3923cefc6fd7667b72f3ca3fa83a


20220416 BeanstalkFarms - DAO + Flashloan

Lost: $182 million

Testing

forge test --contracts ./src/test/Beanstalk_exp.sol -vv

Contract

Beanstalk_exp.sol

Link reference

https://rekt.news/beanstalk-rekt/

https://medium.com/uno-re/beanstalk-farms-hacked-total-damage-is-182-million-b699dd3e5c8

https://twitter.com/peckshield/status/1515680335769456640

https://etherscan.io/tx/0x68cdec0ac76454c3b0f7af0b8a3895db00adf6daaf3b50a99716858c4fa54c6f

https://etherscan.io/tx/0xcd314668aaa9bbfebaf1a0bd2b6553d01dd58899c508d4729fa7311dc5d33ad7


20220415 Rikkei Finance - Access control & Price Oracle Manipulation

Lost: $1.1 million (2671 BNB)

Testing

forge test --contracts ./src/test/Rikkei_exp.sol -vv

Contract

Rikkei_exp.sol

Link reference

https://blockmagnates.com/rikkei-finance-hack/

https://knownseclab.com/news/625e865cf1c544005a4bdaf2

https://rikkeifinance.medium.com/rikkei-finance-incident-investigation-report-b5b1745b0155

https://bscscan.com/tx/0x93a9b022df260f1953420cd3e18789e7d1e095459e36fe2eb534918ed1687492


20220412 ElephantMoney - Flashloan & Price Oracle Manipulation

Lost: $11.2 million (27,416.46 BNB)

Testing

forge test --contracts ./src/test/Elephant_Money_poc.sol -vv

Contract

Elephant_Money_poc.sol

Link reference

https://medium.com/elephant-money/reserve-exploit-52fd36ccc7e8

https://twitter.com/peckshield/status/1514023036596330496

https://twitter.com/BlockSecTeam/status/1513966074357698563

https://bscscan.com/tx/0xec317deb2f3efdc1dbf7ed5d3902cdf2c33ae512151646383a8cf8cbcd3d4577


20220409 GYMNetwork - Flashloan + token migrate flaw

Lost: 1,327 WBNB

Testing

forge test --contracts ./src/test/Gym_1_exp.sol -vv

Contract

Gym_1_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1512832398643265537

https://medium.com/@Beosin_com/beosin-analysis-of-the-attack-on-gymdefi-e5a23bfd93fe

https://bscscan.com/tx/0xa5b0246f2f8d238bb56c0ddb500b04bbe0c30db650e06a41e00b6a0fff11a7e5


20220329 Ronin Network - Bridge

Lost: $624 million

Testing

forge test --contracts ./src/test/Ronin_exp.sol -vv

Contract

Ronin_exp.sol

Link reference

https://rekt.news/ronin-rekt/

https://etherscan.io/tx/0xc28fad5e8d5e0ce6a2eaf67b6687be5d58113e16be590824d6cfa1a94467d0b7

https://etherscan.io/tx/0xed2c72ef1a552ddaec6dd1f5cddf0b59a8f37f82bdda5257d9c7c37db7bb9b08


20220329 Redacted Cartel - Custom Approval Logic

Testing

forge test --contracts ./src/test/RedactedCartel_exp.sol -vv

Contract

RedactedCartel_exp.sol

Link reference

https://medium.com/immunefi/redacted-cartel-custom-approval-logic-bugfix-review-9b2d039ca2c5


20220327 Revest Finance - Reentrancy

Lost: $11.2 million

Testing

forge test --contracts ./src/test/Revest_exp.sol -vv

Contract

Revest_exp.sol

Link reference

https://blocksecteam.medium.com/revest-finance-vulnerabilities-more-than-re-entrancy-1609957b742f

https://etherscan.io/tx/0xe0b0c2672b760bef4e2851e91c69c8c0ad135c6987bbf1f43f5846d89e691428


20220326 Auctus

Lost: $726 k

Testing

forge test --contracts ./src/test/Auctus_exp.sol -vv

Contract

Auctus_exp.sol

Link reference

https://twitter.com/AuctusOptions/status/1508647849663291398?cxt=HHwWjICzpbzO5e8pAAAA

https://etherscan.io/tx/0x2e7d7e7a6eb157b98974c8687fbd848d0158d37edc1302ea08ee5ddb376befea


20220322 CompoundTUSDSweepTokenBypass

Testing

forge test --contracts ./src/test/CompoundTusd_exp.sol -vv

Contract

CompoundTusd_exp.sol

Link reference

https://blog.openzeppelin.com/compound-tusd-integration-issue-retrospective/


20220321 OneRing Finance - Flashloan & Price Oracle Manipulation

Lost: $1.45 million

Testing

forge test --contracts ./src/test/OneRing_exp.sol -vv

Contract

OneRing_exp.sol

Link reference

https://medium.com/oneringfinance/onering-finance-exploit-post-mortem-after-oshare-hack-602a529db99b

https://ftmscan.com/tx/0xca8dd33850e29cf138c8382e17a19e77d7331b57c7a8451648788bbb26a70145


20220320 Li.Fi - Bridges

Lost: $570K

Testing

forge test --contracts ./src/test/LiFi_exp.sol -vvvv

Contract

LiFi_exp.sol

Link reference

https://blog.li.fi/20th-march-the-exploit-e9e1c5c03eb9

https://twitter.com/lifiprotocol/status/1505738407938387971

https://etherscan.io/tx/0x4b4143cbe7f5475029cf23d6dcbb56856366d91794426f2e33819b9b1aac4e96

Fix

implemented a whitelist to only allow calls to approved DEXs.


20220320 Umbrella Network - Underflow

Testing

forge test --contracts ./src/test/Umbrella_exp.sol -vv

Contract

Umbrella_exp.sol

Link reference

https://medium.com/uno-re/umbrella-network-hacked-700k-lost-97285b69e8c7

https://etherscan.io/tx/0x33479bcfbc792aa0f8103ab0d7a3784788b5b0e1467c81ffbed1b7682660b4fa


20220313 Hundred Finance - ERC667 Reentrancy

Lost: $1.7 million

Testing

forge test --contracts ./src/test/HundredFinance_exp.sol -vv

Contract

HundredFinance_exp.sol

Link reference

https://medium.com/immunefi/a-poc-of-the-hundred-finance-heist-4121f23a098

https://gnosisscan.io/tx/0x534b84f657883ddc1b66a314e8b392feb35024afdec61dfe8e7c510cfac1a098


20220313 Paraluni - Flashloan & Reentrancy

Lost: $1.7 million

Testing

forge test --contracts ./src/test/Paraluni_exp.sol -vv

Contract

Paraluni_exp.sol

Link reference

https://halborn.com/explained-the-paraluni-hack-march-2022/

https://twitter.com/peckshield/status/1502815435498176514

https://mobile.twitter.com/paraluni/status/1502951606202994694

https://zhuanlan.zhihu.com/p/517535530

https://bscscan.com/tx/0x70f367b9420ac2654a5223cc311c7f9c361736a39fd4e7dff9ed1b85bab7ad54


20220309 Fantasm Finance - Business logic in mint()

Lost: $2.6 million

Testing

forge test --contracts ./src/test/Fantasm_exp.sol -vv

Contract

Fantasm_exp.sol

Link reference

https://twitter.com/fantasm_finance/status/1501569232881995785

https://medium.com/quillhash/fantom-based-protocol-fantasm-suffers-2-6m-exploit-32de8191ccd4

https://www.certik.com/resources/blog/5p92144WQ44Ytm1AL4Jt9X-fantasm-finance


20220305 Bacon Protocol - Reentrancy

Lost: $1 million

Testing

forge test --contracts ./src/test/Bacon_exp.sol -vv

Contract

Bacon_exp.sol

Link reference

https://twitter.com/peckshield/status/1500105933128495108

https://etherscan.io/tx/0xacfcaa8e1c482148f9f2d592c78ca7a27934c7333dab31978ed0aef333a28ab6

https://etherscan.io/tx/0x7d2296bcb936aa5e2397ddf8ccba59f54a178c3901666b49291d880369dbcf31


20220303 TreasureDAO - Zero Fee

Lost: $1 million

Testing

forge test --contracts ./src/test/TreasureDAO_exp.sol -vv

Contract

TreasureDAO_exp.sol

Link reference

https://slowmist.medium.com/analysis-of-the-treasuredao-zero-fee-exploit-73791f4b9c14

https://arbiscan.io/tx/0x82a5ff772c186fb3f62bf9a8461aeadd8ea0904025c3330a4d247822ff34bc02


20220214 BuildFinance - DAO

Lost: $470k

Testing

forge test --contracts ./src/test/BuildF_exp.sol -vv

Contract

BuildF_exp.sol

Link reference

https://twitter.com/finance_build/status/1493223190071554049

https://www.cryptotimes.io/build-finance-suffered-hostile-governance-takeover-lost-470k/

https://etherscan.io/tx/0x544e5849b71b98393f41d641683586d0b519c46a2eeac9bcb351917f40258a85


20220208 Sandbox LAND - Access control

Testing

forge test --contracts ./src/test/Sandbox_exp.sol -vv

Contract

Sandbox_exp.sol

Link reference

https://slowmist.medium.com/the-vulnerability-behind-the-sandbox-land-migration-2abf68933170

https://etherscan.io/tx/0x34516ee081c221d8576939f68aee71e002dd5557180d45194209d6692241f7b1


20220206 Meter - Bridge

Lost: $4.3 million

Testing

Solana TBD
forge test --contracts ./src/test/meter_exp.sol -vv

Contract

meter_exp.sol

Link reference

https://twitter.com/ishwinder/status/1490227406824685569

https://blog.chainsafe.io/breaking-down-the-meter-io-hack-a46a389e7ae4

this does not seem to be the correct transaction though: https://moonriver.moonscan.io/tx/0x5a87c24d0665c8f67958099d1ad22e39a03aa08d47d00b7276b8d42294ee0591


20220128 Qubit Finance - Bridge address(0).safeTransferFrom() does not revert

Lost: $80 million

Testing

forge test --contracts ./src/test/Qubit_exp.sol -vv

Contract

Qubit_exp.sol

Link reference

https://rekt.news/qubit-rekt/

https://medium.com/@QubitFin/protocol-exploit-report-305c34540fa3

https://etherscan.io/address/0xd01ae1a708614948b2b5e0b7ab5be6afa01325c7 https://etherscan.io/tx/0xac7292e7d0ec8ebe1c94203d190874b2aab30592327b6cc875d00f18de6f3133 https://bscscan.com/tx/0x50946e3e4ccb7d39f3512b7ecb75df66e6868b9af0eee8a7e4b61ef8a459518e


20220118 Multichain (Anyswap) - Insufficient Token Validation

Lost: $1.4 million

Testing

forge test --contracts ./src/test/Anyswap_poc.t.sol -vv

Contract

Anyswap_poc.t.sol

Link reference

https://medium.com/zengo/without-permit-multichains-exploit-explained-8417e8c1639b

https://twitter.com/PeckShieldAlert/status/1483363515411099651

https://etherscan.io/tx/0xe50ed602bd916fc304d53c4fed236698b71691a95774ff0aeeb74b699c6227f7


20211221 Visor Finance - Reentrancy

Lost: $8.2 million

Testing

forge test --contracts ./src/test/Visor_exp.t.sol -vv

Contract

Visor_exp.t.sol

Link reference

https://beosin.medium.com/two-vulnerabilities-in-one-function-the-analysis-of-visor-finance-exploit-a15735e2492

https://twitter.com/GammaStrategies/status/1473306777131405314

https://etherscan.io/tx/0x69272d8c84d67d1da2f6425b339192fa472898dce936f24818fda415c1c1ff3f


20211218 Grim Finance - Flashloan & Reentrancy

Lost: $30 million

Testing

forge test --contracts ./src/test/Grim_exp.sol -vv

Contract

Grim_exp.sol

Link reference

https://cointelegraph.com/news/defi-protocol-grim-finance-lost-30m-in-5x-reentrancy-hack

https://rekt.news/grim-finance-rekt/

https://ftmscan.com/tx/0x19315e5b150d0a83e797203bb9c957ec1fa8a6f404f4f761d970cb29a74a5dd6


20211130 MonoX Finance - Price Manipulation

Lost: $31 million

Testing

forge test --contracts ./src/test/Mono_exp.t.sol -vv

Contract

Mono_exp.t.sol

Link reference

https://slowmist.medium.com/detailed-analysis-of-the-31-million-monox-protocol-hack-574d8c44a9c8

https://knownseclab.com/news/61a986811992da0067558749

https://www.tuoniaox.com/news/p-521076.html

https://polygonscan.com/tx/0x5a03b9c03eedcb9ec6e70c6841eaa4976a732d050a6218969e39483bb3004d5d

https://etherscan.io/tx/0x9f14d093a2349de08f02fc0fb018dadb449351d0cdb7d0738ff69cc6fef5f299


20211027 CreamFinance - Price Manipulation

Lost: $130M

Testing

 forge test --contracts ./src/test/Cream_2_exp.sol -vvv

Contract

Cream_2_exp.sol

Link reference

https://medium.com/immunefi/hack-analysis-cream-finance-oct-2021-fc222d913fc5


20210916 SushiSwap Miso

Lost: All funds returned

Testing

forge test --contracts ./src/test/Sushimiso_exp.sol -vv

Contract

Sushimiso_exp.sol

Link reference

https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong

https://etherscan.io/tx/0x78d6355703507f88f2090eb780d245b0ab26bf470eabdb004761cedf3b1cda44


20210915 Nimbus Platform

Lost: 1.45 ETH

Testing

forge test --contracts ./src/test/Nimbus_exp.sol -vv

Contract

Nimbus_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1438100688215560192


20210915 NowSwap Platform

Lost: 158.28 WETH and 535,706 USDT

Testing

forge test --contracts ./src/test/NowSwap_exp.sol -vv

Contract

NowSwap_exp.sol

Link reference

https://twitter.com/BlockSecTeam/status/1438100688215560192


20210912 ZABU Finance - Deflationary token uncompatible

Testing

forge test --contracts src/test/ZABU_exp.sol -vvv

Contract

ZABU_exp.sol

Link reference

https://slowmist.medium.com/brief-analysis-of-zabu-finance-being-hacked-44243919ea29


20210903 DAO Maker - Bad Access Controal

Lost: $4 million

Testing

forge test --contracts ./src/test/DaoMaker_exp.sol -vv

Contract

DaoMaker_exp.sol

Link reference

https://twitter.com/Mudit__Gupta/status/1434059922774237185

https://etherscan.io/tx/0xd5e2edd6089dcf5dca78c0ccbdf659acedab173a8ab3cb65720e35b640c0af7c


20210830 Cream Finance - Flashloan Attack + Reentrancy

Lost: $18 million

Testing

forge test --contracts ./src/test/Cream_exp.sol -vv

Contract

Cream_exp.sol

Link reference

https://twitter.com/peckshield/status/1432249600002478081

https://twitter.com/creamdotfinance/status/1432249773575208964

https://etherscan.io/tx/0xa9a1b8ea288eb9ad315088f17f7c7386b9989c95b4d13c81b69d5ddad7ffe61e


20210817 XSURGE - Flashloan Attack + Reentrancy

Lost: $5 million

Testing

forge test --contracts ./src/test/XSURGE_exp.t.sol -vv

Contract

XSURGE_exp.t.sol

Link reference

https://beosin.medium.com/a-sweet-blow-fb0a5e08657d

https://medium.com/@Knownsec_Blockchain_Lab/knownsec-blockchain-lab-comprehensive-analysis-of-xsurge-attacks-c83d238fbc55

https://bscscan.com/tx/0x8c93d6e5d6b3ec7478b4195123a696dbc82a3441be090e048fe4b33a242ef09d


20210811 Poly Network - Bridge, getting around modifier through cross-chain message

Lost: $611 million

Testing

forge test --contracts ./src/test/PolyNetwork/PolyNetwork_exp.sol -vv

Contract

PolyNetwork_exp.sol

Link reference

https://rekt.news/polynetwork-rekt/

https://slowmist.medium.com/the-root-cause-of-poly-network-being-hacked-ec2ee1b0c68f

https://etherscan.io/tx/0xb1f70464bd95b774c6ce60fc706eb5f9e35cb5f06e6cfe7c17dcda46ffd59581/advanced

https://github.com/polynetwork/eth-contracts/tree/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b

https://www.breadcrumbs.app/reports/671

FIX

One of the biggest design lessons that people need to take away from this is: if you have cross-chain relay contracts like this, MAKE SURE THAT THEY CAN'T BE USED TO CALL SPECIAL CONTRACTS. The EthCrossDomainManager shouldn't have owned the EthCrossDomainData contract.


20210804 WaultFinace - FlashLoan price manipulation

Lost: 390 ETH

Testing

forge test --contracts ./src/test/WaultFinance_exp.sol -vvv

Contract

WaultFinance_exp.sol

Link reference

https://medium.com/@Knownsec_Blockchain_Lab/wault-finance-flash-loan-security-incident-analysis-368a2e1ebb5b

https://inspexco.medium.com/wault-finance-incident-analysis-wex-price-manipulation-using-wusdmaster-contract-c344be3ed376


20210728 Levyathan Finance - (I) Lost keys and minting (II) Vulnerable emergencyWithdraw

Lost: $1.5 million

Testing

forge test --contracts ./src/test/Levyathan_poc.sol -vv

Contract

Levyathan_poc.sol

Link reference

https://levyathan-index.medium.com/post-mortem-levyathan-c3ff7f9a6f65


20210710 Chainswap - Bridge, logic flaw

Lost: $4.4 million

Testing

forge test --contracts ./src/test/Chainswap_exp2.sol -vv

Contract

Chainswap_exp2.sol

Link reference

https://twitter.com/real_n3o/status/1414071223940571139

https://rekt.news/chainswap-rekt/

https://chain-swap.medium.com/chainswap-exploit-11-july-2021-post-mortem-6e4e346e5a32


20210702 Chainswap - Bridge, logic flaw

Lost: $.8 million

Testing

forge test --contracts ./src/test/Chainswap_exp1.sol -vv

Contract

Chainswap_exp1.sol

Link reference

https://chain-swap.medium.com/chainswap-post-mortem-and-compensation-plan-90cad50898ab


20210628 SafeDollar - Deflationary token uncompatible

Lost: $.2 million

Testing

forge test --contracts src/test/SafeDollar_exp.sol -vvv

Contract

SafeDollar_exp.sol

Link reference

https://twitter.com/peckshield/status/1409443556251430918


20210622 Eleven Finance - Doesn’t burn shares

Testing

forge test --contracts ./src/test/Eleven.sol -vv

Contract

Eleven.sol

Link reference

https://peckshield.medium.com/eleven-finance-incident-root-cause-analysis-123b5675fa76

https://bscscan.com/tx/0xeaaa8f4d33b1035a790f0d7c4eb6e38db7d6d3b580e0bbc9ba39a9d6b80dd250


20210607 88mph NFT - Access control

Testing

forge test --contracts ./src/test/88mph_exp.sol -vv

Contract

88mph_exp.sol

Link reference

https://medium.com/immunefi/88mph-function-initialization-bug-fix-postmortem-c3a2282894d3


20210603 PancakeHunny - Incorrect calculation

Testing

forge test --contracts ./src/test/PancakeHunny_exp.sol -vv

Contract

PancakeHunny_exp.sol

Link reference

https://medium.com/hunnyfinance/pancakehunny-post-mortem-analysis-de78967401d8

https://bscscan.com/tx/0x765de8357994a206bb90af57dcf427f48a2021f2f28ca81f2c00bc3b9842be8e


20210519 PancakeBunny - Price Oracle Manipulation

Testing

forge test --contracts ./src/test/PancakeBunny_exp.sol -vv

Contract

PancakeBunny_exp.sol

Link reference

https://rekt.news/pancakebunny-rekt/

https://bscscan.com/tx/0x897c2de73dd55d7701e1b69ffb3a17b0f4801ced88b0c75fe1551c5fcce6a979


20210509 RariCapital - Cross Contract Reentrancy

Testing

forge test --contracts ./src/test/RariCapital_exp.sol -vv

Contract

RariCapital_exp.sol

Link reference

https://rekt.news/rari-capital-rekt/

https://etherscan.com/tx/0x171072422efb5cd461546bfe986017d9b5aa427ff1c07ebe8acc064b13a7b7be


20210508 Value Defi - Cross Contract Reentrancy

Testing

forge test --contracts ./src/test/ValueDefi_exp.sol -vv 

Contract

ValueDefi_exp.sol

Link reference

https://rekt.news/rari-capital-rekt/

https://bscscan.com/tx/0xa00def91954ba9f1a1320ef582420d41ca886d417d996362bf3ac3fe2bfb9006


20210428 Uranium - Miscalculation

Lost: $50 million

Testing

forge test --contracts ./src/test/Uranium_exp.sol -vv

Contract

Uranium_exp.sol

Link reference

https://twitter.com/FrankResearcher/status/1387347025742557186

https://bscscan.com/tx/0x5a504fe72ef7fc76dfeb4d979e533af4e23fe37e90b5516186d5787893c37991


20210308 DODO - Flashloan Attack

Lost: $700,000

Testing

forge test --contracts ./src/test/dodo_flashloan_exp.sol -vv

Contract

dodo_flashloan_exp.sol

Link reference

https://blog.dodoex.io/dodo-pool-incident-postmortem-with-a-little-help-from-our-friends-327e66872d42

https://halborn.com/explained-the-dodo-dex-hack-march-2021/

https://etherscan.io/tx/0x395675b56370a9f5fe8b32badfa80043f5291443bd6c8273900476880fb5221e


20201229 Cover Protocol

Testing

forge test --contracts ./src/test/Cover_exp.sol -vv

Contract

Cover_exp.sol

Link reference

https://mudit.blog/cover-protocol-hack-analysis-tokens-minted-exploit/

https://slowmist.medium.com/a-brief-analysis-of-the-cover-protocol-hacked-event-700d747b309c


20201121 Pickle Finance

Lost: $20 million

Testing

forge test --contracts ./src/test/Pickle_exp.sol -vv

Contract

Pickle_exp.sol

Link reference

https://github.com/banteg/evil-jar

https://etherscan.io/tx/0xe72d4e7ba9b5af0cf2a8cfb1e30fd9f388df0ab3da79790be842bfbed11087b0


20201026 Harvest Finance - Flashloan Attack

Lost: $33.8 million

Testing

forge test --contracts ./src/test/HarvestFinance_exp.sol -vv

Contract

HarvestFinance_exp.sol

Link reference

https://rekt.news/harvest-finance-rekt/

https://etherscan.io/tx/0x35f8d2f572fceaac9288e5d462117850ef2694786992a8c3f6d02612277b0877

20200804 Opyn Protocol - msgValue in loop

Testing

forge test --contracts ./src/test/Opyn.exp.sol -vv

Contract

Opyn.exp.sol

Link reference

https://medium.com/opyn/opyn-eth-put-exploit-post-mortem-1a009e3347a8

https://etherscan.io/tx/0x56de6c4bd906ee0c067a332e64966db8b1e866c7965c044163a503de6ee6552a


20200618 Bancor Protocol - Access Control

Testing

forge test --contracts ./src/test/Bancor_exp.sol -vv

Contract

Bancor_exp.sol

Link reference

https://blog.bancor.network/bancors-response-to-today-s-smart-contract-vulnerability-dc888c589fe4

https://etherscan.io/address/0x5f58058c0ec971492166763c8c22632b583f667f


20180422 Beauty Chain - Integer Overflow

Lost: $900 million

Testing

forge test --contracts ./src/test/BEC_exp.sol -vv

Contract

BEC_exp.sol

Link reference

https://etherscan.io/tx/0xad89ff16fd1ebe3a0a7cf4ed282302c06626c1af33221ebe0d3a470aba4a660f

https://etherscan.io/address/0xc5d105e63711398af9bbff092d4b6769c82f793d#code


20171106 Parity - 'Accidentally Killed It'

Lost: 514k ETH

Testing

forge test --contracts ./src/test/Parity_kill.sol -vvvv

Contract

Parity_kill.sol

Link reference

https://elementus.io/blog/which-icos-are-affected-by-the-parity-wallet-bug/

https://etherscan.io/tx/0x05f71e1b2cb4f03e547739db15d080fd30c989eda04d37ce6264c5686e0722c9

https://etherscan.io/tx/0x47f7cff7a5e671884629c93b368cb18f58a993f4b19c2a53a8662e3f1482f690

View Gas Reports

Foundry also has the ability to report the gas used per function call which mimics the behavior of hardhat-gas-reporter. Generally speaking if gas costs per function call is very high, then the likelihood of its success is reduced. Gas optimization is an important activity done by smart contract developers.

Every poc in this repository can produce a gas report like this:

forge test --gas-report --contracts <contract> -vvv

For Example: Let us find out the gas used in the Audius poc

Execution

forge test --gas-report --contracts ./src/test/Audius.exp.sol -vvv 

Demo

AudiusPocGasReport.gif

Bug Reproduce

Moved to DeFiVulnLabs

FlashLoan Testing

Moved to DeFiLabs


Transaction debugging tools

Phalcon | Tx.viewer | Cruise |Ethtx | Tenderly

Ethereum Signature Database

4byte | sig.eth | etherface

Useful tools

ABI to interface | Get ABI for unverified contracts | ETH Calldata Decoder

Hacks Dashboard

Slowmist | Defillama | Defiyield | Rekt | Cryptosec


Download Details:

Author: SunWeb3Sec
Source Code: https://github.com/SunWeb3Sec/DeFiHackLabs 

#ethereum #solidity #web3 

DeFiHackLabs: Reproduce DeFi hacked incidents using Foundry

Web3 Blockchain | Build and Deploy a Web3 Blockchain Crowdfunding Platform

With a stunning design, connected to the blockchain, metamask pairing, interaction with smart contracts, sending Ethereum through the blockchain network, writing solidity code, and, most importantly, the ability to create create, view, and donate to crowdfunding campaigns directly through the blockchain; this course is perfect to fully understand how web3, blockchain, Solidity, and smart contracts truly work behind the scenes.

Time Stamps 👇
00:00:00 Intro
00:09:31 Smart Contract
00:53:29 Sidebar
01:03:52 Navbar
01:30:48 Create Campaign
01:54:24 Web3 Context
02:11:27 Homepage
02:44:16 Campaign Details

⭐Thirdweb - https://thirdweb.com/?utm_source=youtube&utm_medium=jsmastery&utm_campaign=crowdfund 

📙 The Web 3.0 Developer Roadmap : https://resource.jsmasterypro.com/web3.0-roadmap 
📙 The Ultimate Solidity CheatSheet : https://resource.jsmasterypro.com/solidity-cheatsheet 

📚 Materials/References:
GitHub Code (give it a star ⭐) - https://github.com/adrianhajdin/project_crowdfunding 
Assets: https://minhaskamal.github.io/DownGit/#/home?url=https://github.com/adrianhajdin/project_crowdfunding/tree/master/client/src/assets 
GitHub Gist Code - https://gist.github.com/adrianhajdin/6e2ad3c9f383d77c369322476c228b73 
Metamask: https://metamask.io/ 
Goerli Faucet: https://goerlifaucet.com/ 

Subscribe: https://www.youtube.com/@javascriptmastery/featured 

#web3 #blockchain #solidity 

Web3 Blockchain | Build and Deploy a Web3 Blockchain Crowdfunding Platform
Blockchain Dev

Blockchain Dev

1669444869

Become a Web3 Developer - Blockchain Developer Roadmap

This tutorial will explain what is a Web3 developer and how to become a Web3 developer without becoming lost in the sea of knowledge. Blockchain Developer Roadmap - Become a Web 3 Developer

⭐️ Timestamps ⭐️
00:00 | Why Learn Blockchain Development?
01:07 |  Become a Blockchain Expert 
03:43 | Blockchain Fundamentals/Theory
05:18 | Ethereum and Decentralized Apps
07:00 | Solidity/Smart Contract Fundamentals 
10:55 | Advanced Smart Contract Concepts
12:38 | Interacting With Smart Contracts
14:20 | Professional Development Tools 
15:35 | Build Decentralized Applications

#web3 #blockchain #webjs #ethereum #solidity #smartcontract

Become a Web3 Developer - Blockchain Developer Roadmap
Blockchain Dev

Blockchain Dev

1668829890

Build Smart Contracts with JavaScript and Solidity

In this Blockchain tutorial for beginners, you'll learn how to build smart contracts using JavaScript and Solidity. Blockchain is redefining the internet and has come to stay.

The first time I tried to learn blockchain development, I felt overwhelmed.

This tutorial you're reading is what I wish I could send back in time to myself.

This will give you a strong foundation in blockchain development, and set you up for success in coding your own smart contracts.

In in addition to my explanation and code examples, I've included lots of videos you can use to supplement your learning.

Prerequisites

This tutorial assumes that you understand some foundational coding concepts. One of these that will be particularly helpful is the concept of object-oriented programming (OOP).

What is Blockchain?

The Blockchain is a network of transactions or assets called blocks where every block is connected to the others. Everyone here has equal access to the data circulating within the network.

You can see blockchain as a document that holds the details of transactions made by a group of people where everyone has a copy. Everyone must agree upon any updates before they are accepted.

Anyone who tries to mutilate their document without the others' consent is seen as fraudulent and will suffer predefined consequences.

For example, imagine that a group of friends (Njoku, Samson, and Ebere) decides to start a peer-to-peer savings account that must run for a certain period before a withdrawal is possible. The three agree that no one will be the boss, and each person will have equal access to the account to ensure trust. So they open an account.

Each time one of them deposits money, everyone gets a new account history document emailed to them. Whenever they decide to add a new member, the person becomes part of the signatories and gets a copy of the account history.

Everyone must consent before a withdrawal happens outside the proposed date. Not following these terms will incur consequences such as losing all of a person’s savings or leaving the association after paying a fine.

Blockchain is known as a decentralized technology since data and authority are shared equally among everybody in the network. It differs from centralized applications where the company owns the data, and the consumers just hope their data isn’t misused.

Examples of decentralized applications include Bitcoin and Ethereum, while centralized applications include Facebook and Google.

Blockchain technology falls under the category of Web 3 simply because it is the third phase of the internet in which users can read, write, and own data. Web 1 was the stage where users could only read data. Web 2 emerged sometime around the early 2000s and is the phase in which users can read and write data.

How Blockchain Works

In this section, I will explain what happens in a blockchain application behind the scenes.

We will begin by looking at how it works in theory and then how we can replicate it using a programming language that many devs already know – JavaScript.

Theory Behind the Blockchain

A blockchain is a connection of many blocks. So it begins with one block called the genesis block. Among other things, a block contains a hash, the previous block hash, and at least one transaction.

Every block in the blockchain keeps a record of its hash and the previous block’s hash to keep the network safe from hackers.

This implies that for a hacker to gain access and break the network, they need to generate the hashes and match them to the right block without breaking other blocks. Now that sounds really stressful and almost impossible. That is how secure blockchains are.

Next, any user on the network can perform at least one transaction. If the user has completed a set of transactions they need at a time, they can use those transactions to create a block. The block may now be added to the others.

The whole process of adding a new block is known as mining. The process secures and verifies the transactions contained in a block.

The hash of a block gets generated when mining. The process of calculating the hash is known as proof of work.

Blockchain in Practice

Let's use some JavaScript object-oriented programming to demonstrate how blockchain works. We are using the OOP method because blockchain programming uses the same pattern.

But before we start building, let's learn how to generate the hash for every block in a blockchain.

How to generate a block's hash

There are a lot of libraries for generating a block's hash. But we will use the SHA256 library for this tutorial. SHA256 is the most popular and is used by many renowned companies.

The SHA256 library takes any data given to it and returns a 64-character long string. Every string passed to the SHA256 library will always return the same 64-character long string every time.

You can check out https://emn178.github.io/online-tools/sha256.html and play around with the UI to see how it works.

Blockchains do not use just any hash generated because of security reasons. It specifies what the first few characters must look like for the hash to be accepted. This means that the hash will have to be generated several times, and a record of what changes on each iteration will be kept for reference purposes.

For example, a blockchain may specify that the only acceptable hash must contain three zeros at the beginning.

To calculate the hash, we need to add a number known as a nonce to the string being hashed. The nonce usually starts from zero and is incremented every time the hash is generated until a hash beginning with three zeros is found. Then the hash and the nonce will be stored for reference purposes.

The code below will calculate the hash for "man":

SHA256("man").toString()

However, we may run the function several times to get a string with three zeros at the beginning. Since the function will always return the same result, we need to add a number to the string and increment it until we get the hash we want.

The code we'd use for that will look like this:

let hash = "";
let nonce = 0;

while (hash.substring(0, 3) !== "000") {
  nonce++;
  hash = SHA256("man" + nonce).toString();
}

console.log(nonce);
console.log(hash);

This code will produce 000d6575d4670dae39df9944e54c27dc4837beab1db23e2de264a7c1a3f38b1a after 5707 times instead of 48b676e2b107da679512b793d5fd4cc4329f0c7c17a97cf6e0e3d1005b600b03.

This level of security measures taken to build blockchain applications makes them very reliable and acceptable.

Now that we understand how a hash is generated in blockchain, let's get back to demonstrating how blockchain works.

How Blockchain Works Using JavaScript

First, create a directory called intro_to_blockchain. Then open the directory in a terminal.

Run the following command and hit enter for all the prompts to initialize the project:

npm init

Create 2 files: blockchain.js and test.js:

touch blockchain.js test.js

We will use the blockchain.js file to write the code that emulates how blockchain works and use test.js to test the code and see the result.

In the blockchain.js, enter the following code:

class Blockchain {
    constructor () {
        this.chain = [this.createGenesisBlock()];
        this.pendingTransactions = [];    
    }
}

The code above declares a class named Blockchain. The constructor function is used to initialize the chain and pendingTransactions array.

The chain array will contain every block or group of transactions added to the network. The pendingTransactions array will hold all transactions that have not been added to a block.

Remember that a blockchain starts with a genesis block. That is why the chain array is initialized with an array containing a function that creates the genesis block. You may hardcode the genesis block into the chain array, too.

We now need to build the createGenesisBlock function. Use the code below:

  createGenesisBlock() {
    return {
      index: 1,
      timestamp: Date.now(),
      transactions: [],
      nonce: 0,
      hash: "hash",
      previousBlockHash: "previousBlockHash",
    };
  }

The function will only execute once because the constructor function runs only once – at the beginning of the program.

It is also the only time a random uncalculated hash or previousBlockHash is used because it is the first block in the chain and does not carry any transactions.

The next thing to do is to make a function to get the last block. Use the code below:

  getLastBlock() {
    return this.chain[this.chain.length - 1];
  };

This code will enable us to access the details of the most recent block added. Remember that we need to keep track of the previous block's hash.

Let's now add the code to calculate the hash of a block.

  
generateHash(previousBlockHash, timestamp, pendingTransactions) {
    let hash = "";
    let nonce = 0;

    while (hash.substring(0, 3) !== "000") {
      nonce++;
      hash = SHA256(
        previousBlockHash +
          timestamp +
          JSON.stringify(pendingTransactions) +
          nonce
      ).toString();
    }

    return { hash, nonce };
  }

To ensure that this works, install the SHA256 library using the following command:

npm i sha256

Import it at the top of your blockchain.js file like this:

const SHA256 = require("sha256");

We will now add a function that creates our transactions and adds them to the list of pending transactions. Enter the following code:

  createNewTransaction(amount, sender, recipient) {
    const newTransaction = {
      amount,
      sender,
      recipient,
    };

    this.pendingTransactions.push(newTransaction);
  }

The time has now arrived for us to build the last function – createNewBlock. It will enable us to add the pending transactions to a block, calculate the hash, and add the block to the chain. Type the code below:

  createNewBlock() {
    const timestamp = Date.now();
    const transactions = this.pendingTransactions;
    const previousBlockHash = this.getLastBlock().hash;
    const generateHash = this.generateHash(
      previousBlockHash,
      timestamp,
      transactions
    );

    const newBlock = {
      index: this.chain.length + 1,
      timestamp,
      transactions,
      nonce: generateHash.nonce,
      hash: generateHash.hash,
      previousBlockHash,
    };

    this.pendingTransactions = [];
    this.chain.push(newBlock);

    return newBlock;
  }

The code above uses the getLastBlock function to access the previous block's hash. It calculates the hash of the current block, adds all the detail of the new block in an object, clears the pendingTransactions array, and pushes the new block into the chain.

Let's export the Blockchain class to be able to access it outside the file:

module.exports = Blockchain;

How to Test the Code

We want to test the code we have written so far and see if it works as expected. We will navigate to the test.js file and begin by importing the Blockchain class that we exported a moment ago like this:

const Blockchain = require("./blockchain");

Now that we have the class here, we can make an instance of it and name it bitcoin:

let bitcoin = new Blockchain();

You may call it whatever you see fit, but I will use bitcoin because it is popular.

Let's now see what we have in bitcoin by default. To do that, we will log it to the console like this:

console.log(bitcoin);

We will now open the project in a terminal and run the following command:

node test

It should output the following:

Screenshot-2022-11-10-at-12.21.35

Default Output

In the output above, we have the chain array containing the genesis block and the pendingTransactions array containing nothing.

You will recall that the constructor function contains all those data and it runs once at the beginning of the program.

To add a new transaction, use the code below:

bitcoin.createNewTransaction(
  "100",
  "0xBcd4042DE499D14e55001CcbB24a551F3b954096",
  "0xa0Ee7A142d267C1f36714E4a8F75612F20a79720"
);

The first parameter is the amount, the second is the sender, and the third is the recipient just as we specified while creating the function.

If you run node test again, you should have one item in the pendingTransactions array like this:

Screenshot-2022-11-10-at-12.31.46

One pending transaction added

To create or mine a block, enter the following code:

bitcoin.createNewBlock();

You should get the output below this time:

Screenshot-2022-11-10-at-12.38.30

You will notice that there are now two (2) blocks in the chain and no more transactions in the pendingTransactions array.

Some things to note in the second block are the nonce and the hash. The nonce is 1404. That means it took 1404 iterations to get the correct hash for this block.

To see the transactions in the second block, we use the following code:

console.log("\n");
console.log("Second Block Transactions", bitcoin.chain[1].transactions);

Now we have the result below:

Screenshot-2022-11-10-at-12.49.08

That looks good! It shows that all our functions work as intended. And that is what goes on behind the scenes of many blockchain applications.

You've just learned how blockchain works. But you shouldn’t build a blockchain application solely on this program idea. There is much more to learn to enable you to build real-world DApp. Still, what we have done so far will help you dive more into learning web3.

One of the things you need to learn is a blockchain programming language such as Solidity and other blockchain frontend libraries such as Web3js and Etherjs.

I'll now introduce you to smart contracts using Solidity.

How to Write a Smart Contract

In this section, we will cover all you need to know about smart contracts and the Solidity programming language.

What is a Smart Contract?

A smart contract is a program stored on the blockchain. It holds certain conditions that must be met before it executes.

Smart contracts take after traditional contracts. But they're different because they are run by a computer automatically when the predefined terms are met.

What is Solidity?

Solidity is the main programming language used to build most smart contracts because it is specifically designed for that purpose. It follows the OOP pattern that we demonstrated using JavaScript and borrows the typed nature of TypeScript. So while some syntax might differ from what you already know, it is not too far-fetched to grasp.

We will be learning the basics of Solidity by using it to build a smart contract that enables users to send funds to each other.

Don't worry, you will not have to set up another project. We will use the remix playground to do everything – write the code, compile, debug, and test.

Let's now head over to https://remix.ethereum.org/. You should have the following screen stare at you for a while:

Screenshot-2022-11-10-at-21.54.11-1

Remix welcome page

Remix is getting everything ready for you. Just be patient 😊

When it's done, you should have the following screen:

Screenshot-2022-11-10-at-21.59.30

This playground provides us with all we need to write our first smart contract.

Let's start by deleting the file created for us by default. To do that, click on the first icon below the remix logo.

Right-click on the file name in the explorer section and select delete:

Screenshot-2022-11-10-at-22.08.37

Click OK in the pop-up menu.

Screenshot-2022-11-10-at-22.10.36

We will now create a new file named Blockchain.sol by clicking the document icon marked red in the image below and type the name of the file in the space provided:

Screenshot-2022-11-10-at-22.15.47

.sol is the extension used for solidity files. The blank space is where we will type our code.

Solidity code always begins with the line below:

// SPDX-License-Identifier: UNLICENSED

Without this code, you will get an error. It is just like saying that you accept the terms and conditions of writing Solidity.

The next thing to do is to state the Solidity version you want to use. I will use the following code:

pragma solidity ^0.8.7;

The caret (^) sign indicates that the program will be compatible with higher versions of solidity. We can now start the program.

The first thing to do is to define a Class named Blockchain. However, the keyword for Class in solidity is contract. So we have:

contract Blockchain {

}

Inside the contract above, we will create a data-type called BlockStruck with the code below:

struct BlockStruck {
    uint256 index;
    uint256 timestamp;
    uint256 amount;
    address sender;
    address recipient;
}

Solidity allows us to create any data-type that we see fit using the struct keyword, which is short for structure.

We define all the keys we expect a value for in the struct. Since solidity is a strongly typed language, we specified a data-type before each key. The struct is similar to Object in JavaScript.

uint indicates that a variable is an integer. Adding a number after it (such as uint256 or uint18) specifies the maximum size it should take, but uint assumes uint256 by default.

address, on the other hand, indicates that a variable is a wallet address. There is also the string data-type.

The next thing that we want to define is an event. An event is usually triggered at the end of a function's execution to send data to the frontend. You can see it like console.log. Some people also use it as a cheap way of storage.

We want to define a BlockEvent that we will trigger after adding a block to the chain. Enter the following code below the BlockStruct:


event BlockEvent(uint256 amount, address sender, address recipient);

Unlike struct, circular braces are used for an event, and their keys are separated by commas (,). Also, notice that struct does not end with a semicolon, but event does.

Now that we have defined the structure of blocks, let's use it to setup an array of blocks called chain like this:

BlockStruck[] chain;

The code above defines the chain to be an array of BlockStruct. As always, we specify the data-type before the variable name.

Next, define a variable to keep track of how many blocks are in the chain:

uint256 chainCount;

You may choose to assign it a value on the same line (uint256 chainCount = 0;) or do it in the constructor function like this:

constructor() {
    chainCount = 0;
}

We will now define three (3) functions: addBlockToChain (to add blocks to the chain), getChain (to return all the blocks added to the chain), and getChainCount (to get the number of blocks added to the chain).

addBlockToChain function

The code below begins the function:


function addBlockToChain(uint256 amount, address payable recipient) public {

}

Like the functions you already know, it begins with the function keyword followed by the name of the function, and the argument it expects in braces.

One of the arguments (recipient) has a flag called payable, indicating that the wallet address is eligible to receive funds. Next to it is the function's visibility flag (public).

Visibility defines who can call a function or variable. It can be public, private, internal, or external.

  1. A public function can be called by any contract.
  2. private functions can only be called inside the contract where they are defined.
  3. Only contracts that inherit internal functions can call them.
  4. external functions are only accessible by other contracts.

In the addBlockToChain, we start by incrementing the chainCount by one like this:

chainCount += 1;

Next, add the block of a transaction to the chain like this:

        chain.push(
            BlockStruck(
                chainCount,
                block.timestamp,
                amount,
                msg.sender,
                recipient
            )
        );

The BlockStruct takes values corresponding to the keys set when defining the struct. It is then added to the chain array using the .push method. Now we have a new block in the chain.

Finally, we trigger the BlockEvent we created a while ago:

emit BlockEvent(amount, msg.sender, recipient);

emit is the keyword used to call an event. As with the BlockStruct, the BlockEvent takes the values as they correspond to the keys set when defining the it.

The addBlockToChain function now looks like this:

    
    function addBlockToChain(uint256 amount, address payable recipient) public {
        chainCount += 1;

        chain.push(
            BlockStruck(
                chainCount,
                block.timestamp,
                amount,
                msg.sender,
                recipient
            )
        );

        emit BlockEvent(amount, msg.sender, recipient);
    }

getChain function

This function takes no argument but returns a BlockStruct. We will use the following code:

    
    function getChain() public view returns (BlockStruck[] memory) {
        return chain;
    }

The program returns the chain, an array of all blocks.

Something to note in the function above is that we used view to show that this function returns a value. We also indicated the kind of data type we expect to be returned (returns (BlockStruck[] memory)) and the storage type to be used (memory).

There are two main storage types in solidity: Storage and Memory. Storage is the default type of storage used to hold data permanently for a program while Memory is temporary and is less expensive in terms of gas.

Gas is a fee paid to execute smart contracts. Don't worry about that. We have some dummy gas that will enable us to test our program.

getChainCount function

Like the getChain, this function also takes no argument. It returns the number of blocks added to the chain so far. See the code below:

    
    function getChainCount() public view returns (uint256) {
        return chainCount;
    }

That completes the smart contract that we intended to create. Now the code looks like this:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.7;

contract Blockchain {
    struct BlockStruck {
        uint256 index;
        uint256 timestamp;
        uint256 amount;
        address sender;
        address recipient;
    }

    event BlockEvent(uint256 amount, address sender, address recipient);

    BlockStruck[] chain;
    uint256 chainCount;

    constructor() {
        chainCount = 0;
    }

    function addBlockToChain(uint256 amount, address payable recipient) public {
        chainCount += 1;

        chain.push(
            BlockStruck(
                chainCount,
                block.timestamp,
                amount,
                msg.sender,
                recipient
            )
        );

        emit BlockEvent(amount, msg.sender, recipient);
    }

    function getChain() public view returns (BlockStruck[] memory) {
        return chain;
    }

    function getChainCount() public view returns (uint256) {
        return chainCount;
    }
}

How to Compile the Smart Contract

We need to compile the code to check if there are errors that we need to fix. The steps below will help us do just that.

Click on the third icon on the left side menu of the remix IDE:

Screenshot-2022-11-11-at-11.07.34

Ensure that the solidity version selected matches the one you specified at the beginning of the smart contract. Then click the Compile button:

Screenshot-2022-11-11-at-11.18.36

The compilation was successful since we have no errors. Beautiful 🥰.

How to Deploy the Smart Contract

Now that compilation is successful, let's deploy the contract.

Click on the fourth icon in the side menu:

Screenshot-2022-11-11-at-11.27.27-1

Select Remix VM (London) for the ENVIRONMENT. It has ten (10) accounts with 100 dummy ethers each that you may use for test purposes. Then click the Deploy button:

Screenshot-2022-11-11-at-11.33.30

Now when you scroll to the bottom, you will find the Blockchain contract under Deployed Contracts. Click the arrow by the deployed contract name to see the functions of the contract that you can interact with.

Screenshot-2022-11-11-at-11.46.28

There are three (3) functions in the image above that match the three (3) functions we defined in our smart contract. Remix automatically creates a UI for you to test your contracts as soon as you deploy them

How to Test the Smart Contract

We will now test the functions we created to see how they respond.

How to test the addBlockToChain function

To test the addBlockToChain function, click the caret (^) icon by the side of the function button and input box. That drops down a form. Fill in 10 for the amount, and fill in one of the ten 10 account addresses for the recipient:

Screenshot-2022-11-11-at-11.56.31

Click the transact button.

Note that you cannot send funds to the same address you used to deploy the contract. You must choose a different account.

How to test the getChain function

Click the getChain button to reveal the blocks in the chain so far:

Screenshot-2022-11-11-at-12.02.10

It returns a tuple, which is a kind of array. Recall that chain is supposed to be an array containing a list of blocks.

How to test the getChainCount function

To get the number of blocks added, click the getChainCount button:

Screenshot-2022-11-11-at-12.08.25

And just as we defined it, it returns a uint. There is just one item in the chain for now, but as you keep adding more blocks, the number will increase.

Walah! Did we come this far? 😳 How Awesome 😍.

Congratulations on sticking to the end of this tutorial!

You are now ready to explore all that you can do with blockchain.

Conclusion

Blockchain is redefining the internet and has come to stay. The difficulty I encountered trying to learn the ropes of this new technology moved me to document this beginner-friendly guide. I hope that it helps everyone still struggling out there.

In this tutorial, you learned what blockchain is, how it works and what goes on behind the scenes. We demonstrated how it works using the OOP pattern of JavaScript and then concluded with a brief introduction to how to build smart contracts using the solidity programming language and remix IDE.

I recommend that you keep learning and getting better at building blockchain applications by creating the following projects in the order they are listed (by increasing difficulty):

Hello World
Simple Storage
Voting Smart Contract
Ether Wallets
Multi Send
Time Lock Smart Contract
ERC20 Token
Token Wallet
Air Drop
ICO

These projects will challenge you to do research and sharpen your blockchain skill.

Happy Chaining!

Original article source at https://www.freecodecamp.org

#blockchain #javascript #solidity #smartcontracts 

Build Smart Contracts with JavaScript and Solidity
Blockchain Dev

Blockchain Dev

1667463293

Web 3.0 Real Estate App with Solidity, Ethereum, Hardhat and React

In this tutorial, you'll learn how to build a Web 3.0 Real Estate App like Zillow Step-by-Step with Solidity, Ethereum, Hardhat and React
 

TABLE OF CONTENTS
00:00 Intro
01:14 Overview
05:56 Create Project
15:24 Escrow Contract
37:27 List Property
56:25 Earnest Deposit
01:02:41 Finish Contract
01:18:56 Deploy Contracts
01:30:07 Create Front End
01:35:25 Connect to Blockchain
01:42:43 Navbar
01:47:27 Search Bar
01:51:56 List Properties
02:03:53 Buy Property

CODE: https://github.com/dappuniversity/millow

#web3 #blockchain #solidity #ethereum #hardhat #react

Web 3.0 Real Estate App with Solidity, Ethereum, Hardhat and React

Build a Lottery App with Solidity and Next.js

In this tutorial, you'll learn how to build a Lottery App with Solidity (Infura) and Next.js. This is the BEST tutorial to learn the basics of Solidity Development!

🔗 GitHub Repo: https://github.com/CleverProgrammers/lottery-dapp-youtube 

#web3 #frontend #blockchain #nextjs #solidity 

Build a Lottery App with Solidity and Next.js

Build a Faucet Smart Contract For an ERC20 Token | Solidity Tutorial

In this faucet smart contract tutorial we build a faucet smart contract to give away ERC20 tokens on Ethereum  to anyone who requests them. Topics covered in this video include Solidity interfaces, events, working with time and sending and receiving tokens.

Solidity is a high-level object-oriented programming language that is principally used for the Ethereum blockchain. Solidity is a great tool to write smart contracts, which are self-executing code that enable complex automated functions. The programming language interacts with the Ethereum Virtual Machine (EVM), which is the abstraction layer between the executing code and execution machine. It is influenced by the C++, Python and JavaScript languages.

Project repo:
https://github.com/jspruance/erc20-tutorial-block-explorer 

Goerli testnet faucet:
https://goerlifaucet.com/ 

Install MetaMask:
https://metamask.io/ 

Remix IDE:
https://remix.ethereum.org/ 

Subscribe : https://www.youtube.com/c/BlockExplorerMedia/featured 

#web3 #solidity #smartcontract 

Build a Faucet Smart Contract For an ERC20 Token | Solidity Tutorial

Danish Thebo

1665260277

Install Solidity on Windows 10 and 11 Guide

https://laramatic.com/install-solidity-on-windows/

Here is the complete guide to install Solidity on Windows 10 and 11 we will walk you through the steps to install Solidity on your Win system and start creating your first smart contract.

Here is how to install Solidity on Windows 10 we will use its Linux Subsystem which is a built-in feature in win 10. We will use WSL to use Ubuntu terminal on Windows.
Let’s get done with it.
 

#linux #solidity #programing 

See the complete step by step guide to isntall solidity on your windows system.

Install Solidity on Windows 10 and 11 Guide