diff --git a/README.md b/README.md index 2ec3494..12636ac 100644 --- a/README.md +++ b/README.md @@ -8,73 +8,35 @@
--- -## ๐Ÿฉ dirs in this repo - -
- -#### ethereum - -
- -* [the evm && opcodes](evm_and_opcodes) -* [solidity](master_solidity) +### ๐Ÿฉ dirs in this repo - -
- -#### other chains - -* [solana](solana) +* [attack_reviews](attack_reviews) * [cosmos](cosmos) -* [rust](rust) - -
- -#### tools - -
- -* [static analysis](static_analysis_tools) -* [dynamic analysis](dynamic_analysis_tools) -* [hardhat](hardhat) -* [foundry](foundry) -* [tenderly](tenderly) -* [oracles](oracles) - -
- -#### general - -
- -* [vulnerabilities](vulnerabilities) -* [attack reviews](attack_reviews) * [cryptography](cryptography) * [decentralized storage](decentralized_storage) +* [dynamic analysis](dynamic_analysis) +* [the evm && opcodes](evm_and_opcodes) +* [gray hacker tools](gray_hat_tools) +* [hardhat](hardhat) * [l2s && rollups](l2_and_rollups) -* [gray hacker stuff](gray_hat_stuff) +* [oracles](oracles) +* [solana](solana) +* [static analysis](static_analysis) +* [vulnerabilities](vulnerabilities) + + + +
+ --- -## ๐Ÿง the evm - -
+## ๐Ÿ— solidity -* [Ethereum book](https://github.com/ethereumbook/ethereumbook) -* [Ethereum's Whitepaper](https://ethereum.org/en/whitepaper/) -* [Understanding rollups](https://barnabe.substack.com/p/understanding-rollup-economics-from?s=r) - - -
- ---- -## ๐Ÿ‰ solidity - -
* [Solidity docs](https://docs.soliditylang.org/en/v0.8.12/) * [OpenZeppelin docs](https://docs.openzeppelin.com/) @@ -89,13 +51,16 @@ * [Vscode plugin: Solidity visual](https://marketplace.visualstudio.com/items?itemName=tintinweb.solidity-visual-auditor) * [Vscode plugin: Solidity support](https://marketplace.visualstudio.com/items?itemName=JuanBlanco.solidity) * [Dapp university](https://www.youtube.com/c/DappUniversity) +* [foundry website](https://getfoundry.sh/) +* [foundry book](https://book.getfoundry.sh/forge/differential-ffi-testing) +* [foundry repo](https://github.com/foundry-rs/foundry) +* [ethernaut x foundry](https://github.com/ciaranmcveigh5/ethernaut-x-foundry)
---- -## ๐ŸŒถ all things security +### ๐Ÿ” all things security -
* [SWC Registry](https://swcregistry.io/) * [Blockchain Security Database](https://consensys.github.io/blockchainSecurityDB/) @@ -133,27 +98,12 @@ * [Bug Bounty 101](https://www.youtube.com/watch?v=S-Z2iwbT1Fg) -
- -#### documented defi and blockchains exploits - -
- -* [everything flashloans](https://github.com/MEV-WAIFU-LABS/mev_toolkit/tree/main/flashloans) -* [defi hacks](https://cryptosec.info/defi-hacks/) -* [Rug Doc Wiki](https://wiki.rugdoc.io/) -* [246 Findings From our Smart Contract Audits](https://blog.trailofbits.com/2019/08/08/246-findings-from-our-smart-contract-audits-an-executive-summary/) -* [rug pull checker tools](https://graph.org/A-Short-List-of-the-Rug-Checker-Tools-04-09) - - -
- --- -## ๐Ÿฅž contracts of interest +### ๐Ÿฅž contracts of interest + -
* [Uniswap v3](https://github.com/Uniswap/v3-core/tree/main/contracts) * [Chainlink](https://github.com/smartcontractkit/chainlink/tree/develop/contracts/src/v0.4) @@ -167,9 +117,7 @@
--- -## ๐Ÿง practice your hacking skils - -
+### ๐ŸŸ practice your hacking skils * [Capture the Ether](https://capturetheether.com/) * [the ethernaut](https://ethernaut.openzeppelin.com/) @@ -191,14 +139,8 @@
--- -## ๐Ÿฐ hacking tools - -
- - - -#### ethereum general +### ๐Ÿฅ“ relevant hacking tools * [Ethstats](https://ethstats.net/) @@ -211,13 +153,6 @@ * [ERC20 verifier](https://erc20-verifier.openzeppelin.com/) and [the source code](https://github.com/tinchoabbate/slither-scripts/tree/master/erc20) * [ANKR RPC gateway](ankr.com/rpc/) * [burp's web3 decoder](https://github.com/nccgroup/web3-decoder) - - - -
- -#### somehow relevant - * [Oyente, analysis Tool for Smart Contracts](https://github.com/enzymefinance/oyente) * [Trail of Bits' Ethereum Security Toolbox](https://github.com/trailofbits/eth-security-toolbox) * [Securify, Security scanner for Ethereum smart contracts](https://github.com/eth-sri/securify2) @@ -231,14 +166,7 @@ * [EVM-trace, Ethereum Virtual Machine transaction tracing tool](https://github.com/ApeWorX/evm-trace) * [Sleuthing Hashed Function Signature and Event Signature on Ethereum](https://dune.com/agaperste/event-and-function-signature-sleuthing?) * [Pratical overview of classic system security](http://www.astro.sunysb.edu/steinkirch/books/security_hw.txt) -* [socketscan, track bridge transactions](https://socketscan.io/) - - - -
- -#### other useful tools - +* [socketscan, track bridge transactions](https://socketscan.io/)s * [Solhint, a linter for Solidity](https://github.com/protofire/solhint) * [Solidity coverage tool](https://github.com/sc-forks/solidity-coverage) * [JSON formatter](https://jsonformatter.curiousconcept.com/) @@ -259,6 +187,6 @@ * [cookbook.dev](https://www.cookbook.dev/) * [detect metamorphic contracts](https://metamorphic.a16zcrypto.com/) * [rpcs list by privacy](https://chainlist.org/) +* [tenderly](https://dashboard.tenderly.co/) -
diff --git a/attack_reviews/bnb_bridge.md b/attack_reviews/2022/bnb_bridge.md similarity index 100% rename from attack_reviews/bnb_bridge.md rename to attack_reviews/2022/bnb_bridge.md diff --git a/attack_reviews/profanity.md b/attack_reviews/2022/profanity.md similarity index 85% rename from attack_reviews/profanity.md rename to attack_reviews/2022/profanity.md index 2acd310..29034a2 100644 --- a/attack_reviews/profanity.md +++ b/attack_reviews/2022/profanity.md @@ -2,5 +2,4 @@
-* [wintermute]() * [indexed finance](https://twitter.com/BlockSecTeam/status/1579514418731560961) diff --git a/attack_reviews/README.md b/attack_reviews/README.md index c797c4d..d4be9f7 100644 --- a/attack_reviews/README.md +++ b/attack_reviews/README.md @@ -1,18 +1,15 @@ -## ๐Ÿฅฅ vulnerabilities - -
- -#### data from big hacks - -* [profanity files](profanity.md) -* [BNB bridge](bnb_bridge.md) - -
+## attack reviews -#### in depth reviews +* [2022 attacks](2022) +* [2023 attacks](2023) +* [immunefi bug fix reviews](top_immunefi_vulnerabilities) -
-* [top immunefi bug fix reviews](https://github.com/bt3gl-labs/1337_blockchain_hacker_toolkit/tree/main/vulnerabilities/top_immunefi_vulnerabilities) -* [analysing txs](https://github.com/bt3gl-labs/1337_blockchain_hacker_toolkit/tree/main/attack_reviews/analysing_txs) + +### resources + +* [defi hacks](https://cryptosec.info/defi-hacks/) +* [Rug Doc Wiki](https://wiki.rugdoc.io/) +* [246 Findings From our Smart Contract Audits](https://blog.trailofbits.com/2019/08/08/246-findings-from-our-smart-contract-audits-an-executive-summary/) +* [rug pull checker tools](https://graph.org/A-Short-List-of-the-Rug-Checker-Tools-04-09) diff --git a/attack_reviews/analysing_txs/cream.md b/attack_reviews/analysing_txs/cream.md deleted file mode 100644 index f6ee5f1..0000000 --- a/attack_reviews/analysing_txs/cream.md +++ /dev/null @@ -1,3 +0,0 @@ -## Cream hack analysis - -
diff --git a/cosmos/README.md b/cosmos/README.md index 058107d..dc38302 100644 --- a/cosmos/README.md +++ b/cosmos/README.md @@ -1,18 +1,18 @@ -## ๐Ÿง„ Cosmos and IBC +## cosmos and IBC + +### tl; dr + +* IBC is an interoperability protocol for communicating arbitrary data between arbitrary state machines. + +* The protocol consists of two distinct layers: the transport layer (TAO) which provides the necessary infrastructure to establish secure connections and authenticate data packets between chains, and the application layer, which defines exactly how these data packets should be packaged and interpreted by the sending and receiving chains. + +* The IBC application layer can be used to build a wide range of cross-chain applications, including but not limited to token transfers, interchain accounts (delegate calls between two chains), non-fungible token transfers and oracle data feeds.
-*IBC is an interoperability protocol for communicating arbitrary data between arbitrary state machines.* +--- +### resources -*The protocol consists of two distinct layers: the transport layer (TAO) which provides the necessary infrastructure to establish secure connections and authenticate data packets between chains, and the application layer, which defines exactly how these data packets should be packaged and interpreted by the sending and receiving chains.* - -*The IBC application layer can be used to build a wide range of cross-chain applications, including but not limited to token transfers, interchain accounts (delegate calls between two chains), non-fungible token transfers and oracle data feeds.* - -
- -### building - -
* [cosmos developer portal](https://tutorials.cosmos.network/) * [cosmos sdk](https://github.com/cosmos/cosmos-sdk/) @@ -23,13 +23,6 @@ * [ignite](https://github.com/ignite/cli) * [gravity bridge](https://github.com/cosmos/gravity-bridge) * [ethermint](https://github.com/evmos/ethermint) - -
- -### block explorers and data - -
- * [atom scan](https://atomscan.com/) * [big dipper](https://bigdipper.live/) * [iob scan](https://ibc.iobscan.io/home) diff --git a/cryptography/README.md b/cryptography/README.md index a38651e..d97f400 100644 --- a/cryptography/README.md +++ b/cryptography/README.md @@ -1,6 +1,10 @@ -## ๐Ÿฅจ cryptography +## cryptography
+--- + +### resources + * [keccak](keccak.md) * [asymmetric cryptography](asymmetric_crypto.md) diff --git a/decentralized_storage/README.md b/decentralized_storage/README.md index 2599703..7f5b08c 100644 --- a/decentralized_storage/README.md +++ b/decentralized_storage/README.md @@ -1,9 +1,12 @@ -## ๐Ÿ’ decentralized storage +## decentralized storage + +### tl; dr +
-### Articles +---- +### resources -
* [forgotten IPFS vulns](https://consensys.net/diligence/blog/2022/09/the-forgotten-ipfs-vulnerabilities) diff --git a/dynamic_analysis_tools/README.md b/dynamic_analysis/README.md similarity index 93% rename from dynamic_analysis_tools/README.md rename to dynamic_analysis/README.md index 374ad13..b3c6001 100644 --- a/dynamic_analysis_tools/README.md +++ b/dynamic_analysis/README.md @@ -1,4 +1,4 @@ -## ๐Ÿ– dynamic analysis tools +## dynamic analysis tools
diff --git a/evm_and_opcodes/README.md b/evm_and_opcodes/README.md index fd24043..5c0953e 100644 --- a/evm_and_opcodes/README.md +++ b/evm_and_opcodes/README.md @@ -1,6 +1,5 @@ -## ๐Ÿฑ the evm +## the evm -
### tl;dr @@ -30,13 +29,8 @@ * [opcodes for the evm](https://ethereum.org/en/developers/docs/evm/opcodes/) * [opcodes and instruction reference](https://github.com/crytic/evm-opcodes) * [EVM Contract Construction](https://blog.smlxl.io/evm-contract-construction-93c98cc4ca96) - - -
- -##### disassemblers - -
- * [ethersplay](https://github.com/crytic/ethersplay) * [IDA EVM](https://github.com/crytic/ida-evm) +* [Ethereum book](https://github.com/ethereumbook/ethereumbook) +* [Ethereum's Whitepaper](https://ethereum.org/en/whitepaper/) +* [Understanding rollups](https://barnabe.substack.com/p/understanding-rollup-economics-from?s=r) diff --git a/foundry/README.md b/foundry/README.md deleted file mode 100644 index 7735d5d..0000000 --- a/foundry/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## ๐Ÿฅฉ foundry - -
- -* [foundry website](https://getfoundry.sh/) -* [foundry book](https://book.getfoundry.sh/forge/differential-ffi-testing) -* [foundry repo](https://github.com/foundry-rs/foundry) -* [ethernaut x foundry](https://github.com/ciaranmcveigh5/ethernaut-x-foundry) diff --git a/gray_hat_stuff/Screen Shot 2022-11-11 at 10.31.37 AM.png b/gray_hat_stuff/Screen Shot 2022-11-11 at 10.31.37 AM.png deleted file mode 100644 index d2c1f18..0000000 Binary files a/gray_hat_stuff/Screen Shot 2022-11-11 at 10.31.37 AM.png and /dev/null differ diff --git a/gray_hat_stuff/README.md b/gray_hat_tools/README.md similarity index 95% rename from gray_hat_stuff/README.md rename to gray_hat_tools/README.md index 3da7fea..55b0753 100644 --- a/gray_hat_stuff/README.md +++ b/gray_hat_tools/README.md @@ -1,4 +1,4 @@ -## ๐Ÿฅฏ gray hacker stuff +## gray hacker tools
diff --git a/hardhat/README.md b/hardhat/README.md index 6119a75..1a7fa0c 100644 --- a/hardhat/README.md +++ b/hardhat/README.md @@ -1,10 +1,15 @@ -## ๐Ÿซ Hardhat stuff +## hardhat stuff + + +### tl; dr
-### Tutorials +--- -
+### tutorials -* [Hardhat for Aurora](https://mirror.xyz/lilithsecurity.eth/7bxj980BWftX6oiwPu0OoTUyxLs7PhOVtSS0jVuXc04) + + +* [hardhat for aurora](https://mirror.xyz/lilithsecurity.eth/7bxj980BWftX6oiwPu0OoTUyxLs7PhOVtSS0jVuXc04) diff --git a/l2_and_rollups/README.md b/l2_and_rollups/README.md index a871ddc..ba12d4f 100644 --- a/l2_and_rollups/README.md +++ b/l2_and_rollups/README.md @@ -1,6 +1,6 @@ -# ๐Ÿ‘ l2s && rollups +## l2s && rollups -
+### tl; dr * the current Ethereum version has low transaction throughput and high latency in processing. This means that transactions are both slow and prohibitively expensive, due to high demand, relative to what the network can take at any given time. * there are two types of scaling solutions: @@ -13,14 +13,17 @@
-### zk-rollups +--- + +#### zk-rollups * zk-rollups bundle together many off-chain transactions into a single verifiable batch using zk-SNARK. * zk-SNARK is an extremely efficient, zero-knowledge proof that allows one party to prove it possesses certain information without revealing that information. These validity proofs are then posted to the Ethereum blockchain.
-### optimistic rollups +--- +#### optimistic rollups * Instead of executing and storing all the data on Ethereum, where transactions are only processed at a premium, we only store a summary. * All the actual computation and storage of contracts and data is done on L2. @@ -30,14 +33,17 @@
-### state channel +--- +#### state channel * setting up channels between parties to form an off-chain network within which many transactions take place * final state is updated on ethereum
-### side cain +--- + +#### side cain * conduct txs in a separate blockchain with its own consensus mechanism * assets and data are transferred with ethereum through a smart contract that locks assets and recreates representative opens in the side chain @@ -45,7 +51,8 @@
-### plasma chain +--- +#### plasma chain * similar to side chains, functioning as separate chains with their own consensus mechanisms * roots of each block are published to ethereum, which makes the system more secure but limits its ability for complex operations @@ -53,3 +60,7 @@
+ +--- + +### resources \ No newline at end of file diff --git a/l2_and_rollups/circom.md b/l2_and_rollups/circom.md index 03e8bd5..b91445b 100644 --- a/l2_and_rollups/circom.md +++ b/l2_and_rollups/circom.md @@ -1,4 +1,4 @@ -## ๐Ÿ [circom](https://docs.circom.io/) +## [circom](https://docs.circom.io/)
diff --git a/oracles/README.md b/oracles/README.md index cf78285..e3898ba 100644 --- a/oracles/README.md +++ b/oracles/README.md @@ -1,10 +1,11 @@ -## ๐Ÿฃ oracles +## oracles +### tl; dr
- +--- ### resources -* [mev toolkit on oracles](https://github.com/MEV-WAIFU-LABS/mev_toolkit/tree/main/oracles) +* [mev toolkit on oracles](https://github.com/go-outside-labs/mev-toolkit/tree/main/oracles) diff --git a/rust/README.md b/rust/README.md deleted file mode 100644 index 0f31a22..0000000 --- a/rust/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## ๐Ÿซ” Rust - -
- -### Learning - -
- -* [Rust by example](https://doc.rust-lang.org/rust-by-example/) diff --git a/solana/README.md b/solana/README.md index 46f2606..6a6db27 100644 --- a/solana/README.md +++ b/solana/README.md @@ -1,5 +1,14 @@ -## ๐Ÿง‹ solana hacking +## solana + + +### tl; dr +
+ +--- + +### resources + * [solsec](https://github.com/0xsanny/solsec0) diff --git a/solidity/README.md b/solidity/README.md deleted file mode 100644 index 5d562ad..0000000 --- a/solidity/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## ๐Ÿฟ master solidity - -
- -### in this dir - -
- - -* [set your workspace](set_your_workspace/) -* [bolierplates](boilerplates/) -* [solidity tl;dr](solidity_tldr.md) -* [l2s and rollups](l2_and_rollups/) -* [tokens standard](token_standards/) -* [tests](tests/) -* [saving gas](saving_gas.md) diff --git a/solidity/abi_encoding.md b/solidity/abi_encoding.md deleted file mode 100644 index 1894d17..0000000 --- a/solidity/abi_encoding.md +++ /dev/null @@ -1,24 +0,0 @@ -## ABI encoding - -* the solidity built-in function `abi.encode` encodes solidity types into raw bytes, that can be interpreted directly by the EVM. - - -``` -contract StringEncoding { - bytes public encodedString = abi.encode("hacking"); -} -``` - -* this is what happens: - 1. 1st (32 bytes) word = offset โ†’ indicates at which bytes index the string starts. If you count 32 from the beginning (= index 32), you will reach the starting point of where the actual encoded string starts. - 2. 2nd (32 bytes) word = string length โ†’ in the case of the string, this indicates how many characters (including whitespaces) are included in the string. - 3. 3rd (32 bytes) word = the actual utf8 encoded string โ†’ each individual bytes corresponds to hex notation of a letter / character encoded in utf8. - -
- -#### other ABI Encodings - -* address payable -> address -* contract -> address -* enum -> uint8 -* struct -> tuple of elementry types diff --git a/solidity/boilerplates/README.md b/solidity/boilerplates/README.md deleted file mode 100644 index 4418ceb..0000000 --- a/solidity/boilerplates/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## ๐ŸŒฎ boilerplates - - -
- -* [First ERC-721 project](https://github.com/bt3gl-labs/Blockchain-Development-and-Security/tree/main/Solidity-Expert/Boilerplates/erc721-solidity-101) diff --git a/solidity/boilerplates/erc721-solidity-101/.env_sample b/solidity/boilerplates/erc721-solidity-101/.env_sample deleted file mode 100644 index f93641e..0000000 --- a/solidity/boilerplates/erc721-solidity-101/.env_sample +++ /dev/null @@ -1,5 +0,0 @@ -API_URL = "https://eth-rinkeby.alchemyapi.io/v2/" -PUBLIC_KEY = -PRIVATE_KEY = -METADATA_URL = " -CONTRACT_ADDRESS = diff --git a/solidity/boilerplates/erc721-solidity-101/README.md b/solidity/boilerplates/erc721-solidity-101/README.md deleted file mode 100644 index 85395a3..0000000 --- a/solidity/boilerplates/erc721-solidity-101/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# One: A special summer - - -1. Compile contract: - -``` -npx hardhat compile -``` - -2. Deploy contract: - -``` -npx hardhat run scripts/deploy-contract.js --network rinkeby -``` - -3. Mint NFT: - -``` -node scripts/mint-nft.js -``` \ No newline at end of file diff --git a/solidity/boilerplates/erc721-solidity-101/contracts/MiaNFT.sol b/solidity/boilerplates/erc721-solidity-101/contracts/MiaNFT.sol deleted file mode 100644 index 1bb8d51..0000000 --- a/solidity/boilerplates/erc721-solidity-101/contracts/MiaNFT.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.7.3 <0.9.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/utils/Counters.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; - - -contract MiaNFT is ERC721, Ownable { - - using Counters for Counters.Counter; - Counters.Counter private _tokenIds; - - constructor() public ERC721("Mia's NFT, "NFT") {} - - function mintNFT(address recipient, string memory tokenURI) - public onlyOwner - returns (uint256) - { - _tokenIds.increment(); - - uint256 newItemId = _tokenIds.current(); - _mint(recipient, newItemId); - _setTokenURI(newItemId, tokenURI); - - return newItemId; - } -} \ No newline at end of file diff --git a/solidity/boilerplates/erc721-solidity-101/hardhat.config.js b/solidity/boilerplates/erc721-solidity-101/hardhat.config.js deleted file mode 100644 index 8b52766..0000000 --- a/solidity/boilerplates/erc721-solidity-101/hardhat.config.js +++ /dev/null @@ -1,19 +0,0 @@ -/** -* @type import('hardhat/config').HardhatUserConfig -*/ -require('dotenv').config(); -require("@nomiclabs/hardhat-ethers"); - -const { API_URL, PRIVATE_KEY } = process.env; - -module.exports = { - solidity: "0.7.3", - defaultNetwork: "rinkeby", - networks: { - hardhat: {}, - rinkeby: { - url: API_URL, - accounts: [`0x${PRIVATE_KEY}`] - } - }, -} diff --git a/solidity/boilerplates/erc721-solidity-101/package.json b/solidity/boilerplates/erc721-solidity-101/package.json deleted file mode 100644 index a863d5e..0000000 --- a/solidity/boilerplates/erc721-solidity-101/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "MiaNFT", - "version": "1.0.0", - "description": "", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "Mia von Steinkirch", - "license": "MIT", - "devDependencies": { - "@nomiclabs/hardhat-ethers": "^2.0.2", - "@nomiclabs/hardhat-waffle": "^2.0.1", - "@openzeppelin/contracts": "^3.1.0-solc-0.7", - "chai": "^4.3.4", - "ethereum-waffle": "^3.4.0", - "ethers": "^5.4.6", - "hardhat": "^2.6.2" - }, - "dependencies": { - "@alch/alchemy-web3": "^1.1.4", - "dotenv": "^10.0.0" - } -} diff --git a/solidity/boilerplates/erc721-solidity-101/scripts/deploy-contract.js b/solidity/boilerplates/erc721-solidity-101/scripts/deploy-contract.js deleted file mode 100644 index 630b540..0000000 --- a/solidity/boilerplates/erc721-solidity-101/scripts/deploy-contract.js +++ /dev/null @@ -1,14 +0,0 @@ -async function main() { - const nft = await ethers.getContractFactory("MiaNFT"); - - const nft_deploy = await nft.deploy(); - console.log(" โ›“๐Ÿงฑโœจ Contract address:", nft_deploy.address); - console.log(" โžก๏ธ (Please add this string to .env)"); -} - -main() - .then(() => process.exit(0)) - .catch(e => { - console.error(e); - process.exit(1); - }); diff --git a/solidity/boilerplates/erc721-solidity-101/scripts/mint-nft.js b/solidity/boilerplates/erc721-solidity-101/scripts/mint-nft.js deleted file mode 100644 index f4333b9..0000000 --- a/solidity/boilerplates/erc721-solidity-101/scripts/mint-nft.js +++ /dev/null @@ -1,41 +0,0 @@ -require('dotenv').config(); - -const PUBLIC_KEY = process.env.PUBLIC_KEY; -const PRIVATE_KEY = process.env.PRIVATE_KEY; -const API_URL = process.env.API_URL; -const METADATA_URL = process.env.METADATA_URL; -const CONTRACT_ADDRESS = process.env.CONTRACT_ADDRESS; -const { createAlchemyWeb3 } = require("@alch/alchemy-web3"); -const web3 = createAlchemyWeb3(API_URL); -const contract = require("../artifacts/contracts/MiaNFT.sol/MiaNFT.json"); -const nftContract = new web3.eth.Contract(contract.abi, CONTRACT_ADDRESS); - -async function mintNFT(tokenURI) { - - const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); - - const transaction = { - 'from': PUBLIC_KEY, - 'to': CONTRACT_ADDRESS, - 'nonce': nonce, - 'gas': 500000, - 'maxPriorityFeePerGas': 1999999987, - 'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI() - }; - - const sign = web3.eth.accounts.signTransaction(transaction, PRIVATE_KEY); - sign.then((signedTransaction) => { - - web3.eth.sendSignedTransaction(signedTransaction.rawTransaction, function(e, hash) { - if (!e) { - console.log("๐Ÿ’พ Transaction hash: ", hash); - } else { - console.log("ERROR:", e) - } - }); - }).catch((e) => { - console.log("ERROR:", e); - }); -} - -mintNFT(METADATA_URL); diff --git a/solidity/boilerplates/learning/hello-world.sol b/solidity/boilerplates/learning/hello-world.sol deleted file mode 100644 index 24bd164..0000000 --- a/solidity/boilerplates/learning/hello-world.sol +++ /dev/null @@ -1,32 +0,0 @@ -// Specifies the version of Solidity, using semantic versioning. -// Learn more: https://solidity.readthedocs.io/en/v0.5.10/layout-of-source-files.html#pragma -pragma solidity ^0.5.10; - -// Defines a contract named `HelloWorld`. -// A contract is a collection of functions and data (its state). -// Once deployed, a contract resides at a specific address on the Ethereum blockchain. -// Learn more: https://solidity.readthedocs.io/en/v0.5.10/structure-of-a-contract.html -contract HelloWorld { - - // Declares a state variable `message` of type `string`. - // State variables are variables whose values are permanently stored in contract storage. - // The keyword `public` makes variables accessible from outside a contract - // and creates a function that other contracts or clients can call to access the value. - string public message; - - // Similar to many class-based object-oriented languages, a constructor is - // a special function that is only executed upon contract creation. - // Constructors are used to initialize the contract's data. - // Learn more: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#constructors - constructor(string memory initMessage) public { - // Accepts a string argument `initMessage` and sets the value - // into the contract's `message` storage variable). - message = initMessage; - } - - // A public function that accepts a string argument - // and updates the `message` storage variable. - function update(string memory newMessage) public { - message = newMessage; - } -} diff --git a/solidity/boilerplates/learning/token.sol b/solidity/boilerplates/learning/token.sol deleted file mode 100644 index ff4e272..0000000 --- a/solidity/boilerplates/learning/token.sol +++ /dev/null @@ -1,58 +0,0 @@ -pragma solidity ^0.5.10; - -contract Token { - // An `address` is comparable to an email address - it's used to identify an account on Ethereum. - // Addresses can represent a smart contract or an external (user) accounts. - // Learn more: https://solidity.readthedocs.io/en/v0.5.10/types.html#address - address public owner; - - // A `mapping` is essentially a hash table data structure. - // This `mapping` assigns an unsigned integer (the token balance) to an address (the token holder). - // Learn more: https://solidity.readthedocs.io/en/v0.5.10/types.html#mapping-types - mapping (address => uint) public balances; - - // Events allow for logging of activity on the blockchain. - // Ethereum clients can listen for events in order to react to contract state changes. - // Learn more: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#events - event Transfer(address from, address to, uint amount); - - // Initializes the contract's data, setting the `owner` - // to the address of the contract creator. - constructor() public { - // All smart contracts rely on external transactions to trigger its functions. - // `msg` is a global variable that includes relevant data on the given transaction, - // such as the address of the sender and the ETH value included in the transaction. - // Learn more: https://solidity.readthedocs.io/en/v0.5.10/units-and-global-variables.html#block-and-transaction-properties - owner = msg.sender; - } - - // Creates an amount of new tokens and sends them to an address. - function mint(address receiver, uint amount) public { - // `require` is a control structure used to enforce certain conditions. - // If a `require` statement evaluates to `false`, an exception is triggered, - // which reverts all changes made to the state during the current call. - // Learn more: https://solidity.readthedocs.io/en/v0.5.10/control-structures.html#error-handling-assert-require-revert-and-exceptions - - // Only the contract owner can call this function - require(msg.sender == owner, "You are not the owner."); - - // Enforces a maximum amount of tokens - require(amount < 1e60, "Maximum issuance exceeded"); - - // Increases the balance of `receiver` by `amount` - balances[receiver] += amount; - } - - // Sends an amount of existing tokens from any caller to an address. - function transfer(address receiver, uint amount) public { - // The sender must have enough tokens to send - require(amount <= balances[msg.sender], "Insufficient balance."); - - // Adjusts token balances of the two addresses - balances[msg.sender] -= amount; - balances[receiver] += amount; - - // Emits the event defined earlier - emit Transfer(msg.sender, receiver, amount); - } -} diff --git a/solidity/saving_gas.md b/solidity/saving_gas.md deleted file mode 100644 index bfd09c8..0000000 --- a/solidity/saving_gas.md +++ /dev/null @@ -1,153 +0,0 @@ -## โ›ฝ๏ธ Tricks to save gas - - - -
- -#### Gas is the cost to for on-chain computation and storage. -#### Examples: addition costs 3 gas, Keccak-256 costs 30 gas + 6 gas for each 256 bits of data being hashed, sending a transaction costs 21,000 gas. - - -
- ------ - -### gas reports - -
- -* [hardhat](https://medium.com/@thelasthash/%EF%B8%8F-gas-optimization-with-hardhat-1e553eaea311) -* [foundry](https://book.getfoundry.sh/forge/gas-reports) - - - - -
- ---- - - - -### Function names - -- brute force hashes of function names to find those that starts `0000`, so this can save around 50 gas - ----- - -### Other contracts - -- avoid calls to other contracts - ---- - -### Pack variables - -The below code is an example of poorย code and will consume 3 storage slot: - -``` -uint8 numberOne; -uint256 bigNumber; -uint8 numberTwo; -``` - -A much more efficient way to do this in solidity will be: - -``` -uint8 numberOne; -uint8 numberTwo; -uint256 bigNumber; -``` - ---- - -### Constant vs. Immutable variables - -Constant values can sometimes be cheaper than immutable values: - -1. For a constant variable, the expression assigned to it is copied to all the places where it is accessed and also re-evaluated each time, allowing local optimizations. -2. Immutable variables are evaluated once at construction time and their value is copied to all the places in the code where they are accessed. For these values, 32 bytes are reserved, even if they would fit in fewer bytes. - ---- - -### Iterators - -* ++i uses 5 gas less than i++ - ---- - -### Mappings are cheaper than Arrays - -- avoid dynamically sized arrays -- An array is not stored sequentially in memory but as a mapping. -- You can pack Arrays but not Mappings. -- Itโ€™s cheaper to use arrays if you are using smaller elements like `uint8` which can be packed together. -- You canโ€™t get the length of a mapping or parse through all its elements, so depending on your use case, you might be forced to use an Array even though it might cost you more gas. - ---- - -### **Use bytes32 rather than string/bytes** - -- If you can fit your data in 32 bytes, then you should use bytes32 datatype rather than bytes or strings as it is much cheaper in solidity. -- Any fixed size variable in solidity is cheaper than variable size. - ---- - -### Modifiers - -- For all the public functions, the input parameters are copied to memory automatically, and it costs gas. -- If your function is only called externally, then you should explicitly mark it as external. -- External functionโ€™s parameters are not copied into memory but are read from `calldata` directly. -- internal and private are both cheaper than public and external when called from inside the contract in some cases. - - - ---- - -### Delete variables that you donโ€™t need - -- If you donโ€™t need a variable anymore, you should delete it using the delete keyword provided by solidity or by setting it to its default value. - ---- - -### **No need to initialize variables with default values** - -- If a variable is not set/initialized, it is assumed to have the default value (0, false, 0x0 etc depending on the data type). If you explicitly initialize it with its default value, you are just wasting gas. - -``` -uint256 hello = 0; //bad, expensive -uint256 world; //good, cheap -``` - ---- - -### Make use of single line swaps - -- This is space-efficient: - -``` -(hello, world) = (world, hello) -``` - -
- ---- - -
- -## negative gas costs - -- Deleting a contract (SELFDESTRUCT) is worth a refund of 24,000 gas. -- Changing a storage address from a nonzero value to zero (SSTORE[x] = 0) is worth a refund of 15,000 gas. - -
- - ---- - -## resources and tools - -
- -* [truffle contract size](https://github.com/IoBuilders/truffle-contract-size) -* [Solidity Gas Optimizations, The Innovative & Dangerous -](https://mirror.xyz/haruxe.eth/DW5verFv8KsYOBC0SxqWORYry17kPdeS94JqOVkgxAA) diff --git a/solidity/set_your_workspace/remix-IDE.md b/solidity/set_your_workspace/remix-IDE.md deleted file mode 100644 index 58ea070..0000000 --- a/solidity/set_your_workspace/remix-IDE.md +++ /dev/null @@ -1,68 +0,0 @@ -## Remix IDE - -
- -Remix IDE is an open source web3 application and it's used for the entire journey of smart contract development. - -
- -Screen Shot 2022-03-10 at 5 57 22 PM - - -
- -* Everything in Remix is a plugin. The plugin mamanger is the place to load functionalities and create your own plugins. -* By default, Remix stores files in Workspaces, which are folders in the browser's local storage. -* You can publish all files from current workspace to a gist, using the Gist API. - - -
- -#### Compiler (Solidity) - -* You can compile (and deploy) contracts with versions of Solidity older than 0.4.12. However, the older compilers used a legacy AST. -* The "fork selection" dropdown list allows to compile code against a specific ehtereum hard fork. - - -
- -#### Optimization - -* The optimizer tries to simplify complicated expressions, which reduces both code size and execution cost. It can reduce gas needed for contract deployment as well as for external calls made to the contract. - - -
- -#### Environment - -* `JavaScript VM`: All transactions will be executed in a sandbox blockchain in the browser. -* `Injected Provider`: Metamaask is an example of a profiver that inject web3. -* `Web3 Provider`: Remix will connect to a remote node (you need to provide the URL to the selected provider: geth, parity or any ethereum client) - - -
- -#### Setup - -* Gas Limit: sets the amount of ETH, WEI, GWEI that is sent to ta contract or a payable function. -* Deploy: sends a transaction that deplpys the selected contract. -* atAdress: used to access a contract whtat has already been deployed (does not cost gas). -* To interact with a contract using the ABI, create a new file in Remix, with extension `.abi`. -* The Recorder is a tool used to save a bunch of transactions in a JSON file and rerun them later either in the same environment or in another. -* The Debugger shows the contract's state while stepping through a transaction. -* Using generated sources will make it easier to audit your contracts. -* Static code analysis can be done by a plugin, so that you can examine the code for security vulnerabilities, bad development practices, etc. -* Hardhat integration can be done with `hardhat.config.js` (Hardhat websocket listener should run at `65522`). Hardhat provider is a plugin for Remix IDE. - - -
- -#### Generate artifacts - -When a compilation for a Solidity file succeeds, Remix creates three Json files for each compiled contract, that can be seen in the `File Explorers plugin`: - -1. `artifacts/.json`: contains links to libraries, the bytecode, gas estimation, the ABI. -2. `articfacts/.json`: contains the metadata from the output of Solidity compilation. -3. `artifcats/build-info/.json`: contains info about `solc` compiler version, compiler input and output. - - diff --git a/solidity/solidity_tldr.md b/solidity/solidity_tldr.md deleted file mode 100644 index 9abb0f0..0000000 --- a/solidity/solidity_tldr.md +++ /dev/null @@ -1,412 +0,0 @@ - -## solidity tl;dr - -
- -## predefined global variables and functions - -
- -* When a contract is executed in the EVM, it has access to a small set of global objects: block, msg, and tx objects. -* In addition, Solidity exposes a number of EVM opcodes as predefined functions. - - -
- -#### msg - -* msg object: the transaction that triggered the execution of the contract. -* msg.sender: sender address of the transaction. -* msg.value: ether sent with this call (in wei). -* msg.data: data payload of this call into our contract. -* msg.sig: first four bytes of the data payload, which is the function selector. - -
- -#### tx - -* tx.gasprice: gas price in the calling transaction. -* tx.origin: address of the originating EOA for this transaction. WARNING: unsafe! - -
- -#### block - -* block.coinbase: address of the recipient of the current block's fees and block reward. -* block.gaslimit: maximum amount of gas that can be spent across all transactions included in the current block. -* block.number: current block number (blockchain height). -* block.timestamp: timestamp placed in the current block by the miner (number of seconds since the Unix epoch). - -
- -#### address - -* address.balance: balance of the address, in wei. -* address.transfer(__amount__): Transfers the amount (in wei) to this address, throwing an exception on any error. -* address.send(__amount__): similar to transfer, only instead of throwing an exception, it returns false on error. WARNING: always check the return value of send. -* address.call(__payload__): low-level CALL functionโ€”can construct an arbitrary message call with a data payload. Returns false on error. WARNING: unsafe. -* address.delegatecall(__payload__): low-level DELEGATECALL function, like callcode(...) but with the full msg context seen by the current contract. Returns false on error. WARNING: advanced use only! - - -
- -#### built-in functions - -* addmod, mulmod: for modulo addition and multiplication. For example, addmod(x,y,k) calculates (x + y) % k. -* keccak256, sha256, sha3, ripemd160: calculate hashes with various standard hash algorithms. -* ecrecover: recovers the address used to sign a message from the signature. -* selfdestruct(__recipient_address__): deletes the current contract, sending any remaining ether in the account to the recipient address. -* this: address of the currently executing contract account. - -
- -#### what is considered modifying state - -- writing to state variables -- emitting events -- creating other contracts -- sending ether via calls -- using selfdestruct -- using low-level calls -- calling any function not marked view or pure -- using inline assembly that contains certain opcodes - - - - - -
- ---- - -## TL;DR solidity x python/C++ - - -
- -From Python, we get: -- modifiers -- multiple inheritances - -From JavaScript we get: -- function-level scoping -- the `var` keyword - -From C/C++ we get: - -- scoping: variables are visible from the point right after their declaration until the end of the smallest {}-block that contains the declaration. -- the good ol' value types (passed by value, so they are alway copied to the stack) and reference types (references to the same underlying variable). -- however, look how cool: a variable that is declared will have an initial default value whose byte-representation is all zeros. -- int and uint integers, with uint8 to uint256 in step of 8. - -From being statically-typed: -- the type of each variable (local and state) needs to be specified at compile-time (as opposed to runtime). - -
- - -You start files with the SPDX License Identifier (`// SPDX-License-Identifier: MIT`). SPDX stands for software package data exchange. The compiler will include this in the bytecode metadata and make it machine readable. - -
- -**Pragmas.** Big thing. Directives that are used to enable certain compiler features and checks. - -Version Pragma indicates the specific Solidity compiler version. It does not change the version of the compiler, though, so yeah, you will get an error if it does not match the compiler. - -Other types are Compiler version, ABI coder version, SMTCheker. - -
- -The best-practices for layout in a contract are: -1. state variables -2. events -3. modifiers -4. constructors -5. functions - -
- - -**NatSpec comments**. Also known as the "ethereum natural language specification format". Written as triple slashes (`///`) or double asterisk block -`(/**...*/)`, directly above function declarations or statements to generate documentation in `JSON` format for developers and end-users. These are some tags: -* @title: describe the contract/interface -* @author -* @notice: explain to an end user what it does -* @dev: explain to a dev -* @param: document params -* @return: any returned variable -* @inheritdoc: copies missing tags from the base function (must be followed by contract name) -* @custon: anything application-defined - - - -
- -**Events**. An abstraction on top of EVM's logging: emitting events cause the arguments to be stored in the transaction's log (which are associated with the address of the contract). Events are emitted using **emit**. - -Events are especially useful for light clients and DApp services, which can "watch" for specific events and report them to the user interface, or make a change in the state of the application to reflect an event in an underlying contract. - -
- - ---- - -## Variables - -
- -**Address types**. The address type comes in two types: - -1. holds a 20 byte value (the size of an Ethereum address) -2. address payable: with additional members transfer and send. address payable is an address you can send Ether to (while plain address not). - -Explicit conversion from address to address payable can be done with payable(). -Explicit conversion from or to address is allowed for uint160, integer literals, byte20, and contract types - -The members of address type are pretty interesting: .balance, .code, .codehash, .transfer, .send, .call, .delegatecall, .staticcall. - -
- -**Fixed-size Byte Arrays**. bytes1, bytes2, bytes3, โ€ฆ, bytes32 hold a sequence of bytes from one to up to 32. The type byte[] is an array of bytes, but due to padding rules, it wastes 31 bytes of space for each element, so it's better to use bytes() - - -
- -**State variables**. Variables that can be accessed by all functions of the contract and values are permanently stored in the contract storage. - -**State visibility specifiers.** This is important. These are state variables that define how the methods will be accessed: -- public: part of the contract interface and can be accessed internally or via messages. -- external: like public functions, but cannot be called within the contract. -- internal: can only be accessed internally from within the current contracts (or contracts deriving from it). -- private: can only be accessed from the contract they are defined in and not in derived contracts. -- pure: neither reads nor writes any variables in storage. It can only operate on arguments and return data, without reference to any stored data. Pure functions are intended to encourage declarative-style programming without side effects or state. -- payable: can accept incoming payments. Functions not declared as payable will reject incoming payments. There are two exceptions, due to design decisions in the EVM: coinbase payments and `SELFDESTRUCT` inheritance will be paid even if the fallback function is not declared as payable. - - - -**Immutability**. State variables can be declared as constant or immutable, so they cannot be modified after the contract has been constructed. Their difference is beautiful: -**for constant variables, the value is fixed at compile-time; for immutable variables, the value can still be assigned at construction time (in the constructor or point of declation)** - -There is an entire gas cost thing too. For constant variables, the expression assigned is copied to all the places, and re-evaluated each time (local optimizations are possible). For immutable variables, the expression is evaluated once at constriction time and their value is copied to all the places in the code they are accessed, on a reserved 32 bytes, becoming usually more expensive than constant. - -
- ---- - -## Functions - -
- -**Functions modifiers**. Used to change the behavior of functions in a declarative way, so that the function's control flow continues after the "_" in the preceding modifier. This symbol can appear in the modifier multiple times. - -The underscore followed by a semicolon is a placeholder that is replaced by the code of the function that is being modified. Essentially, the modifier is "wrapped around" the modified function, placing its code in the location identified by the underscore character. - -To apply a modifier, you add its name to the function declaration. More than one modifier can be applied to a function; they are applied in the sequence they are declared, as a space-separated list. - -``` -function destroy() public onlyOwner { -``` - -
- -**Function Visibility Specifiers**. Super uber important. These are how visibility works for functions: - -- public: part of the contract interface and can be either called internally or via messages. -- external: part of the contract interface, and can be called from other contracts and via transactions. Here is the interesting part: an external function `func` cannot be called internally, so `func()` would not work. But `this.func()` does. -- internal: can only be accessed from within the current contract or contracts deriving from it. -- private: can only be accessed from the contract they are defined in and not even in derived contracts - -
- -**Function Mutability Specifiers**: - -- view functions can read the contract state but not modify it: enforced at runtime via STATICALL opcode. -- pure functions can neither read a contract nor modify it. -- only view can be enforced at the EVM level, not pure. - -
- -**Overloading**. Okay, this one is hardcore: a contract can have multiple functions of the same name but with different parameter types! They are matched by the arguments supplied in the function call ๐Ÿ˜ฌ. - - -
- ---- - -## Data structures - -
- -- structs: custom-defined types that can group several variables of same/different types together to create a custom data structure. -- enums: used to create custom types with a finite set of constants values. Cannot have more than 256 members. - -
- -**Constructors**. When a contract is created, the function with *constructor* is executed once and then the final code of the contract is stored on the blockchain (all public and external functions, but not the constructor code or internal functions called by it). - -
- -**Receive function**. So this is interesting. A contract can have ONE *receive* function (*receive() external payable {...}*) without the function keyword, and no arguments and no return and... have `external` and `payable`. This is the function on plain Ether transfers via send() or transfer(). - -Interesting facts: -- Receive is executed on a call to the contract with empty calldata. -- Receive might only rely on 2300 gas being available. -- A contract without Receive can actually receive Ether as a recipient of a coinbase transaction (miner block reward) or as a destination of `selfdestruct`. -- A contract cannot react to the Ether transfer above. - -
- -**Falback function**. Kinda in the same idea, a contract can have ONE *fallback* function, which must have external visibility. - -- fallback is executed on a call to the contract if none of the other functions match the given function signature or no data was supplied and there is not receive Ether function. - - -
- -**Transfer.** The transfer function fails if the balance of the contract is not enough or if the transfer is rejected by the receiving account, revering on failure. - -
- -**Send.** Low-level counterpart of transfer, however, if the execution fails then send only returns false (return value must be checked by the caller). - -
- ----- - -## calling another contract - -
- -**Call/Delegatecall/Staticall**. Used to interface with contracts that do not adhere to ABI, or to give more direct control over encoding. They all take a single bytes memory parameter and return the success condition (as a bool) and the return data (byte memory). - -With delegatecall, only the code of the given address is used but all other aspects are taken from the current contract. The purpose is to use logic code that is stored in the callee contract but operates on the state of the caller contract. - -With staticall, the execution will revert if the called function modifies the state in any way. - -
- -### Creating a new instance - -* The safest way to call another contract is if you create that other contract yourself. -* To do this, you can simply instantiate it, using the keyword `new`, as in other object-oriented languages. This keyword will create the contract on the blockchain and return an object that you can use to reference it. - -``` -contract Token is Mortal { - Faucet _faucet; - - constructor() { - _faucet = new Faucet(); - } -} -``` - -
- - -### Addressing an existing instance - -* Another way you can call a contract is by casting the address of an existing instance of the contract. -* With this method, you apply a known interface to an existing instance. -* This is much riskier than the previous mechanism, because we donโ€™t know for sure whether that address actually is a Faucet object. - -``` -import "Faucet.sol"; - -contract Token is Mortal { - - Faucet _faucet; - - constructor(address _f) { - _faucet = Faucet(_f); - _faucet.withdraw(0.1 ether); - } -} - -``` - -
- - -### Raw call, delegatecall - -* Solidity offers some even more "low-level" functions for calling other contracts. -* These correspond directly to EVM opcodes of the same name and allow us to construct a contract-to-contract call manually. -* As such, they represent the most flexible and the most dangerous mechanisms for calling other contracts. -* It can expose your contract to a number of security risks, most importantly reentrancy. - -``` -contract Token is Mortal { - constructor(address _faucet) { - _faucet.call("withdraw", 0.1 ether); - } -} -``` - -* Another variant of call is delegatecall, which replaced the more dangerous callcode. A delegatecall is different from a call in that the msg context does not change. -* Essentially, delegatecall runs the code of another contract inside the context of the execution of the current contract. - - - -
- ----- - -## Data - -
- -**Data Location.** Every reference type has an additional annotation with the data location where it is stored: - -* memory: lifetime is limited to an external function call -* storage: limited to the lifetime of a contract and the location where the state variables are stored -* calldata: non-modifiable, non-persistent area where function arguments are stored and behaves mostly like memory - -
- -**Block and Transaction Properties.** Cute shit. - -- blockhash -- block.chainid -- block.coinbase -- block.difficulty -- block.gaslimit -- block.number -- block.timestamp -- msg.data -- msg.sender -- msg.sig -- msg.value -- tx.gasprice -- gasleft -- tx.origin - -
- -**Randomness**. Not cute shit: you cannot rely on block.timestamp or blockhash as a source of randomness, as they can be influenced by miners to some degree. - -
- ---- - -## ABI Encoding and Decoding Functions - -
- -- abi.decode -- abi.encode -- abi.encodePacked -- abi.encodeWithSelector -- abi.encodeWithSignature - -
- ----- - -## Error Handling - -
- -- assert(): causes a panic error and revert if the condition is not met -- require(): reverts if the condition is not met -- revert(): abort execution and revert state changes - diff --git a/solidity/solidity_topics.md b/solidity/solidity_topics.md deleted file mode 100644 index d76394d..0000000 --- a/solidity/solidity_topics.md +++ /dev/null @@ -1,8 +0,0 @@ -## solidity topics - -solidity provides two types of events: - -* anonymous - * 4 topics may be indexed, and there is not signature hash (no filter) -* non-anonymous (default) - * up to 3 topics may be indexed, since the first topic is reserved to the event signature (filter) diff --git a/solidity/tests/README.md b/solidity/tests/README.md deleted file mode 100644 index d897eb4..0000000 --- a/solidity/tests/README.md +++ /dev/null @@ -1,35 +0,0 @@ -## ๐Ÿฃ tests in solidity - -
- -### assert vs. require - -* Assert() should only be used to test for internal errors, and to check invariants. -* Require() should be used to ensure valid conditions are met that cannot be detected until execution time. -* You may optionally provide a message for require, but not for assert. - - -
- -### unit testing - -
- -* [Solidity-Coverage](https://github.com/sc-forks/solidity-coverage) -* [Remix tests](https://github.com/ethereum/remix-project/tree/master/libs/remix-tests) -* [OpenZeppelin test helpers](https://github.com/OpenZeppelin/openzeppelin-test-helpers) -* [foundry forge tests](https://github.com/foundry-rs/foundry/tree/master/forge) -* [etheno](https://github.com/crytic/etheno) - - - -
- -### articles - -
- -* [how to mock solidity contracts](https://ethereum.org/en/developers/tutorials/how-to-mock-solidity-contracts-for-testing/) -* [truffle smart contract test framework](https://ethereum.org/en/developers/tutorials/how-to-mock-solidity-contracts-for-testing/) -* [in-depth guide to testing ethereum smart contracts](https://iamdefinitelyahuman.medium.com/an-in-depth-guide-to-testing-ethereum-smart-contracts-2e41b2770297) -* [how to test smart contracts](https://betterprogramming.pub/how-to-test-ethereum-smart-contracts-35abc8fa199d) diff --git a/solidity/tests/unit-testing.md b/solidity/tests/unit-testing.md deleted file mode 100644 index 472f5c2..0000000 --- a/solidity/tests/unit-testing.md +++ /dev/null @@ -1,63 +0,0 @@ -## Basic Unit testing - -
- -Functions in a test file to make testing more structural: - -* `beforeEach()` - Runs before each test -* `beforeAll()` - Runs before all tests -* `afterEach()` - Runs after each test -* `afterAll()` - Runs after all tests - -
- -A generic unit testing file looks like: - - -``` -pragma solidity >=0.4.22 <0.8.0; -import "remix_tests.sol"; // this import is automatically injected by Remix. -import "remix_accounts.sol"; -// Import here the file to test. - -// File name has to end with '_test.sol', this file can contain more than one testSuite contracts -contract testSuite { - - /// 'beforeAll' runs before all other tests - /// More special functions are: 'beforeEach', 'beforeAll', 'afterEach' & 'afterAll' - function beforeAll() public { - // Here should instantiate tested contract - Assert.equal(uint(1), uint(1), "1 should be equal to 1"); - } - - function checkSuccess() public { - // Use 'Assert' to test the contract, - // See documentation: https://remix-ide.readthedocs.io/en/latest/assert_library.html - Assert.equal(uint(2), uint(2), "2 should be equal to 2"); - Assert.notEqual(uint(2), uint(3), "2 should not be equal to 3"); - } - - function checkSuccess2() public pure returns (bool) { - // Use the return value (true or false) to test the contract - return true; - } - - function checkFailure() public { - Assert.equal(uint(1), uint(2), "1 is not equal to 2"); - } - - /// Custom Transaction Context - /// See more: https://remix-ide.readthedocs.io/en/latest/unittesting.html#customization - /// #sender: account-1 - /// #value: 100 - function checkSenderAndValue() public payable { - // account index varies 0-9, value is in wei - Assert.equal(msg.sender, TestsAccounts.getAccount(1), "Invalid sender"); - Assert.equal(msg.value, 100, "Invalid value"); - } -} -``` - -Note that ine can input custom values for `msg.sender` & `msg.value` of transaction using NatSpec comments. - - diff --git a/solidity/token_standards/README.md b/solidity/token_standards/README.md deleted file mode 100644 index c79680b..0000000 --- a/solidity/token_standards/README.md +++ /dev/null @@ -1,41 +0,0 @@ -## ethereum token standards - -### tl; dr - -* EIP stands for Ethereum Improvement Proposals. -* ERC stands for Ethereum request for comments (technical documents written by Ethereum developers for Ethereum community). -* Each such document contains a set of rules required to implement tokens for the Ethereum ecosystem. - - - -
- ---- - -### erc-20 - - -* In the case of ERC20, a transaction sending ether to an address changes the state of an address. - - a transaction transferring a token to an address only changes the state of the token contract, not the state of the recipient address. -* one of the main reasons for the success of EIP-20 tokens is in the interplay between `approve` and `transferFrom`, which allows for tokens to not -only be transferred between externally owned accounts (EOA). - - but to be used in other contracts under application specific conditions by abstracting away `msg.sender` as the mechanism for token access control. -* a limiting factor lies from the fact that the EIP-20 `approve` function is defined in terms of `msg.sender`. - - this means that userโ€™s initial action involving EIP-20 tokens must be performed by an EOA. - - if the user needs to interact with a smart contract, then they need to make 2 transactions (`approve` and the smart contract internal call `transferFrom`), with gas costs. - -
- ---- - -### in this dir - -* [ERC20](erc20.md) -* [ERC777](erc777.md) -* [ERC721](erc721.md) - -
- ---- - -### resources diff --git a/solidity/token_standards/erc20.md b/solidity/token_standards/erc20.md deleted file mode 100644 index 45bcff2..0000000 --- a/solidity/token_standards/erc20.md +++ /dev/null @@ -1,73 +0,0 @@ -## ERC20 - -
- -* The ERC20 standard defines a common interface for contracts implementing this token, such that any compatible token can be accessed and used in the same way. - -
- -### ERC20-compliant token contract - -* totalSupply -Returns the total units of this token that currently exist. ERC20 tokens can have a fixed or a variable supply. - -* balanceOf -Given an address, returns the token balance of that address. - -* transfer -Given an address and amount, transfers that amount of tokens to that address, from the balance of the address that executed the transfer. - -* transferFrom -Given a sender, recipient, and amount, transfers tokens from one account to another. Used in combination with approve. - -* approve -Given a recipient address and amount, authorizes that address to execute several transfers up to that amount, from the account that issued the approval. - -* allowance -Given an owner address and a spender address, returns the remaining amount that the spender is approved to withdraw from the owner. - -* Transfer -Event triggered upon a successful transfer (call to transfer or transferFrom) (even for zero-value transfers). - -* Approval -Event logged upon a successful call to approve. - -
- ---- - -### ERC20 optional functions - -In addition to the required functions listed in the previous section, the following optional functions are also defined by the standard: - -* name -Returns the human-readable name (e.g., "US Dollars") of the token. - -* symbol -Returns a human-readable symbol (e.g., "USD") for the token. - -* decimals -Returns the number of decimals used to divide token amounts. For example, if decimals is 2, then the token amount is divided by 100 to get its user representation. - -
- ---- - -### The ERC20 interface defined in Solidity - - -``` -contract ERC20 { - function totalSupply() constant returns (uint theTotalSupply); - function balanceOf(address _owner) constant returns (uint balance); - function transfer(address _to, uint _value) returns (bool success); - function transferFrom(address _from, address _to, uint _value) returns - (bool success); - function approve(address _spender, uint _value) returns (bool success); - function allowance(address _owner, address _spender) constant returns - (uint remaining); - event Transfer(address indexed _from, address indexed _to, uint _value); - event Approval(address indexed _owner, address indexed _spender, uint _value); -} -``` - diff --git a/solidity/token_standards/erc721.md b/solidity/token_standards/erc721.md deleted file mode 100644 index 4fef101..0000000 --- a/solidity/token_standards/erc721.md +++ /dev/null @@ -1,41 +0,0 @@ -## ERC721 - -
- - -To see the difference between ERC20 and ERC721, look at the internal data structure used in ERC721: - - -``` -mapping (uint256 => address) private deedOwner; -``` - -
- -Whereas ERC20 tracks the balances that belong to each owner, with the owner being the primary key of the mapping, -ERC721 tracks each deed ID and who owns it, with the deed ID being the primary key of the mapping. - -
- - -### The ERC721 contract interface specification - - -``` -interface ERC721 /* is ERC165 */ { - event Transfer(address indexed _from, address indexed _to, uint256 _deedId); - event Approval(address indexed _owner, address indexed _approved, - uint256 _deedId); - event ApprovalForAll(address indexed _owner, address indexed _operator, - bool _approved); - - function balanceOf(address _owner) external view returns (uint256 _balance); - function ownerOf(uint256 _deedId) external view returns (address _owner); - function transfer(address _to, uint256 _deedId) external payable; - function transferFrom(address _from, address _to, uint256 _deedId) - external payable; - function approve(address _approved, uint256 _deedId) external payable; - function setApprovalForAll(address _operator, boolean _approved) payable; - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` diff --git a/solidity/token_standards/erc777.md b/solidity/token_standards/erc777.md deleted file mode 100644 index eac66ff..0000000 --- a/solidity/token_standards/erc777.md +++ /dev/null @@ -1,67 +0,0 @@ -## ERC777 - -
- -* an ERC20-compatible interface - -* transfer tokens using a send function, similar to ether transfers - -* compatible with ERC820 for token contract registration - -* allow contracts and addresses to control which tokens they send through a tokensToSend function that is called prior to sending - -* enable contracts and addresses to be notified of the tokens' receipt by calling a tokensReceived function in the recipient, and to reduce the probability of tokens being locked into contracts by requiring contracts to provide a tokensReceived function - -* allow existing contracts to use proxy contracts for the `tokensToSend and `tokensReceived` functions - -* operate in the same way whether sending to a contract or an EOA - -* provide specific events for the minting and burning of tokens - -* enable operators (trusted third parties, intended to be verified contracts) to move tokens on behalf of a token holder - -* provide metadata on token transfer transactions in userData and operatorData fields - -
- ---- - -
- -### ERC777 contract interface specification - - -``` -interface ERC777Token { - function name() public constant returns (string); - function symbol() public constant returns (string); - function totalSupply() public constant returns (uint256); - function granularity() public constant returns (uint256); - function balanceOf(address owner) public constant returns (uint256); - - function send(address to, uint256 amount, bytes userData) public; - - function authorizeOperator(address operator) public; - function revokeOperator(address operator) public; - function isOperatorFor(address operator, address tokenHolder) - public constant returns (bool); - function operatorSend(address from, address to, uint256 amount, - bytes userData,bytes operatorData) public; - - event Sent(address indexed operator, address indexed from, - address indexed to, uint256 amount, bytes userData, - bytes operatorData); - event Minted(address indexed operator, address indexed to, - uint256 amount, bytes operatorData); - event Burned(address indexed operator, address indexed from, - uint256 amount, bytes userData, bytes operatorData); - event AuthorizedOperator(address indexed operator, - address indexed tokenHolder); - event RevokedOperator(address indexed operator, address indexed tokenHolder); -} -``` - - - - - diff --git a/static_analysis_tools/README.md b/static_analysis/README.md similarity index 94% rename from static_analysis_tools/README.md rename to static_analysis/README.md index b8d4202..c161e30 100644 --- a/static_analysis_tools/README.md +++ b/static_analysis/README.md @@ -1,4 +1,4 @@ -## ๐Ÿง‹ static analysis tools +## static analysis tools
diff --git a/tenderly/README.md b/tenderly/README.md deleted file mode 100644 index 5e5d8b1..0000000 --- a/tenderly/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## ๐Ÿง‰ tenderly - -
- -* [tenderly](https://dashboard.tenderly.co/) -* [tenderly pocked knife](https://officercia.medium.com/tenderly-app-a-swiss-pocketknife-for-the-web3-developer-89bb904bee46) diff --git a/vulnerabilities/README.md b/vulnerabilities/README.md index 991f414..3c0fe0d 100644 --- a/vulnerabilities/README.md +++ b/vulnerabilities/README.md @@ -1,18 +1,30 @@ ## smart contract vulnerabilities + +### tl; dr + + +* `tx.origin` needs to bere placed by `msg.sender`, otherwise any contract you call can act on your behalf. +* inline assembly should be used only in rare cases. +* unclear semantics: `now` is alias for `block.timestamp` not current time; use of low level `call`, `callcode`, `delegatecall` should be avoided whenever possible; use `transfer` whenever failure of ether transfer should rollnack the whole transaction. +* beware of caller contracts: `selfdestruct` can block calling contracts unexpectedly. +* invocation of local functions via `this`: never use `this` to call functions in the same contract, it only consumes more gas than normal call. +* transferring Ether in a for/while/do-while loop should be avoid due to the block gas limit. +* erc20 `decimals` should have `uint8` as return type. +
+--- + ### in this dir * [reentrancy](reentrancy_attacks) -* [arithmetic bugs](arithmetic-bugs-notes.md) -* [code injection via `delegatecall`](delegatecall) -* [ddos attacks](ddos-notes.md) -* [pentesting](pentesting.md) * [randomness in ethereum](random_numbers.md) -* [security tips](security_tips.md) -* [address poisoning](address_poisoning) +* [code injection via `delegatecall`](delegatecall) +* [ddos attacks](ddos.md) + +
diff --git a/vulnerabilities/arithmetic-bugs-notes.md b/vulnerabilities/arithmetic-bugs-notes.md deleted file mode 100644 index f6dd5f9..0000000 --- a/vulnerabilities/arithmetic-bugs-notes.md +++ /dev/null @@ -1 +0,0 @@ -## Notes on arithmetic bugs diff --git a/vulnerabilities/ddos-notes.md b/vulnerabilities/ddos.md similarity index 91% rename from vulnerabilities/ddos-notes.md rename to vulnerabilities/ddos.md index 65f6228..555f9ea 100644 --- a/vulnerabilities/ddos-notes.md +++ b/vulnerabilities/ddos.md @@ -1,4 +1,4 @@ -## Notes on DDoS attacks on the context of blockchains +## DDoS attacks on the context of blockchains
diff --git a/vulnerabilities/delegatecall/README.md b/vulnerabilities/delegatecall/README.md index 3dcf257..1ec0ca7 100644 --- a/vulnerabilities/delegatecall/README.md +++ b/vulnerabilities/delegatecall/README.md @@ -1,4 +1,4 @@ -# Attacks via code injection with `DELEGATECALL` +## attacks via code injection with `DELEGATECALL`
diff --git a/vulnerabilities/delegatecall/proxies.md b/vulnerabilities/delegatecall/proxies.md index 446077f..6f96823 100644 --- a/vulnerabilities/delegatecall/proxies.md +++ b/vulnerabilities/delegatecall/proxies.md @@ -1,11 +1,15 @@ -## ๐ŸŒถ notes on proxies +## proxies + +### tl; dr
-*There exists a special variant of a message call, named delegatecall which is identical to a message call apart from the fact that the code at the target address is executed in the context (i.e. at the address) of the calling contract and msg.sender and msg.value do not change their values. This means that a contract can dynamically load code from a different address at runtime. Storage, current address and balance still refer to the calling contract, only the code is taken from the called address.* +* here exists a special variant of a message call, named delegatecall which is identical to a message call apart from the fact that the code at the target address is executed in the context (i.e. at the address) of the calling contract and msg.sender and msg.value do not change their values. This means that a contract can dynamically load code from a different address at runtime. Storage, current address and balance still refer to the calling contract, only the code is taken from the called address.
+--- + ### proxy patterns
@@ -21,19 +25,47 @@
-### diamond pattern +#### transparent proxy pattern (TPP) + +1. upgrade logic is stored in proxy itself. +2. gas-inefficient
+#### universal upgradable proxy standard (UUPS) + +1. upgrade logic is stored in logic itself +2. gas-efficient + + +
+ +#### diamond pattern + + * diamond patterns differ from proxy patterns because the diamond proxy contract can delegates function calls to more than one logic contract. * when a user makes a function call, the proxy contract checks the mapping to find the facet responsible for executing that function. Then it invokes delegatecall (using the fallback function) and redirects the call to the appropriate logic contract.
-### resources +--- + +### unitialized proxy bug + + + +* Developers might leave proxies unitialized - this can be a problem when it leads to changes such as granting ownership to the caller +* the owners of the contract can upgrade the implementation contract +* this bug can lead to the self-destruction of the implementation contract (proxy contract is bricked)
+--- + +### resources + + + * [proxy patterns](https://mirror.xyz/0xB38709B8198d147cc9Ff9C133838a044d78B064B/M7oTptQkBGXxox-tk9VJjL66E1V8BUF0GF79MMK4YG0) * [how diamond upgrades work](https://dev.to/mudgen/how-diamond-upgrades-work-417j) * [the state of smart contract updates](https://blog.openzeppelin.com/the-state-of-smart-contract-upgrades/) diff --git a/vulnerabilities/governance_attacks.md b/vulnerabilities/governance_attacks.md deleted file mode 100644 index 02dacd2..0000000 --- a/vulnerabilities/governance_attacks.md +++ /dev/null @@ -1,11 +0,0 @@ -## ๐Ÿ— governance attacks - -
- - -### ethereum - -
- - -Screen Shot 2022-09-23 at 1 51 36 PM diff --git a/vulnerabilities/pentesting.md b/vulnerabilities/pentesting.md deleted file mode 100644 index f318556..0000000 --- a/vulnerabilities/pentesting.md +++ /dev/null @@ -1,3 +0,0 @@ -## ๐Ÿดโ€โ˜ ๏ธ Pentesting - -
diff --git a/vulnerabilities/proxies.md b/vulnerabilities/proxies.md deleted file mode 100644 index eaff9e7..0000000 --- a/vulnerabilities/proxies.md +++ /dev/null @@ -1,43 +0,0 @@ -## ๐ŸŠ Proxies - -
- -### TL;DR Proxies Patterns - -
- -#### Transparent Proxy Pattern (TPP) - -1. upgrade logic is stored in proxy itself. -2. gas-inefficient - -
- -#### Universal Upgradable Proxy Standard (UUPS) - -1. upgrade logic is stored in logic itself -2. gas-efficient - - -
- ---- - -### Unitialized proxy bug - -
- -* Developers might leave proxies unitialized - this can be a problem when it leads to changes such as granting ownership to the caller -* the owners of the contract can upgrade the implementation contract -* this bug can lead to the self-destruction of the implementation contract (proxy contract is bricked) - - ---- - -### Resources - -
- -* [Wormhole bridge protocol](https://github.com/immunefi-team/wormhole-uninitialized) - - diff --git a/vulnerabilities/random_numbers.md b/vulnerabilities/random_numbers.md index d56ce6e..4dfa899 100644 --- a/vulnerabilities/random_numbers.md +++ b/vulnerabilities/random_numbers.md @@ -1,4 +1,4 @@ -## ๐ŸŒถ randomization +## random number vulns
@@ -10,11 +10,14 @@ * `DIFFICULTY` is renamed to `PREVRANDAO`, and return the output of the randomness beacon provided by the beacon chain. It's stronger than `BLOCKHASH` but still biasable. +
+---- + ### resources -
+ * [ethereum randomness ](https://eth2book.info/altair/part2/building_blocks/randomness) diff --git a/vulnerabilities/sandwich-notes.md b/vulnerabilities/sandwich-notes.md deleted file mode 100644 index 629d1d5..0000000 --- a/vulnerabilities/sandwich-notes.md +++ /dev/null @@ -1,9 +0,0 @@ -## Notes on Sandwich attacks - -
- -### On Ethreum - -
- -* [A practical example on how to perform sandwich attacks on UniswapV2 pairs](https://github.com/libevm/subway) diff --git a/vulnerabilities/security_tips.md b/vulnerabilities/security_tips.md deleted file mode 100644 index 8efa20b..0000000 --- a/vulnerabilities/security_tips.md +++ /dev/null @@ -1,13 +0,0 @@ -## ๐ŸŒญ security tips - -
- -* `tx.origin` needs to bere placed by `msg.sender`, otherwise any contract you call can act on your behalf. -* inline assembly should be used only in rare cases. -* unclear semantics: `now` is alias for `block.timestamp` not current time; use of low level `call`, `callcode`, `delegatecall` should be avoided whenever possible; use `transfer` whenever failure of ether transfer should rollnack the whole transaction. -* beware of caller contracts: `selfdestruct` can block calling contracts unexpectedly. -* invocation of local functions via `this`: never use `this` to call functions in the same contract, it only consumes more gas than normal call. -* transferring Ether in a for/while/do-while loop should be avoid due to the block gas limit. -* erc20 `decimals` should have `uint8` as return type. - -