diff --git a/courses/foundry/1-foundry-simple-storage/10-vscode-solidity-setup/+page.md b/courses/foundry/1-foundry-simple-storage/10-vscode-solidity-setup/+page.md new file mode 100644 index 000000000..ae3566759 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/10-vscode-solidity-setup/+page.md @@ -0,0 +1,64 @@ +--- +title: VSCode Solidity setup +--- + +_Follow along with this video:_ + +--- + +### Improving Code Format in Visual Studio Code + +When you first start, your code might just look like a whole bunch of dull, lifeless, white text. + +This can be easily fixed by using one of the `Solidity` extensions. Out of all the Solidity extensions available in the Extensions tab (CTRL/CMD + SHIFT + X) the following are worth mentioning: + +1. [Solidity by Juan Blanco](https://marketplace.visualstudio.com/items?itemName=JuanBlanco.solidity), the most used Solidity extension out there. +2. [Solidity by Nomic Foundation](https://marketplace.visualstudio.com/items?itemName=NomicFoundation.hardhat-solidity) is Patrick's favorite Solidity extension. The rest of the course will be displaying this extension. +3. [Solidity Visual Developer](https://marketplace.visualstudio.com/items?itemName=tintinweb.solidity-visual-auditor) is another popular choice. + +**NOTE**: If the code remains unhighlighted despite having installed the extension, there's a quick solution to that. Press `Command + Shift + P`, or `Control + Shift + P` on Windows. This opens up the command bar. In the command bar, type in "Settings" and select "Preferences: Open User Settings (JSON)". + +If you have nothing in there, create a new setting by typing in: + +``` +{ + "editor.defaultFormatter": "NomicFoundation.hardhat" +} +``` + +Use: + +`"editor.defaultFormatter": "tintinweb.solidity-visual-auditor"` for Solidity Visual Developer + +or + +`"editor.defaultFormatter": "JuanBlanco.solidity"` for Solidity by Juan Blanco + +### Other interesting extensions + +In the previous lesson, we mentioned a file called `foundry.toml`. This also has an extension that formats it to make it easier to read. Please install [Even Better TOML](https://marketplace.visualstudio.com/items?itemName=tamasfe.even-better-toml). + +Another indispensable extension is [Inline Bookmarks](https://marketplace.visualstudio.com/items?itemName=tintinweb.vscode-inline-bookmarks). + +The Inline Bookmarks plugin facilitates bookmarking the actual code. The extension can be used for document review, auditing, log analysis, and keeping track of development notes and to-do lists. You may share your notes and bookmarks with others with ease because they are saved with your files. + +The following default trigger words/tags are configured by default: +``` +@todo - (blue) General ToDo remark. +@note - (blue) General remark. +@remind - (blue) General remark. +@follow-up - (blue) General remark. +@audit - (red) General bookmark for potential issues. +@audit-info - (blue) General bookmark for information to be noted for later use. +@audit-ok - (green) Add a note that a specific line is not an issue even though it might look like. +@audit-issue - (purple) Reference a code location an issue was filed for. +``` + +You can fully customize the colors! + +Remember these! They will be very handy in developing and especially in auditing projects. + +More details are available [here](https://github.com/tintinweb/vscode-inline-bookmarks). + +Next comes the fun part! Let's compile our contract using Foundry! + diff --git a/courses/foundry/1-foundry-simple-storage/11-compile-a-smart-contract-using-foundry/+page.md b/courses/foundry/1-foundry-simple-storage/11-compile-a-smart-contract-using-foundry/+page.md new file mode 100644 index 000000000..6b820ad04 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/11-compile-a-smart-contract-using-foundry/+page.md @@ -0,0 +1,29 @@ +--- +title: Compile a smart contract using Foundry +--- + +_Follow along with this video:_ + +--- + +### Compiling Smart Contracts: A Guide to the Foundry Console Compilation Process + +Open a new terminal. Type in `forge build` or `forge compile` to compile the smart contracts in your project. + +Once the compiling is finished, you'll see some new folders in the Explorer tab on the left side. One of them is a folder called `out`. Here you'll be able to find the [ABI](https://docs.soliditylang.org/en/latest/abi-spec.html) of the smart contract together with the [Bytecode](https://www.geeksforgeeks.org/introduction-to-bytecode-and-opcode-in-solidity/) and a lot of useful information. + +The `cache` folder also appears. Generally, this folder is used to store temporary system files facilitating the compilation process. But for this course, you can safely ignore it. + +### More terminal wizardry + +Throughout your solidity development/audit journey you will type a lot of terminal commands, every time to make a change that you want tested you'll probably have to rerun the `forge build` then maybe you test it with `forge test` or run a script with `forge script` and many more. Typing all these over and over again is inefficient and time-consuming. The better way is to use the `up` and `down` arrow keys. Type the following commands: + +``` +echo "I like Foundry" +echo "I love Cyfrin" +echo "Auditing is great" +``` + +Now press the `up` and `down` arrow keys to cycle through the 3 commands. + +Ok, cool! We learned how to compile a contract, but how does one deploy a smart contract? \ No newline at end of file diff --git a/courses/foundry/1-foundry-simple-storage/12-deploy-a-smart-contract-locally-using-ganache/+page.md b/courses/foundry/1-foundry-simple-storage/12-deploy-a-smart-contract-locally-using-ganache/+page.md new file mode 100644 index 000000000..bc9d5ae7c --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/12-deploy-a-smart-contract-locally-using-ganache/+page.md @@ -0,0 +1,93 @@ +--- +title: Deploy a smart contract locally using Ganache +--- + +_Follow along with this video:_ + + +### Deploying a smart contract + +There are multiple ways and multiple places where you could deploy a smart contract. + +While developing using the Foundry framework the easiest and most readily available place for deployment is Anvil. + +Anvil is a local testnet node shipped with Foundry. You can use it for testing your contracts from frontends or for interacting over RPC. + +To run Anvil you simply have to type `anvil` in the terminal. + +::image{src='/foundry-simply-storage/10-deploy-a-smart-contract-locally-using-ganache/Image1.PNG' style='width: 75%; height: auto;'} + +You now have access to 10 test addresses funded with 10_000 ETH each, with their associated private keys. + +This testnet node always listens on `127.0.0.1:8545` this will be our `RPC_URL` parameter when we deploy smart contracts here. More on this later! + +More info about Anvil is available [here](https://book.getfoundry.sh/reference/anvil/). + +Please press `Ctrl/CMD + C` to close Anvil. + +Anvil will be used throughout the course to deploy and test our smart contracts, but before that, let's quickly check an intermediary step. + +### Ganache + +_Ganache is a glaze, icing, sauce, or filling for pastries usually made by heating equal parts weight of cream and chopped chocolate, warming the cream first, then pouring it over the chocolate._ + +Wait, not that ganache! The other ganache: + +Ganache is a personal blockchain for rapid Ethereum and Filecoin distributed application development. You can use Ganache across the entire development cycle; enabling you to develop, deploy, and test your dApps in a safe and deterministic environment. + +Better! + +Please download Ganache from [here](https://archive.trufflesuite.com/ganache/). + +For people using Windows WSL please read [this](https://github.com/Cyfrin/foundry-simple-storage-f23?tab=readme-ov-file#windows-wsl--ganache). Using Ganache in this environment is not the easiest thing to do. We are not going to use this in the future, so don't worry if you can't configure it properly. + +Hit `Quickstart Ethereum`. Voila! A brand new blockchain. We get some addresses, that have balances and private keys. + +### Configuring MetaMask + +To deploy to a custom network (like your localhost), you'll need MetaMask. MetaMask is a popular cryptocurrency wallet and browser extension that allows users to interact with the Ethereum blockchain and its ecosystem. If you don't have it download it from [here](https://metamask.io/download/) + +Follow these steps: + +1. Open MetaMask. + +2. Click the three little dots and select 'Expand View'. + +3. Go to 'Settings', then 'Networks'. + +4. Here, you'll see the list of networks (Ethereum, Mainnet, etc.) with plenty of details about each one. Locate the RPC URL - this is key. + +The RPC URL is essentially the endpoint we make API calls to when sending transactions. For every blockchain transaction you execute, you're making an API to whatever is in here. +To send a transaction to your custom blockchain, you need to add it as a network: + +1. Click on 'Add a Network' + +2. Scroll to the bottom of the list of networks. + +3. Hit 'Add a Network manually'. + +4. Enter the details of your local network + + Network name: `Localhost` + + New RPC URL: Ganache`http://127.0.0.1:7545` or Anvil `http://127.0.0.1:8545` (make sure you always add `http://`) - these two could differ on your machine, please consult the Ganache UI or Anvil terminal for the exact RPC URL. + + Chain ID: Ganache `5777`(sometimes `1337`) or Anvil `31337` - these two could differ on your machine, please consult the Ganache UI or Anvil terminal for the exact Chain ID. + + Currency symbol: ETH + + Block explorer URL: - (we don't have a block explorer for our newly created blockchain, which will most likely disappear when we close the VS Code / Ganache app) + +Great! Now that we configured our local network, the next step is to add one of the accounts available in Ganche or Anvil into our MetaMask. [This is done as follows](https://support.metamask.io/hc/en-us/articles/360015489331-How-to-import-an-account#h_01G01W07NV7Q94M7P1EBD5BYM4): + +1. Click the account selector at the top of your wallet. + +2. Click `Add account or hardware wallet`. + +3. Click `Import account` + +4. You will be directed to the Import page. Paste your Ganache/Anvil private key. Click `Import`. + +**NOTE: Do not use this account for anything else, do not interact with it or send things to it on mainnet or any other real blockchain, use it locally, for testing purposes. Everyone has access to it.** + +Next up we shall talk more about adding a new network to MetaMask. diff --git a/courses/foundry/1-foundry-simple-storage/13-how-to-add-a-new-network-to-metamask/+page.md b/courses/foundry/1-foundry-simple-storage/13-how-to-add-a-new-network-to-metamask/+page.md new file mode 100644 index 000000000..2e69eac1b --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/13-how-to-add-a-new-network-to-metamask/+page.md @@ -0,0 +1,24 @@ +--- +title: How to add a new network to Metamask +--- + +_Follow along with this video:_ + +--- + +### Adding New Networks Using MetaMask + +Conveniently, MetaMask provides an easy way to add EVM-compatible chains. By pre-configuring a host of them, you can add a chain such as the Arbitrum One by simply clicking on the `Networks` button on the top left, then `Add Network` and proceeding to `Add`. The pleasing part is that MetaMask does all the grunt work, filling in all the necessary information for you. A click on Approve Network ensures the successful addition of the network. + +Steps: + +1. Click on the Networks button on the top left +2. Click on Add Network +3. Choose your desired EVM-compatible chain +4. Click on Add +5. After ensuring all necessary information is already filled in, click on Approve Network + +But what can you do if the chain you want to add is not pre-configured? + +Simple! You employ the same process we just used to add our new Ganache local chain in the [previous lesson](https://updraft.cyfrin.io/courses/foundry/foundry-simple-storage/deploy-smart-contract-locally) + diff --git a/courses/foundry/1-foundry-simple-storage/14-deploy-a-smart-contract-locally-using-forge/+page.md b/courses/foundry/1-foundry-simple-storage/14-deploy-a-smart-contract-locally-using-forge/+page.md new file mode 100644 index 000000000..ab3a762ce --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/14-deploy-a-smart-contract-locally-using-forge/+page.md @@ -0,0 +1,88 @@ +--- +title: Deploy a smart contract locally using Forge +--- + +_Follow along with this video:_ + +--- + +### Deploying to a local blockchain + +To find out more about forge's capabilities type + +``` +forge --help +``` + +Out of the resulting list, we are going to use the `create` command. + +Type `forge create --help` in the terminal or go [here](https://book.getfoundry.sh/reference/forge/forge-create) to find out more about the available configuration options. + +Try running `forge create SimpleStorage`. It should fail because we haven't specified a couple of required parameters: + +1. `Where do we deploy?` + +2. `Who's paying the gas fees/signing the transaction?` + +Let's tackle both these questions. + +As you've learned in the previous lessons, each blockchain (private or public) has an RPC URL (RPC SERVER) that acts as an endpoint. When we tried to deploy our smart contract, forge tried to use `http://localhost:8545/`, which doesn't host any blockchain. Thus, let's try to deploy our smart contract specifying the place where we want to deploy it. + +Please start Ganache and press `Quickstart Ethereum`. Copy the RPC Server `HTTP://127.0.0.1:7545`. Let's run our forge create again specifying the correct rpc url. + +``` +forge create SimpleStorage --rpc-url http://127.0.0.1:7545 +``` + +This again failed, indicating the following: + +``` +Error accessing local wallet. Did you set a private key, mnemonic or keystore? +``` + +Try the following command: + +``` +forge create SimpleStorage --rpc-url http://127.0.0.1:7545 --interactive +``` + +You will be asked to enter a private key, please paste one of the private keys available in Ganache. When you paste a key you won't see the text or any placeholder symbols, just press CTRL(CMD) + V and then ENTER. + +Voila! + +::image{src='/foundry-simply-storage/12-deploy-a-smart-contract-locally-using-forge/Image1.PNG' style='width: 75%; height: auto;'} + +You can go to Ganache and check the `Blocks` and `Transactions` tabs to see more info about what you just did. + +From now on, everything we deploy shall be done on Anvil. But if you like Ganache more, feel free to use that. + +Do the following: + +1. Run `clear` +2. Run `anvil` +3. Create a new terminal by pressing the `+` button +4. Copy one of the private keys from the anvil terminal +5. Run `forge create SimpleStorage --interactive` + We don't need to specify an `--rpc-url` this time because forge defaults to Anvil's RPC URL. +6. Go to the Anvil terminal and check the deployment details: + +``` + Transaction: 0x40d2ca8f0d680f098c7d5e3c127ef1ce1207ef439ba6e163c2042483e15998a6 + Contract created: 0x5fbdb2315678afecb367f032d93f642f64180aa3 + Gas used: 357076 + + Block Number: 1 + Block Hash: 0x85a56c0b8f166e86d1cce65412615e0d9a72972e04b2488023275131ea27330a + Block Time: "Mon, 15 Apr 2024 11:50:55 +0000" + +``` + +The more explicit way to deploy using `forge create` is as follows: + +``` +forge create SimpleStorage --rpc-url http://127.0.0.1:8545 --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 +``` + +We included the `--rpc-url` to not count on the default and the `--private-key` to not use the `--interactive` option anymore. + +Pfew! That was a lot, but we learned a very important thing, how to deploy a smart contract on two local blockchains. But what comes next is one of the most important if not the **_MOST IMPORTANT_** aspects you will learn here: **_Private key safety_** diff --git a/courses/foundry/1-foundry-simple-storage/15-important-private-key-safety-pt-1/+page.md b/courses/foundry/1-foundry-simple-storage/15-important-private-key-safety-pt-1/+page.md new file mode 100644 index 000000000..45cf0530f --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/15-important-private-key-safety-pt-1/+page.md @@ -0,0 +1,43 @@ +--- +title: Important - private key safety pt.1 +--- + +_Follow along with this video:_ + +--- + +### Practicing Private Key Safety + +Having a private key in plain text is extremely bad. The private key(s) we used in the last lesson are well-known keys for local testing, you shouldn't use those on mainnet and keeping them in plain text is ok, but any other private key should be kept hidden, especially your production key or key's associated with accounts that hold crypto. + +Moreover, it's very bad to have private keys in bash history (hit the up arrow and see the key you used to deploy). + +You can delete your history by typing: + +``` +history -c +``` + +We will teach you more about how to secure private keys in one of the next lessons. + +### Your Safety Promise + +It's time now to articulate your promise for maintaining private key safety. Create a file titled `Promise.md`. In this file, make it a point to write down your promise: + +``` +I promise to never use my private key associated with real money in plain text. +``` + +If you feel comfortable doing so, consider tweeting this to affirm and secure your pledge. Make sure to tag [@PatrickAlphaC](https://twitter.com/PatrickAlphaC) and [@CyfrinUpdraft](https://twitter.com/CyfrinUpdraft) or any other professional in this field to hold yourself accountable. + +Hacking private keys is one of the most important reasons people and projects lose absurd amounts. You don't even need to look that deep to find titles like this: + +[The Ronin hack](https://www.halborn.com/blog/post/explained-the-ronin-hack-march-2022) - Social engineering of private keys + +[Early Crypto Investor Bo Shen Says He Lost $42 Million in Wallet Hack](https://www.bnnbloomberg.ca/early-crypto-investor-bo-shen-says-he-lost-42-million-in-wallet-hack-1.1850446) + +[The \$477 million FTX hack](https://www.elliptic.co/blog/the-477-million-ftx-hack-following-the-blockchain-trail) where `The new CEO of FTX revealed that private keys allowing access to the firm’s crypto assets were stored in unencrypted form, and a former employee disclosed that over $150 million was stolen from Alameda Research, due to poor security. ` + +Don't be like that! Maybe you are not holding millions, but what you hold is yours, don't let it become theirs! + +In the following lessons, we'll learn how to access RPC URLs for free using Alchemy for any blockchain. We will also delve into exploring safer methodologies for dealing with private keys. Stay tuned! diff --git a/courses/foundry/1-foundry-simple-storage/16-deploy-a-smart-contract-locally-using-anvil/+page.md b/courses/foundry/1-foundry-simple-storage/16-deploy-a-smart-contract-locally-using-anvil/+page.md new file mode 100644 index 000000000..f3106f2ce --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/16-deploy-a-smart-contract-locally-using-anvil/+page.md @@ -0,0 +1,187 @@ +--- +title: Deploy a smart contract locally using Anvil +--- + +_Follow along with this video:_ + +--- + +### Deploy a smart contract locally using Anvil via scripts + +Deploying a smart contract via scripting is particularly handy because it provides a consistent and repeatable way to deploy reliably and its features enhance the testing of both the deployment processes and the code itself. + +There's a strong chance that you like the command-line approach, but scripting enriches the whole deployment process, bringing in more functionality and an ease of use second to none. + +Foundry eases the whole process since it is written in Solidity. This means our deployment scripts will also be written in Solidity. It is essential to distinguish Solidity as a contract language from Solidity as a scripting language. Foundry also incorporates elements that enhance our Solidity experience beyond the smart contracts realm. So, let's get started on creating a script to deploy our simple storage contract. + +In Foundry we keep our scripts in the `script` folder. + +Please create a new file called `DeploySimpleStorage.s.sol`. + +Using `.s.sol` as a suffix is a naming convention for Foundry scripts, in future lessons, when we'll write Foundry tests, these will bear the suffix of `.t.sol`. + +For more best practice info regarding Foundry scripts please click [here](https://book.getfoundry.sh/tutorials/best-practices#scripts). + +Open the newly created file. Here we'll write a solidity script for deploying our SimpleStorage contract. + +Type the following: + +```solidity +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.19; + +contract DeploySimpleStorage { + +} +``` + +The first two lines are pretty self-explanatory. + +We declare the new contract, named `DeploySimpleStorage` + +For it to be considered a Foundry script and to be able to access the extended functionality Foundry is bringing to the table we need to import `Script` from `"forge-std/Script.sol"` and make `DeploySimpleStorage` inherit `Script`. + +**NOTE**: `forge-std` also called Forge Standard Library is a collection of pre-written Solidity contracts designed to simplify and enhance scripting and testing within the Foundry development framework. + +Furthermore, to be able to deploy `SimpleStorage` we also need to import it by typing `import {SimpleStorage} from "../src/SimpleStorage.sol";` + +```solidity +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.19; + +import {Script} from "forge-std/Script.sol"; +import {SimpleStorage} from "../src/SimpleStorage.sol"; + +contract DeploySimpleStorage is Script { + +} +``` + +Every script needs a main function, which, according to the best practice linked above is called `run`. Whenever you run `forge script` this is the function that gets called. + +```solidity +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.19; + +import {Script} from "forge-std/Script.sol"; +import {SimpleStorage} from "../src/SimpleStorage.sol"; + +contract DeploySimpleStorage is Script { + function run() external returns (SimpleStorage) { + vm.startBroadcast(); + + SimpleStorage simpleStorage = new SimpleStorage(); + + vm.stopBroadcast(); + return simpleStorage; + } +} +``` +`run` is an external function that will return the `SimpleStorage` contract. + +In the Run function, we are going to use a distinctive keyword: `vm`. Foundry has a distinctive feature known as cheat codes. The `vm` keyword is a cheat code in Foundry, and thereby only works in Foundry. + +`vm.startBroadcast` indicates the starting point for the list of transactions that get to be sent to the `RPC URL`; + +Similarly, `vm.stopBroadcast` indicates the ending point of the list of transactions that get to be sent to the `RPC URL`; + +Between those two we write: + +`SimpleStorage simpleStorage = new SimpleStorage();` + +The `new` keyword is used to create a new smart contract in Solidity. + +We end the function with `return simpleStorage;`. + +Please select the `Anvil` terminal and press `CTRL(CMD) + C` to stop it. Now run the following command: + +```bash +forge script script/DeploySimpleStorage.s.sol +``` + +This should go through without any errors, but if you hit some errors related to `incompatible solidity versions in various files` please ensure that both the `SimpleStorage.sol` and `DeploySimpleStorage.s.sol` use `pragma solidity 0.8.19;` + +If you want to further extend your knowledge about scripting please go [here](https://book.getfoundry.sh/tutorials/solidity-scripting?highlight=scr#solidity-scripting) + +You should get the following output: + +```text +[⠆] Compiling... +[⠔] Compiling 2 files with 0.8.19 +[⠒] Solc 0.8.19 finished in 1.08s +Compiler run successful! +Script ran successfully. +Gas used: 338569 + +== Return == +0: contract SimpleStorage 0x90193C961A926261B756D1E5bb255e67ff9498A1 + +If you wish to simulate on-chain transactions pass a RPC URL. +``` + +**The million-dollar question**: If we didn't pass an RPC URL, where did this deploy to? + +If the RPC URL is not specified, Foundry automatically launches an Anvil instance, runs your script (in our case deployed the contract) and then terminates the Anvil instance. + +Run the `anvil` command in the terminal, open up a new terminal and type the following: + +```bash +forge script script/DeploySimpleStorage.s.sol --rpc-url http://127.0.0.1:8545 +``` + +To get the following output: + +```text +No files changed, compilation skipped +EIP-3855 is not supported in one or more of the RPCs used. +Unsupported Chain IDs: 31337. +Contracts deployed with a Solidity version equal or higher than 0.8.20 might not work properly. +For more information, please see https://eips.ethereum.org/EIPS/eip-3855 +Script ran successfully. + +== Return == +0: contract SimpleStorage 0x34A1D3fff3958843C43aD80F30b94c510645C316 + +## Setting up 1 EVM. + +========================== + +Chain 31337 + +Estimated gas price: 2 gwei + +Estimated total gas used for script: 464097 + +Estimated amount required: 0.000928194 ETH + +========================== + +SIMULATION COMPLETE. To broadcast these transactions, add --broadcast and wallet configuration(s) to the previous command. See forge script --help for more. +``` + +**Another million-dollar question**: Is it deployed now? + +Answer: No, the output indicates this was a simulation. But, we got a new folder out of this, the `broadcast` folder contains information about different script runs in case we forget details. + +Hit the up arrow key and add `--broadcast --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80` at the end. + +Our contract is now successfully deployed! Fantastic! + +Switch to the `anvil` terminal where you'll see: + +```text + Transaction: 0x73eb9fb4ef7b159e03c50d669c42e2ec4eeaa9358bea0a710cb07168e5192570 + Contract created: 0x5fbdb2315678afecb367f032d93f642f64180aa3 + Gas used: 357088 + + Block Number: 1 + Block Hash: 0x8ea564f146e04bb36fc27f0b491223a023b5882d2fcfce3ff85e0dd152e611e4 + Block Time: "Tue, 16 Apr 2024 13:39:51 +0000" +``` + +Awesome! + +Through this lesson we kept talking about a thing called `transaction`, but what is a `transaction`? Tune in the next lesson to find out. diff --git a/courses/foundry/1-foundry-simple-storage/17-what-is-a-transaction/+page.md b/courses/foundry/1-foundry-simple-storage/17-what-is-a-transaction/+page.md new file mode 100644 index 000000000..2ae821403 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/17-what-is-a-transaction/+page.md @@ -0,0 +1,56 @@ +--- +title: What is a transaction +--- + +_Follow along with this video:_ + +--- + +### More about blockchain transactions + +In the previous lesson we kept talking about transactions, but we never explained what a transaction is. In simple terms, a transaction captures details of an activity that has taken place on a blockchain. + +On the left side of your screen, in the Explorer tab, you'll find a folder called `broadcast`. Foundry saves all your blockchain interactions here. The `dry-run` folder is used for interactions you made when you didn't have a blockchain running (remember that time when we deployed our contract without specifying an `--rpc-url`). Moreover, the recordings here are separated by `chainId`. + +**Note**: The `chainId` is a unique identifier assigned to a specific blockchain network. It is used to distinguish one blockchain from another and is a crucial parameter for ensuring the security and integrity of transactions and interactions on the blockchain. + +Click on `run-latest.json`. +Here we can find more details about the last deployment script we ran in our previous lesson. It will show things like `transactionType`, `contractName` and `contractAddress`. Moreover, in the `transaction` section, you can see what we actually sent over to the RPC URL: + +```javaScript + "transaction": { + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": null, + "gas": "0x714e1", + "value": "0x0", + "input": "0x608060...c63430008130033", + "nonce": "0x0", + "chainId": "0x7a69", + "accessList": null, + "type": null + } +``` + +Let's go through each of these: + +- `from` is self-explanatory, it's the address we used to sign the transaction; +- `to` is the recipient, in our case is null or address(0), this is the standard destination for when new smart contracts are deployed; +- `gas` is the amount of gas spent. You will see the hex value `0x714e1` (or any other value represented in hex format); + +**Quick tip**: Normal humans can't understand hex values like the one indicated above, but there's a quick way to convert these into usual numbers. Run the following command in your terminal: `cast --to-base 0x714e1 dec`. `cast` is a very versatile tool provided by Foundry, type `cast --help` in your terminal to find out more, or go [here](https://book.getfoundry.sh/reference/cast/cast). + +- `value` is the transaction value, or the amount of ETH we are sending over. Given that this transaction was made to deploy a contract, the value here is `0x0` or `0`, but we could have specified a value and that would have been the initial balance of the newly deployed contract; + +- `data` in this case is the contract deployment code and the contract code. In the excerpt above this was truncated; + +- `nonce` is a unique identifier assigned to each transaction sent from a specific account. The nonce is used to ensure that each transaction is processed only once and to prevent replay attacks. `nonce` is incremented with every single transaction; + +- `accessList` is a feature of Ethereum to optimize the gas cost of transactions. It contains a list of addresses and associated storage keys that the transaction is likely to access, allowing the EVM to more efficiently compute the gas cost of storage access during the transaction's execution; + +- `type` please ignore this for now. + +There are other values that play an important part that weren't presented in that list, namely the `v`, `r`, and `s`. These are components of a transaction's signature, which are used to validate the authenticity and integrity of the transaction. + +Whenever we send a transaction over the blockchain there's a signature happening, that's where we use our `private key`. + +**Important:** Every time you change the state of the blockchain you do it using a transaction. The thing that indicates the change is the `data` field of a transaction. Deployment bytecode, contract bytecode and OPCODEs will be tackled in a future lesson. diff --git a/courses/foundry/1-foundry-simple-storage/18-important-private-key-safety-pt-2/+page.md b/courses/foundry/1-foundry-simple-storage/18-important-private-key-safety-pt-2/+page.md new file mode 100644 index 000000000..251c30c62 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/18-important-private-key-safety-pt-2/+page.md @@ -0,0 +1,53 @@ +--- +title: Important - private key safety pt.2 +--- + +_Follow along with this video:_ + +--- + +### How to not have your private key in the command line + +Some lessons ago we deployed `SimpleStorage` using the following command: + +``` +forge script script/DeploySimpleStorage.s.sol --rpc-url http://127.0.0.1:8545 --broadcast --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 +``` + +Having our private key in plain text is very bad, as we've explained in [Lesson 13](https://updraft.cyfrin.io/courses/foundry/foundry-simple-storage/private-key-safety). What can we do to avoid this, except using the `--interactive` parameter, because we don't want to keep copy-pasting our private key? + +**BIG BOLDED DISCLAIMER: What we are about to do is fine for development purposes, do not put a real key here, it very terrible for production purposes.** + +Create a new file in the root of your project called `.env`. Then, go the `.gitignore` file and make sure `.env` is in there. + +The `.env` file will host environment variables. Variables that are of a sensitive nature that we don't want to expose in public. + +Open the file and put the following in it: + +``` +PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 +RPC_URL=http://127.0.0.1:8545 +``` + +Next run `source .env`. This adds the above-mentioned environment variables into our shell. Now run `echo $PRIVATE_KEY` or `echo $RPC_URL` to check if the values are stored in the shell. + +Now we can safely replace the parameters in our `forge script` command: + +``` +forge script script/DeploySimpleStorage.s.sol --rpc-url $RPC_URL --broadcast --private-key $PRIVATE_KEY +``` + +This doesn't only hide your private key from plain sight in the command line but also facilitates faster terminal usage, imagine you'd have to copy-paste the `http://127.0.0.1:8545` RPC URL over and over again. It's cleaner this way. + +But yes, now we have the private key in plain text in the `.env` file, that's not good. + +### How to handle this problem with production code? + +Foundry has a very nice option called `keystore`. To read more about it type `forge script --help` in your terminal. Using `forge script --keystore ` allows you to specify a path to an encrypted store file, encrypted by a password. Thus your private key would never be available in plain text. + +Let's agree to the following: + +1. For testing purposes use a `$PRIVATE_KEY` in an `.env` file as long as you don't expose that `.env` file anywhere. +2. Where real money is involved use the `--interactive` option or a [keystore file protected by a password](https://github.com/Cyfrin/foundry-full-course-f23?tab=readme-ov-file#can-you-encrypt-a-private-key---a-keystore-in-foundry-yet). + +There's one more thing about storing keys in a `.env` file. Please take a look at the ["THE .ENV PLEDGE"](https://github.com/Cyfrin/foundry-full-course-f23/discussions/5). Read it, understand it and comment `I WILL BE SAFE`. Tweet it, Tiktok it, blog about it, make an Insta story about it, print it and put it on your fridge and share some copies with your neighbors. Please stay safe! diff --git a/courses/foundry/1-foundry-simple-storage/19-never-use-a-env-file/+page.md b/courses/foundry/1-foundry-simple-storage/19-never-use-a-env-file/+page.md new file mode 100644 index 000000000..266369548 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/19-never-use-a-env-file/+page.md @@ -0,0 +1,44 @@ +--- +title: Never Use A Env File +--- + +_Follow along with this video:_ + +--- + +### Meanwhile, some things have changed + +In our previous lesson, we showed you how to configure and use a `.env` file to hold your private key and rpc url, some developments have taken place since that lesson was made so ... You should never use a `.env` again. + +### Encrypting your Keys Using ERC2335 + +For now, let's pretend our private key is this: + +`0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80` (key 0 from Anvil) + +Type the following command in your terminal: +``` +cast wallet import nameOfAccountGoesHere --interactive +``` + +Ideally, you don't do this in your VS Code. + +You will be asked for your private key and a password to secure it. You will do this only once, which is amazing! + +If you remember, last lesson we deployed running the following command: +``` +forge script script/DeploySimpleStorage.s.sol --rpc-url $RPC_URL --broadcast --private-key $PRIVATE_KEY +``` + +Now that we configured our wallet we can deploy as following: + +``` +forge script script/DeploySimpleStorage.s.sol --rpc-url http://127.0.0.1:8545 --broadcast --account nameOfAccountGoesHere --sender 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 +``` +You will be asked for your password. You won't be able to deploy without your password. + +To see all the configured wallets you can call the following: `cast wallet list`. + +Clear your history so your private key won't randomly remain there using the following command: `history -c`. + +***Stay safe! Stay froggy! Don't lose your keys. If you are seeing your private key in plain text, you are doing something wrong.*** diff --git a/courses/foundry/1-foundry-simple-storage/20-interact-with-a-smart-contract-using-the-cli/+page.md b/courses/foundry/1-foundry-simple-storage/20-interact-with-a-smart-contract-using-the-cli/+page.md new file mode 100644 index 000000000..308709c7c --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/20-interact-with-a-smart-contract-using-the-cli/+page.md @@ -0,0 +1,64 @@ +--- +title: Interact with a smart contract using the CLI +--- + +_Follow along with this video:_ + +--- + +### Interacting With Contract Addresses via Command Line & Foundry's Cast Tool + +This lesson builds on top of previous lessons where we deployed `SimpleStorage` via `forge script`. We have `Anvil` running and the smart contract is deployed. + +Copy the contract address. + +### Sending information to the blockchain + +Foundry has a built-in tool known as `Cast`. `Cast` comes loaded with numerous commands to interact with. Learn more about them by typing `cast --help`. One such useful command is `send` which is designed to sign and publish a transaction. To view help about `send`, type `cast send --help`. + +To use `send` we need a signature and some arguments. + +Please call the following in your terminal: + +**Note**: Down below use the address you copy-pasted from your terminal, there's a chance it will be different than the one mine was deployed. + +``` +cast send 0x5FbDB2315678afecb367f032d93F642f64180aa3 "store(uint256)" 1337 --rpc-url $RPC_URL --private-key $PRIVATE_KEY +``` + +**What did we just do?** + +Let's break it down: +- `cast send` is the command we used to sign and publish our transaction; +- `0x5FbDB2315678afecb367f032d93F642f64180aa3` or any other address is the target of our `cast send`, the contract we are interacting with; +- `"store(uint256)"` is the [signature of the function](https://ethereum.stackexchange.com/questions/135205/what-is-a-function-signature-and-function-selector-in-solidity-and-evm-language) we are calling. +- `1337` is the number we pass to the `store` function. As we can see in the function signature, we are expected to provide an `uint256` input. You can obviously provide any number you want, as long as it fits `uint256`. +- you already know what `--rpc-url $RPC_URL --private-key $PRIVATE_KEY` are. The place where we send and the private key we use to sign. + +### Reading information from the blockchain + +`cast` conveniently provides a way to read information stored on the blockchain. Type `cast call --help` in your terminal to find out more. It works similarly to `send`, where you have to provide a signature and some arguments. The difference is you are only peering into the storage, not modifying it. + +Call the following command in your terminal: + +``` +cast call 0x5FbDB2315678afecb367f032d93F642f64180aa3 "retrieve()" +``` + +We receive back the following: +``` +0x0000000000000000000000000000000000000000000000000000000000000539 +``` +This represents a hex value. In the previous lessons, we learned how to convert this to a normal number. + +Type the following command in your terminal: +``` +cast --to-base 0x0000000000000000000000000000000000000000000000000000000000000539 dec +``` +And surprise, surprise, `1337` came back. + +I recommend you play around and send multiple transactions with different numbers and then read them from the blockchain. + +Awesome! We've learned something very valuable. You are going to use this more times than you can count. + +**Up next:** Deploying a smart contract on Sepolia diff --git a/courses/foundry/1-foundry-simple-storage/21-deploying-to-a-testnet/+page.md b/courses/foundry/1-foundry-simple-storage/21-deploying-to-a-testnet/+page.md new file mode 100644 index 000000000..ef4e1332d --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/21-deploying-to-a-testnet/+page.md @@ -0,0 +1,56 @@ +--- +title: Deploying to a Testnet +--- + +_Follow along the course with this video._ + + + +--- + +## Deploying our Contract to Testnet or Live Network with Foundry and Alchemy + +Hi, everyone! Are you curious about what your contract would look like on a testnet or a live network? If so, buckle up because this blog post will cover exactly that! We'll walk through the process of updating our Environment Variable (.env) file for an actual testnet. + +Clearly, we need an actual testnet for a real network. But our trusty MetaMask has built-in Infura connections that are incompatible. Why? Because they're tailored specifically for MetaMask. Hence, we need our own Remote Procedure Call (RPC) URL. + +## Creating our Own RPC URL for a Testnet + +_To create one, we could run our own blockchain node, but let's be honest — many folks prefer avoiding that route. Instead, we utilize Node as a Service (NaaS) applications to expedite the process._ + +One promising option is using Alchemy - a free NaaS platform that we can send the transactions to. This procedure resides within the _Deploying to Testnet or Mainnnet_ section in the full course repo of the Foundry. + +::image{src='/foundry/19-testnet-deploy/testnet1.png' style='width: 100%; height: auto;'} + +To access the Alchemy platform, we simply click on the aforementioned function. On the platform, we sign up (I used Google sign-in for this demo). + +Our next step is creating a new app in the Alchemy user interface. I named mine _Sepolia Testing_ and kept the description the same, given that our chain will be an Ethereum one based on Ethiopia. + +We can bypass advanced features for now and finalize our app. Now we have the app details needed for our node, including frequency of calls and other details. We also have a new https endpoint by clicking view key, which functions exactly the same way as our ganache or MetaMask endpoint. + +## Altering our Private Key + +Next, let's do something about our private keys. Our ganache private key will no longer cut it — it has neither real money nor any testnet ETH in it. + +Our solution is to use one of our MetaMask private keys. To do this, we switch back to Sepolia in our MetaMask, choose an account with money in it, click on account details, and export the private key. _Remember, never share your real private key!_ + +Upon confirmation with your password, copy the private key and omit the line in the env file — hashtag or pound sign denoting comments. + +## Executing the Transaction + +With our Sepolia RPC URL and private key from MetaMask, executing a transaction now becomes tremendously easier. + +```bash +source .env +forge script script/deploySimpleStorage.s.sol --rpc-url=$Sepolia_RPC_URL --private-key=$PRIVATE_KEY --broadcast +``` + +This command deploys our contract to the testnet, and we can monitor the transaction on our Alchemy dashboard. + +We soon find that our contract, Simple Storage, has been deployed on the Sepolia chain. We can grab our transaction hash and input it into Sepolia etherscan IO to confirm the successful transaction. + +After we refresh our Alchemy dashboard, we'll verify the requests sent and track the ETH send raw transaction that transmitted our transaction to the blockchain. + +So, this is how we deploy our contract on a real testnet leveraging Foundry and Alchemy! + +Our next step will explore adding real-world components to the mix. Stay tuned! diff --git a/courses/foundry/1-foundry-simple-storage/22-verify-a-smart-contract-on-etherscan/+page.md b/courses/foundry/1-foundry-simple-storage/22-verify-a-smart-contract-on-etherscan/+page.md new file mode 100644 index 000000000..bd2ca42c5 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/22-verify-a-smart-contract-on-etherscan/+page.md @@ -0,0 +1,43 @@ +--- +title: Verify a smart contract on Etherscan +--- + +_Follow along with this video:_ + +--- + +### Manually verify a smart contract on Etherscan + +Soooo ... we just deployed our smart contract on Sepolia, let's check it out! + +We go [here](https://sepolia.etherscan.io/address/0x1093560Fe9029c4fB9044AbF2fC94288970D98Db#code) click on `Contract` and find this: + +::image{src='/foundry-simply-storage/21-verify-a-smart-contract-on-etherscan/Image1.PNG' style='width: 75%; height: auto;'} + +This bytecode looks horrendous. We need to do something to improve the readability (which currently is non-existent). + +Etherscan is prompting us to do something about it via the message: `Are you the contract creator? Verify and Publish your contract source code today!` + +So, let's click on `Verify and Publish`. + +The address of the Contract comes prepopulated, if not please paste it from your terminal. + +Select `Solidity(Single file)` because we are using solidity and we have only one file. + +Select your Compiler Version. My contract used solidity 0.8.19. + +The license type we used is MIT. + +On the next page, paste your Solidity Contract. Select `Yes` in `Optimization`, and leave everything else as is. + +Finish up the `verify` process. If you get this message: + +``` +Successfully generated Bytecode and ABI for Contract Address [0x1093560Fe9029c4fB9044AbF2fC94288970D98Db] +``` + +you did it right! + +Now you have access to the `Read Contract` and `Write Contract`. This lets you interact directly with your contract through etherscan. + +Congratz! You just learned how to verify a smart contract on etherscan, the manual way. This is not the ideal way, in the future, we will teach you how to verify them programmatically. diff --git a/courses/foundry/1-foundry-simple-storage/23-cleaning-up-the-project/+page.md b/courses/foundry/1-foundry-simple-storage/23-cleaning-up-the-project/+page.md new file mode 100644 index 000000000..7a00e1b6a --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/23-cleaning-up-the-project/+page.md @@ -0,0 +1,62 @@ +## Cleaning Up the Project + +We've covered a lot of ground in this project. We learned how to write our first Solidity contract, how to deploy it to a test network, and how to interact with it using Forge. Before we move on to more complex projects, let's take a moment to clean things up and make sure our project is well-organized. + +### Formatting + +One important aspect of any project is consistency in formatting. We've been using VS Code's auto-formatter to help us with this, but it's important to make sure that anyone else working on the project is following the same formatting rules. + +Forge has a built-in format command that we can use to ensure consistent formatting across the project. We can run this command in our terminal with: + +```bash +forge fmt +``` + +This command will automatically format all our Solidity files according to Forge's default style. + +### README.md + +Another important file to include in any project is a `README.md` file. This file serves as a guide for anyone who wants to learn about your project, how to use it, or how to contribute to it. + +The `README.md` file is written in Markdown, which is a lightweight markup language that's easy to read and write. + +Here's an example of what you might include in your `README.md` file: + +````markdown +# SimpleStorage + +This is a simple Solidity contract that stores a single uint256 value. + +## Getting Started + +1. Clone this repository. +2. Install Forge using the instructions found at [https://github.com/foundry-rs/foundry](https://github.com/foundry-rs/foundry). +3. Run the following command to compile the contract: + +```bash +forge build +``` + +4. Run the following command to deploy the contract to a test network: + +```bash +forge create +``` + +5. Interact with the contract using Forge's interactive console. + +```bash +forge console +``` + +## Contributing + +We welcome contributions to this project. If you're interested in contributing, please open an issue or submit a pull request. +``` +We can preview our `README.md` file in VS Code by going to the `View` menu and selecting `Open Preview to the Side`. This will open a new window showing what the `README.md` file will look like when it's rendered on GitHub. + +### Using AI for Markdown Formatting + +If you find that formatting Markdown is a bit tedious, you can use an AI tool like ChatGPT to help you out. Just copy and paste the text you want to format into ChatGPT and ask it to format it in Markdown. It will do a pretty good job of converting your plain text into Markdown, and you can then review and edit it as needed. + +```` diff --git a/courses/foundry/1-foundry-simple-storage/24-foundry-zksync/+page.md b/courses/foundry/1-foundry-simple-storage/24-foundry-zksync/+page.md new file mode 100644 index 000000000..accf8bb0f --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/24-foundry-zksync/+page.md @@ -0,0 +1,34 @@ +--- +title: Foundry ZKsync +--- + +_Follow along with the video_ + +--- + +In this lesson, we'll explore Layer 2 deployment on ZKsync, which involves a different compilation method compared to Ethereum. This difference arises because ZKsync uses unique opcodes. While Solidity code behaves similarly on both platforms, the low-level outputs generated by Foundry in the `/out` folder will not be entirely compatible with the ZKsync VM. + +### Foundry ZKsync + +To get started with ZKsync, we will follow these three steps: + +1. 🛠️ Install `foundry-zksync` +2. 🧑‍💻 Compile the Solidity contract with the `--zksync` flag +3. 🔄🏠 Reinstall the original Vanilla Foundry + +> 👀❗**IMPORTANT**:br +> Installing `foundry-zksync` will override any existing Foundry binaries, such as `forge` and `cast`. + +The GitHub resources for this course contain a link to the [Foundry ZKsync repository](https://github.com/Cyfrin/foundry-full-course-cu?tab=readme-ov-file#compiling-to-zksync-in-foundry-zksync). `foundry-zksync` is a fork of Foundry tailored for the ZKsync environment. The [repository](https://github.com/matter-labs/foundry-zksync) includes quick install instructions to help you set up the tool. + +- First, clone the Foundry ZKsync repository in a different directory from your Foundry project. Use the `git clone` command to clone the repository locally on your computer. + +- Once cloned, navigate to the created Foundry ZKsync directory and run the installation command: + + ``` + ./install-foundry-zksync + ``` + + This command requires a Unix-like environment, such as WSL on Windows, or a Mac or Linux system. After running the command, verify the installation by checking the version with `forge --version`. A different version number will indicate the successful installation of Foundry ZKsync. + +- To keep your environment flexible, you can switch to Foundry ZKsync by running `foundryup-zksync`. After using it, it's recommended to switch back to Vanilla Foundry by running the `foundryup` command. This removes ZKsync-specific flags and settings, allowing you to easily toggle between Foundry ZKsync and Vanilla Foundry as needed. diff --git a/courses/foundry/1-foundry-simple-storage/25-compiling-foundry-zksync/+page.md b/courses/foundry/1-foundry-simple-storage/25-compiling-foundry-zksync/+page.md new file mode 100644 index 000000000..9d06c5c60 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/25-compiling-foundry-zksync/+page.md @@ -0,0 +1,11 @@ +--- +title: Compiling foundry ZKsync +--- + +_Follow along with the video_ + +--- + +> Previously, when we ran the `forge build` command, it generated an `/out` folder in the root project directory. This folder contains all the compilation details related the Ethereum Virtual Machine (EVM) and Vanilla Foundry. To compile for the ZKsync chain instead, we use the command `forge build --zksync`. This command creates a new folder in our project root called `/zkout`, and contains all the compiled code compatible to the ZKsync Era VM. + +If we need to revert to vanilla Foundry for deployment on the EVM, we simply run the command `foundryup` and then use `forge build`, which builds a standard Foundry project. Unless otherwise specified, we should continue using this method. diff --git a/courses/foundry/1-foundry-simple-storage/26-zksync-local-node/+page.md b/courses/foundry/1-foundry-simple-storage/26-zksync-local-node/+page.md new file mode 100644 index 000000000..fbf8cbf1c --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/26-zksync-local-node/+page.md @@ -0,0 +1,37 @@ +--- +title: ZKsync Setting up Local Node +--- + +_Follow along with the video_ + +--- + +### Introduction + +> 👀❗**IMPORTANT**:br +> This lesson is optional. If you encounter difficulties installing or understanding the required tools, feel free to proceed to the next section and continue using Anvil to test your smart contract locally. + +In the previous lessons, we learned about deploying smart contracts with the `forge create` and `forge script` commands on our **local Anvil chain**. In this lesson, we will set up and run a **ZKsync local environment**. + +### Local Node Setup + +To deploy locally on a ZKsync local chain, you'll need additional tools: Docker, Node.js, and zksync-cli. + +1. **Docker**: Start the [Docker](https://www.docker.com/) daemon. On Mac OS, you can start it using the Docker application interface. On Linux, use commands like `sudo systemctl start docker` and `sudo systemctl stop docker` will manage Docker lifecycles. Verify the installation with `docker --version` and `docker ps` commands. + +2. **Node.js and npm**: Install [Node.js](https://nodejs.org/en) and [npm](https://www.npmjs.com/). Follow the Node.js documentation to install the right version for your operating system. Verify the installations with `npm --version` and `node --version` commands. + +3. **zksync-cli**: Once Docker and Node.js are installed, you can install the [zksync-cli](https://www.npmjs.com/package/zksync-cli) to manage your local ZKsync development environment. Run `npx zksync-cli dev config` to set up your configuration. Choose the `in-memory` node option for a quick startup without persistent state and avoid additional options like a portal or block explorer unless you want to explore them independently. + +To start your local ZKsync node, run `npx zksync-cli dev start`. This command spins up a ZKsync node in Docker and runs it in the background. Verify the process is running with `docker ps`. + +> 🗒️ **NOTE**:br +> If Docker isn’t running, the `npx zksync-cli dev start` command will fail. Ensure Docker is running before attempting to start the ZKsync node again. + +### Deployment + +The ZKsync deployment process is similar to previous deployments. We will use the same commands, but this time, we will append the `--zksync` and `--legacy` flags. Note that the `forge script` command is not well supported in ZKsync, so we will use `forge create` instead. + +### Conclusion + +Setting up a local ZKsync node involves a few additional tools, including Docker, Node.js, npm, and zksync-cli: they will help creating a robust ZKsync development environment and allowing test and deployment of smart contracts on a ZKsync local chain. diff --git a/courses/foundry/1-foundry-simple-storage/27-zksync-local-deploy/+page.md b/courses/foundry/1-foundry-simple-storage/27-zksync-local-deploy/+page.md new file mode 100644 index 000000000..2d2ea270a --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/27-zksync-local-deploy/+page.md @@ -0,0 +1,30 @@ +--- +title: ZKsync Local Deployment +--- + +_Follow along with the video_ + +--- + +In this lesson, we are going to deploy the contract `SimpleStorage.sol` on a **ZKsync local chain**. + +We start by verifying that the Forge version we are using is correct. By running the `forge --version` command it confirms that we are on version 0.2: this indicates we are using the right Foundry ZKsync edition. + +Next, we proceed with creating a `SimpleStorage` contract using the command: + +```bash +forge create src/SimpleStorage.sol:SimpleStorage --rpc_url --private_key --legacy --zksync +``` + +Here, `` represents ZKsync node address, such as `http://127.0.0.1:8011`. + +> 👀❗**IMPORTANT**:br +> Including private keys directly in commands is not a safe practice. + +This command instructs Foundry to locate the `SimpleStorage` contract in the `src/SimpleStorage.sol` file and deploy it. Upon execution, the contract compiles and deploys successfully. The output will display details such as the deployer, the deployed contract address, and the transaction hash. + +::image{src='/foundry-simply-storage/27-zksync-local-deploy/deployment-successful.png' style='width: 50%; height: auto;'} + +Using the `--legacy` flag is recommended for deploying simple contracts, while more complex codebases may require different approaches. Attempting to deploy without the `--legacy` flag might result in errors like `failed to serialize transaction, address to address is null`, which will be covered in future lessons. + +Once you are finished, you can close Docker Desktop and revert to the Vanilla Foundry environment using the `foundryup` command. diff --git a/courses/foundry/1-foundry-simple-storage/28-tx-types/+page.md b/courses/foundry/1-foundry-simple-storage/28-tx-types/+page.md new file mode 100644 index 000000000..e1565ff20 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/28-tx-types/+page.md @@ -0,0 +1,36 @@ +--- +title: Transaction Types +--- + +_Follow along with the video_ + +--- + +### Introduction + +In this lesson, we will explore the different transaction types within the ZKsync VM and EVM ecosystems. + +### `/broadcast` Folder + +When deploying to a ZKsync local node, a `/broadcast` folder will be created and it will contain detailed information about the **deployment transactions**. Inside this folder, you will find subfolders named after specific deployment chain IDs, such as **`260`** for ZKsync and **`31337`** for Anvil. These subfolders store the data of the transactions executed during the deployment process. + +By examining both the `run-latest.json` file in these folders, we can observe different **transaction types** for each transaction within a chain. For instance, transactions on the Anvil chain might be labeled as type **`0x2`**, while those on the ZKsync chain will be of type **`0x0`**. Deploying a smart contract on the EVM without the `--legacy` flag results in a default transaction type of `0x2`. Adding the `--legacy` flag changes it to type `0x0`. + +The EVM and ZKsync ecosystems support multiple transaction types to accommodate various Ethereum Improvement Proposals (EIPs). Initially, Ethereum had only one transaction type (`0x0` legacy), but as the ecosystem evolved, multiple types were introduced through various EIPs. Subsequent types include type 1, which introduces an _access list_ of addresses and keys, and type 2, also known as [EIP 1559](https://eips.ethereum.org/EIPS/eip-1559) transactions. + +> 👀❗**IMPORTANT**:br +> This `0x2` type is the current default type for the EVM. + +Additionally, ZKsync introduces its [unique transaction type](https://docs.zksync.io/zk-stack/concepts/transaction-lifecycle#eip-712-0x71), the type `113` (`0x71` in hex), which can enable features like [account abstraction](https://docs.zksync.io/build/developer-reference/account-abstraction/). + +> 💡 **TIP**:br +> The `forge script` command will work in some scenarios, but it’s not entirely clear where it might fail. For the purpose of this course, we will assume scripting does not work while working with ZKsync. + +### Resources + +- [ZKsync documentation](https://docs.zksync.io/zk-stack/concepts/transaction-lifecycle#transaction-types) about transaction types +- [Cyfrin Blog on EIP-4844](https://www.cyfrin.io/blog/what-is-eip-4844-proto-danksharding-and-blob-transactions) + +### Conclusion + +The ZKsync VM and EVM ecosystems support various transaction types to meet different EIP requirements. By examining deployment folders and understanding the use of flags like `--legacy`, we can effectively distinguish between these transaction types. diff --git a/courses/foundry/1-foundry-simple-storage/29-why-l2/+page.md b/courses/foundry/1-foundry-simple-storage/29-why-l2/+page.md new file mode 100644 index 000000000..ceaa6b3fc --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/29-why-l2/+page.md @@ -0,0 +1,30 @@ +--- +title: L2s +--- + +_Follow along with the video_ + +--- + +### Introduction + +In previous lessons, we deployed to the Sepolia testnet and started working with the Layer 2 solution ZKsync. Deploying to Sepolia simulates deployment to the Ethereum mainnet, offering a comprehensive understanding of Layer 1 deployments. However, it's important to note that most projects today prefer deploying to Layer 2 solutions rather than directly to Ethereum due to the high costs associated with deployments. + +### Gas Usage + +When deploying to a ZKsync local node, a `/broadcast` folder is created, containing a lot of detailed deployment transaction information. For instance, in our `run-latest.json` file, we can see the `gasUsed` value and we can convert this hexadecimal number `0x5747A` to its decimal equivalent by typing `cast to base 0x5747A dec`. This conversion allows us to estimate the deployment cost on the Ethereum mainnet. By checking recent gas prices on Etherscan, we can calculate the total cost using the formula: + +``` +Total Cost = Gas Used * Gas Price +``` + +We can see this total cost in the deployment transaction on [Sepolia Etherscan](https://sepolia.etherscan.io/tx/0xc496b9d30df33aa9285ddd384c14ce2a58eef470898b5cda001d0f4a21b017f6), under the `Transaction Fee` section. In this case, `357,498` gas will costs `0.000279288255846978` ETH, which today is equivalent to $7. + +Deploying even a minimal contract like `SimpleStorage` on Ethereum can be expensive. Larger contracts, with thousands of lines of code, can cost thousands of dollars. This is why many developers prefer deploying to Layer 2 solutions like ZKsync, which offer the same security as Ethereum but at a fraction of the cost. + +### Deploying to ZKsync Sepolia + +Deploying to ZKsync Sepolia is similar to deploying to a ZKsync local node. You can retrieve a ZKsync Sepolia RPC URL from [Alchemy](https://www.alchemy.com/) by creating a new app based on the ZKsepolia network. Then, you can proceed to add the `ZKSYNC_RPC_URL` to your `.env` configuration. + +> 🗒️ **NOTE**:br +> To understand the cost benefits of Layer 2 solutions, visit [L2Fees.info](https://l2fees.info) and compare the significant cost differences between sending a transaction on Ethereum and ZKsync Era. diff --git a/courses/foundry/1-foundry-simple-storage/30-alchemy-mempool/+page.md b/courses/foundry/1-foundry-simple-storage/30-alchemy-mempool/+page.md new file mode 100644 index 000000000..03a1dcb3b --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/30-alchemy-mempool/+page.md @@ -0,0 +1,82 @@ +--- +title: Alchemy & The Mempool +--- + +_Follow along the course with this video._ + + + +--- + +## Alchemy: A Game Changer for Decentralized Application Development + +Innovation in the blockchain industry has come a long way, with powerful tools making their way into the ecosystem to support developers and bring efficiency to their workflows. Among these tools is Alchemy, and today we have Vito, the lead developer experience at Alchemy, to walk us through the platform, its features, and how you can leverage it to exponentially increase your productivity. + +## What is Alchemy? + +Alchemy is a platform equipped with APIs, SDKs, and libraries to enhance your developer experience while working on Web3 projects. Think of Alchemy as the AWS of Web3. It functions as a node provider and developer tooling platform predominantly used in thousands of Web3 and Web2 applications, including large Web2 corporations like Adobe, Shopify, and Stripe. + +The need for platforms such as Alchemy arises from the fact that, as a developer, you don't usually have to worry about running the servers your code operates on or developing the deployment and integration pipelines for your application. Instead, you use services such as AWS, Azure, and Google Cloud for that—Alchemy does the same but for Web3. + +## How Does Alchemy Work? + +Alchemy enhances your developer experience through a combination of features. The platform's primary component is the _Supernode_, a proprietary blockchain engine that works as a load balancer on top of your node. + +Like its name suggests, the Supernode ensures data from the blockchain is always up-to-date and readily available. Using the Supernode as a foundation, Alchemy has built the _Enhanced APIs_—a set of APIs that makes pulling data from the blockchain a breeze. + +To put it simply, the Alchemy Supernode sits at the core of its ecosystem, powering up functionalities like Enhanced APIs and monitoring tools while supporting multiple chains. + +What follows is a step-by-step guide on how to create a new account on Alchemy and leverage this platform to its full extent: + +## Creating a New Account on Alchemy + +Creating an account on Alchemy is not only easy but also completely free. You can also freely scale your applications up using the platform's generous premium plans. + +#### Step 1: Navigate to Alchemy.com + +Head over to [Alchemy.com](https://www.alchemy.com/) and create a new account. + +#### Step 2: Create a New Application + +Once you have signed in, create a new application. + +Next, give your application a name and a description. Then, select a chain and network. Alchemy currently supports the majority of EVM-compatible chains, including: + +- Ethereum +- Polygon PoS +- Polygon zkEVM +- Optimism +- Arbitrum +- Solana (non-EVM chain) + +## The Application-Specific Dashboard + +Once your application is up and running, you will have access to the application-specific dashboard. This dashboard provides crucial insights into your application and infrastructure health, such as latency, compute units, and transaction success rate, which can be valuable for debugging and identifying issues. + +If you observe a lower success rate for your transactions, go to the "Recent Invalid Request" tab. This will list all unsuccessful requests along with the reasons for their failure, making it easier for you to debug and fix issues. + +::image{src='/foundry/22-alchemy/alchemy1.png' style='width: 100%; height: auto;'} + +## Mempool Watcher + +Another powerful tool provided by Alchemy is the Mempool watcher. Picture it as Ethereum's mempool, where all pending transactions reside waiting for validation or mining. + +The Mempool watcher provides extensive details about your transactions, such as: + +- Transaction status (mined, pending, dropped, replaced) +- Gas used +- Time taken for validation +- Transaction value +- Sender's and receiver's address + +This detailed transaction tracking allows you to have a better understanding of each transaction and aids immensely in debugging specific issues related to individual transactions. + +## Wrapping Up + +To sum up, Alchemy is a revolutionary platform that brings a plethora of tools to aid your Web3 development experience. From Supernode to Enhanced APIs and crucial troubleshooting tools, Alchemy is undeniably a game changer in the world of decentralized applications. + +"Alchemy can be a powerful asset to any blockchain developer, offering a simplified experience in an inherently complicated Web3 environment." – Vito, Lead Developer Experience at Alchemy. + +Vito suggests that you check out Alchemy's [documentation](https://docs.alchemy.com/) to explore more about the platform, its APIs, SDKs, libraries, and tools. Also, don't forget to follow them on Twitter at [@AlchemyPlatform](https://twitter.com/alchemyplatform) and [@AlchemyLearn](https://twitter.com/alchemyLearn). And if you want to connect directly with Vito, feel free to reach out to him on Twitter at [@VitoStack](https://twitter.com/VittoStack). + +Alchemy is revolutionizing the landscape of blockchain development and making it more accessible and efficient for everyone involved. Happy building with Alchemy! diff --git a/courses/foundry/1-foundry-simple-storage/31-summary-congratulations/+page.md b/courses/foundry/1-foundry-simple-storage/31-summary-congratulations/+page.md new file mode 100644 index 000000000..fdffe8891 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/31-summary-congratulations/+page.md @@ -0,0 +1,47 @@ +--- +title: Summary & Congratulations +--- + +_Follow along the course with this video._ + + + +--- + +## Celebrating Milestones in Foundry: A Complete Walkthrough of Our Recent Project + +You should feel a warm sense of accomplishment envelop you. Completing an entire project in Foundry is no mean feat. A hearty congratulation is in order for such an indomitable effort. This article serves as a quick, yet comprehensive, recap of everything we learnt in our project, proceeding into our next engagement. From the onset, rest assured, we are set to advance our Foundry skills, push upcoming projects on GitHub, and familiarize ourselves with advanced tooling. + +## A Quick Trip Down Memory Lane: Key Takeaways from the Project + +Firstly, we journeyed through the process of creating a new Foundry project using Forge and Knit. These essential tools afforded us a structured, professional environment complete with folders to keep our work organized. + +We not only learnt about Foundry’s basic commands but also their specific functionalities such as: + +- **Cast**: interacts with contracts that have been previously deployed. +- **Forge**: compiles and interacts with our contracts. +- **Anvil**: deploys a local blockchain, similar to another tool we used, Ganache. + +A pivotal part of our learning process was comprehending that sending a transaction via our MetaMask is tantamount to making an HTTP post request to a particular RPC URL. A similar RPC URL can be obtained from a node-as-a-service provider like [Alchemy](https://www.alchemyapi.io/) and used to send transactions directly from our Foundry projects. + +We obtained practical knowledge on how to compile code in Foundry and write a Solidity script for its subsequent deployment. We also find it critical to ensure the security of our private keys. Hence, throughout this course, we will be using an `.env` file. But be warned when dealing with real money, having your private key in plain text is not advisable. + +## Understanding Contract Deployment and Interaction on the Blockchain + +We delved into the automation of contract deployments to a blockchain. Post-deployment, we interacted with them using the `cast` keyword and `send` to make transactions, then `cast call` to read from those contracts. + +Moreover, the knowledge on how to auto format contracts with `Forge format` was acquired. We also learnt the painstaking yet rewarding manual method of verifying our contracts on the blockchain. + +```bash +forge format my_contract.sol +``` + +::image{src='/foundry/23-summary/summary1.png' style='width: 100%; height: auto;'} + +## Looking Ahead + +With these tools in your web development arsenal, you've performed exceptionally well – and yes, you should be incredibly proud. Remember, even something as small as installing tools like `Vs code` and `Foundry` can pose great difficulties, so, you're doing fantastic. + +Take a breather. Remember, breaks enhance productivity. Till next time, continue to strive for greatness in every line of code you write! + +::image{src='/foundry/23-summary/summary2.png' style='width: 100%; height: auto;'} diff --git a/courses/foundry/1-foundry-simple-storage/4-develop-in-cloud-using-gitpod/+page.md b/courses/foundry/1-foundry-simple-storage/4-develop-in-cloud-using-gitpod/+page.md new file mode 100644 index 000000000..11d4b0033 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/4-develop-in-cloud-using-gitpod/+page.md @@ -0,0 +1,21 @@ +--- +title: Develop in the cloud using Gitpod +--- + +_Follow along with this video:_ + +--- + +### Develop in the cloud using Gitpod + +**BIG BOLDED DISCLAIMER: This is not the ideal way to develop smart contracts. While using Gitpod you should never share private information, like a key or a secret phrase. That's if you like to continue being the owner of the associated accounts.** + +Gitpod is an online platform that provides cloud-based, pre-configured development environments specifically designed for working with Git repositories. It's similar to Remix IDE, but it allows you to run VS Code in a browser, on a remote server. + +Go to [Gitpod's website](https://gitpod.io/login/) and click `Continue with Github`. After that, you'll be able to create a new workspace, starting from a Github repository, using a stable version of VS Code. + +You'll be amazed to find out it looks exactly like VS Code. There's also an option to open Gitpod into your VS Code desktop version. + +Everything works like in VS Code and thus you should be able to run anything using the same commands. + +Gitpod has some [fantastic resources](https://www.gitpod.io/docs/introduction/getting-started) to get you started. diff --git a/courses/foundry/1-foundry-simple-storage/5-local-setup/+page.md b/courses/foundry/1-foundry-simple-storage/5-local-setup/+page.md new file mode 100644 index 000000000..217dcbee6 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/5-local-setup/+page.md @@ -0,0 +1,9 @@ +--- +title: Local Setup +--- +_Follow along with the video_ +--- + +To maintain a clean terminal, especially when it becomes cluttered, you can type the command "clear" and press Enter. Alternatively, use the shortcut `command + k` on a Mac or `control + k` on Linux or Windows. + +It's important to understand the difference between the **`trash can`** and the **`x`** icons in your VS code terminal: clicking the **`x`** icon it will _hide/show the terminal_, keeping all previous content visible when reopened. Clicking on the **`trash can`** icon instead, _terminates the current terminal session_. When you reopen it, you’ll see a fresh, empty session. \ No newline at end of file diff --git a/courses/foundry/1-foundry-simple-storage/6-foundry-install/+page.md b/courses/foundry/1-foundry-simple-storage/6-foundry-install/+page.md new file mode 100644 index 000000000..2868dbb5a --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/6-foundry-install/+page.md @@ -0,0 +1,87 @@ +--- +title: Foundry Install +--- + +_Follow along the course with this video._ + + + +--- + +Welcome to this handy guide on installing and operating Foundry, a versatile tool that will add a new level of command-line ease to your developer journey. Whether you're running Windows, Linux or MacOS, we've got you covered with instructions and tips. So sit back, grab a cup of coffee, and let's dive in. + +## Prepping your Terminal + +First things first. Before we dive into installing Foundry, make sure you have your terminal set up correctly. + +If you are using Windows, you should see something like `WSL` or `Ubuntu`. Once you have your terminal environment ready, it’s time for some quick tips to help streamline your workflow. + +### Keeping your Terminal Clutter-free + +When commands pile up in your terminal, things can get a little overwhelming. Clear it up by simply typing `clear` and hitting `Enter`. Alternatively, use `Command K` if you're on a Mac or `Control K` if you're on Linux or Windows. + +**Pro tip:** This is one of my favorite keyboard shortcuts that I use all the time. + +### Understanding the Trash Can and the X + +::image{src='/foundry/5-foundryinstall/foundryinstall1.png' style='width: 100%; height: auto;'} + +The trash can and the X buttons in your terminal perform distinct functions. Hitting `X` simply hides your terminal but retains all the previous lines of code. On the other hand, trashing it essentially deletes whatever is running in it. To open up a clean terminal, hit the trash can and then pull it back using `Toggle` or `Terminal > New Terminal`. + +## Installing Foundry + +With our terminal set and some tips up our sleeve, let's progress to installing Foundry. Navigate to the [Foundry website](https://book.getfoundry.sh/getting-started/installation) and from the installation tab, fetch the command to install Foundry. + +The command would look something like this: + +```bash +curl -L https://foundry.paradigm.xyz | bash +``` + +Hit `Enter` after pasting this in your terminal. + +**Note:** You must have Internet access for this to work as it's downloading Foundry from their official website. + +## Verifying Your Installation + +After running the `curl` command, an output will appear at the bottom of your terminal indicating the detected shell and the fact that Foundry has been added to your `Path`. + +For instance, the output can be something like this: + +```bash +Detected your preferred shell is bashrc and added Foundry to Path run:source /home/user/.bashrcStart +a new terminal session to use Foundry +``` + +Now, simply type `foundryup` and `Enter` to install and update Foundry to the latest version. Whenever you want to install an update for Foundry, simply run `foundryup` again. + +This will install four components: forge, cast, anvil, and chisel. To confirm the successful installation, run `forge --version`. You should get an output indicating the Forge version as shown below. + +```bash +Forge version x.x.x +``` + +Now, here's something to remember: when you hit the trash can in the top right, it literally 'removes' the terminal. The X button, in contrast, simply hides it. + +### Is Foundry Up Not Running? + +Don't panic if this command doesn't run. You might have an issue with your path, and you might need to add Foundry to your path. In case you run into this issue, check lesson 6 of the GitHub repo associated with this course. If no debugging tips are available there, feel free to start a discussion on the course's GitHub repo. Before doing so, make sure to check if a similar discussion already exists. + +Try typing `forge --version` into your terminal. Have you received an unwelcome output saying `Forge command found`? This implies that you have to rerun the `source` command that Foundry offered during installation. + +Note: Most of the time the `bashrc` file gets loaded automatically. However, if this doesn't apply to your setup, the following lines can add the required command to the end of your `Bash profile`. This will ensure that your `bashrc` file loads by default. + +```bash +cd ~ +echo 'source /home/user/.bashrc' >> ~/.bash_profile +``` + +> this depends on your operating system, please check foundry docs to see detailed instructions. + +## Wrapping Up + +And there we have it! Congratulations on installing Foundry and prepping your terminal to work seamlessly with it. Remember, hitting snags during installation is normal, especially if you're new to this. Don't hesitate to engage with the course community via GitHub if you run into issues. + +::image{src='/foundry/5-foundryinstall/foundryinstall2.png' style='width: 100%; height: auto;'} + +Here's to many hassle-free coding sessions with Foundry! diff --git a/courses/foundry/1-foundry-simple-storage/7-setup-your-vscode/+page.md b/courses/foundry/1-foundry-simple-storage/7-setup-your-vscode/+page.md new file mode 100644 index 000000000..48f14854c --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/7-setup-your-vscode/+page.md @@ -0,0 +1,67 @@ +--- +title: Setup your VSCode +--- + +_Follow along with this video:_ + +--- + +## VS Code setup + +### Installing VS Code extensions + +1. Open the Extensions view: + +There are two ways to do this: + +Click the Extensions icon in the Activity Bar on the left side of VS Code. + +Use the shortcut Ctrl+Shift+X (Windows/Linux) or Cmd+Shift+X (Mac). + +2. Browse or search for extensions: + +The Extensions view displays featured extensions by default. + +Use the search bar to find a specific extension by name. + +3. Install the extension: + +Once you've found the extension you want, click the "Install" button. +VS Code will handle the download and installation process. + +**That's it! The extension should be ready to use within VS Code.** + + +### Integrating AI into our work + +One of the best extensions that integrates AI in our development is GitHub Copilot + +Although it's a premium service, its intuitive AI-powered code autocomplete feature could be a game-changer for you. Of course, you can choose to go with other AI extensions based on your preferences. + +You can download GitHub Copilot [here](https://marketplace.visualstudio.com/items?itemName=GitHub.copilot). More details and answers for your GitHub Copilot-related questions are available [here](https://github.com/features/copilot/?editor=vscode#faq). + + +### Other important VS Code Tips + +***Beware the white dot***, if you see it, your work is not saved, which means your project won't behave the way you want it to behave. + +```CTRL(CMD) + ` ```opens/closes your terminal. It's the equivalent of pressing the `X` button on the top right part of your terminal. + +The `trash can` button, on the left side of the `X` button destroys the terminal, make sure you always remember the difference between these two buttons. + +Hooray! This concludes the setup part of this course. Now we get to the fun part, actually developing a project using solidity and foundry. + + +### More setup ... + +Run the following commands in your terminal: + +``` +mkdir foundry-f23 +cd foundry-f23 +``` + +`mkdir` creates a directory or subdirectory. +`cd` changes the directory. + +Moving forward, it's advisable to keep all your repositories in this folder. Thus, you'll always have a place to reference all your code. diff --git a/courses/foundry/1-foundry-simple-storage/8-create-a-new-foundry-project/+page.md b/courses/foundry/1-foundry-simple-storage/8-create-a-new-foundry-project/+page.md new file mode 100644 index 000000000..818e66f52 --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/8-create-a-new-foundry-project/+page.md @@ -0,0 +1,86 @@ +--- +title: Create a new Foundry project +--- + +_Follow along with this video:_ + +--- + +### More setup + +Make sure we are in the folder we created in the previous lesson. + +**Reminder**: We ran the following commands + +``` +mkdir foundry-f23 +cd foundry-f23 +``` + +Now type the following commands: + +``` +mkdir foundry-simple-storage-f23 +cd foundry-simple-storage-f23 +``` + +You can always make the `cd` command faster by pressing the `Tab` key after you type the first couple of letters from the destination name. `Tab` lets you autocomplete a lot of commands/paths. + +If you type `code .` a new instance of VS Code will open, having the `foundry-simple-storage-f23` as the default path. + +You can see the contents of this folder on the left sidebar. Try the following command: + +``` +touch randomFile.txt +``` + +This will create a `randomFile.txt` + +If you want to delete it type: + +``` +rm randomFile.txt +``` + +The terminal is pretty slick when it comes to moving/opening/creating directories/files, changing paths and generally running things. I recommend going through [this tutorial](https://ubuntu.com/tutorials/command-line-for-beginners#1-overview) if you want to learn how to move extra fast. + +### Creating a New Project + +The way you [create a new Foundry project](https://book.getfoundry.sh/projects/creating-a-new-project) is by running the `forge init` command. This will create a new Foundry project in your current working directory. + +If you want Foundry to create the new project in a new folder type `forge init nameOfNewFolder`. + +Keep in mind that by default `forge init` expects an empty folder. If your folder is not empty you must run `forge init --force .` + +Be sure to configure your username and email if you encounter errors related to Git configuration. + +``` +git config --global user.email "yourEmail@provider.com" +git config --global user.name "yourUsername" +``` + +And that's it, your folder should look as follows: + +::image{src='/foundry-simply-storage/7-create-a-new-foundry-project/Image1.PNG' style='width: 75%; height: auto;'} + +**But what does all this mean?** + +`lib` is the folder where all your dependencies are installed, here you'll find things like: + +- `forge-std` (the forge library used for testing and scripting) +- `openzeppelin-contracts` is the most battle-tested library of smart contracts +- and many more, depending on what you need/install + +`scripts` is a folder that houses all your scripts + +`src` is the folder where you put all your smart contracts + +`test` is the folder that houses all your tests + +`foundry.toml` - gives configuration parameters for Foundry + +More on these folders and files later. + +Please right-click `src`, click on `New File` and name it `SimpleStorage.sol`. Copy the code available [here](https://github.com/Cyfrin/foundry-simple-storage-f23/blob/main/src/SimpleStorage.sol). + +One last thing, please delete `Counter.s.sol`, `Counter.sol` and `Counter.t.sol`. These files are a set of basic smart contracts that Foundry provides as a default when you create a new Foundry project. diff --git a/courses/foundry/1-foundry-simple-storage/9-create-a-new-foundry-project-wsl/+page.md b/courses/foundry/1-foundry-simple-storage/9-create-a-new-foundry-project-wsl/+page.md new file mode 100644 index 000000000..8753fcd6c --- /dev/null +++ b/courses/foundry/1-foundry-simple-storage/9-create-a-new-foundry-project-wsl/+page.md @@ -0,0 +1,31 @@ +--- +title: WSL setup +--- + +_Follow along with the video_ + +--- + +### Introduction + +Hallo 👋🏻, I'm Vasily and I'll be your instructor for all Windows development. You'll see me frequently as I guide you through installing, running, and configuring various Windows tools. + +### WSL setup + +Microsoft has significantly improved its development environment support in recent years. However, for _smart contract development_, installing dependencies can sometimes be tricky. To streamline this process, we will use the **Windows Subsystem for Linux (WSL)**: this is a better option because it enables a full-fledged _unix-like console_ on your Windows machine, simplifying the use of tools and utilities commonly found in unix-based environments. This setup ensures compatibility with all the code that runs on unix-based systems like macOS and Linux. + +To install WSL, you can begin by opening the Windows terminal. On Windows 11, press the Windows key, type "terminal," and hit `enter`. On Windows 10, you need to install the Windows terminal from the Microsoft Store (select the official app from Microsoft Corporation). + +Once installed, open the terminal and type `wsl --install`. This command will initiate the installation process. Afterward, restart your computer. Upon reboot, the terminal will appear again, prompting you to select a Unix username and set a password. WSL will be then successfully installed ✅. + +### Visual Studio Code + +After installing WSL, we need to install a code editor. We will use Visual Studio Code (VS Code), and there are three different methods to install it: + +1. **Using the Terminal**: Utilize `winget`, a package manager pre-installed on Windows 11. Open the terminal and type `winget search VS Code` to find the desired package. Then, execute `winget install Microsoft.VisualStudioCode` to install VS Code. + +2. **Via Web Browser**: Search for "Visual Studio Code" in your web browser, select the official Microsoft link and download the installer. Follow the prompts, accept the user agreement and customize all the installation options. + +3. **Using VSCodium**: For those who prefer more independence and privacy, there is an open-source alternative called **VSCodium**. It is similar to VS Code but without Microsoft's telemetry. Download the [VSCodium installer](https://github.com/VSCodium/vscodium/releases) from GitHub and follow its similar installation steps. + +Choose the method that best suits your needs. For this course, I will use the official Visual Studio Code from Microsoft.