Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding al chapters for lesson 8 #11

Merged
merged 5 commits into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions config/sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,30 @@ export default {
},
],
},

{
title: "4. HTML Fund Me",
collapsible: true,
items: [
{
title: "1. Setup",
to: "/foundry/3-html-fund-me/1-setup/",
},
{
title: "2. How MetaMask works with the Browser",
to: "/foundry/3-html-fund-me/2-metamask/",
},
{
title: "3. Function Selectors Introduction",
to: "/foundry/3-html-fund-me/3-function-selectors/",
},
{
title: "4. Summary",
to: "/foundry/3-html-fund-me/4-summary/",
},
],
},

],
"/solidity": [],
};
55 changes: 55 additions & 0 deletions src/routes/foundry/3-html-fund-me/1-setup/+page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
---
title: Setup
---

_Follow along the course with this video._

<iframe width="560" height="315" src="https://www.youtube.com/embed/883HH60QqDY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

---

Hey there! Welcome to Lesson Eight. This session promises to be engaging and insightful as we dive deeper into the world of Development, focusing on MetaMask interactions with websites.

## Maintaining Transparency With Transactions

It is integral to understand how MetaMask, or any wallet for that matter, interacts with a website. Having this foundational knowledge equips you to ensure that your wallet sends the precise transaction you intend it to broadcast.

<img src="/html-fundme/1-setup/setup1.png" style="width: 100%; height: auto;">

## HTML FundMe F23: A Raw Javascript Full Website Application

Though we won't be delving into building a full-stack application in this lesson, you can find resources and examples for the same in the full blockchain solidity course on Javascript (JS) with Node JS.

We will, however, discuss HTML FundMe F 23 - a basic raw JavaScript full website application. If you feel crafty, go ahead and replicate it for practical grasp. The objective is to comprehend what happens under the hood when you interact with these websites.

## Diving In Without Prior Introduction

For a fresh change, we'll readily dive into the heart of the course without going through the customary walkthrough. You've been introduced to Git and GitHub in our previous courses, which will come in handy now.

Pull up your code base at Foundry F23, the repository with all our code. Copy the URL and begin working as if you've just downloaded it from GitHub, like this:

```bash
git clone git@github.com:username/repo.git
```

You'll find a 'Quick Start' section in all of my READMEs for your reference. Use it to clone the repository or open the file.

## Spinning Up The Website

The HTML FundMe repository has a very basic HTML and JavaScript structure to run a website. You can use an extension called Live Server to run the website. Alternatively, you should be able to open Reveal in Finder or use your file explorer to open it in your browser.

### Here's how it should look:

```bash
code html-fund-me-f23
```

The website runs on a minimalist architecture, which we're going to use to illustrate how MetaMask interacts with the website.

<img src="/html-fundme/1-setup/setup2.png" style="width: 100%; height: auto;">

## Wrapping Up

Having understood the fundamental of interactions between MetaMask and websites, you'd be more confident and aware of your transactions. Your coding journey grows with you. See you at the next lesson!

Keep coding and keep exploring!
74 changes: 74 additions & 0 deletions src/routes/foundry/3-html-fund-me/2-metamask/+page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
---
title: How MetaMask works with the Browser
---

_Follow along the course with this video._

<iframe width="560" height="315" src="https://www.youtube.com/embed/PL1H5tXwE3Q" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

---

In our web development journey, we often interact with JavaScript-enabled websites. But when it comes to dealing with MetaMask -- a cryptocurrency wallet and Ethereum gateway -- things become a little more intriguing. Let's uncover the puzzle and understand how MetaMask works with your website. Moreover, I will guide you on how to interact with such a website connected to a blockchain and a FundMe contract on the Anvil network.

## MetaMask &amp; Its Interaction with Websites

MetaMask is more than just a cryptocurrency wallet -- it acts as an interface that allows websites to interact with the Ethereum blockchain. Notably, these websites interact predominantly with the `window.ethereum` JavaScript object injected into the web browser by MetaMask. By utilizing this object, websites send transactions to MetaMask or any connected wallet.

However, keep in mind that if you switch to a browser without MetaMask installed, you won't be able to establish this connection. If you inspect the console and type `window.ethereum`, you'll encounter `undefined`. For detailed information about working with the `window.ethereum` object, refer to the MetaMask documentation [here](https://docs.metamask.io/guide/).

<img src="/html-fundme/2-metamask/metamask1.png" style="width: 100%; height: auto;">

## Establishing Connection with MetaMask

For your website to interact with MetaMask, you should have a mechanism to establish a connection. In order to do so, most websites feature a 'connect' button that on being clicked initiates the connection.

When you click the 'connect' button on your website, MetaMask will prompt you to connect one of your accounts. Once the connection is set up, your website will be able to fetch the account's balance and carry out transactions.

This JavaScript code shows the process to establish a connection via the 'connect' button. On clicking this button, the function checks if MetaMask is available on the browser. If found, it sends a request to MetaMask to connect one of the existing accounts.

## Interacting with Smart Contracts

Once the connection is established, we can interact with the functions of deployed smart contracts. For this demonstration, I will show you how to interact with a contract called `FoundryFundMe`. This contract has functions such as `fund`, `withdraw`, and `getBalance`. Here is an example of how to interact with the `getBalance` function:

Firstly, an Ethers provider gets the RPC URL from MetaMask. Secondly, it gets the signer using this provider. The signer, in context, is the connected account. Lastly, it creates a contract instance using the contract address, ABI, and signer.

```js
// JavaScript code to interact with the `getBalance` function
let provider = new ethers.providers.Web3Provider(window.ethereum);
let signer = provider.getSigner();
let contract = new ethers.Contract(contractAddress, ABI, signer);
// Retrieve the balance
let balance = await contract.getBalance();
```

## Switching to the Anvil Network

At some point, you may want to practice interacting with smart contracts on a local Anvil chain instead of the Ethereum Mainnet. Through MetaMask, you can easily shift from the Ethereum Mainnet to the Anvil network.

To do this, go to `Settings -> Networks -> Add Network`, and manually enter the following network details:

- Network Name: Anvil
- New RPC URL: \[RPC-URL-OF-ANVIL-NETWORK\]
- Chain ID: 31337
- Currency Symbol: Eth or whatever you prefer.
- Block Explorer URL: \[This field can be left blank\]

After the network is added, you can switch to Anvil chain in MetaMask and start interacting with the smart contracts deployed there.

## Interacting with the `FundMe` Contract

Once you've switched to the Anvil network, repeating the process as discussed in the previous section, you can deploy the `FundMe` contract and interact with it using MetaMask.

From the website, enter an amount in the `fund` section and click `fund`. This will create a transaction sent to MetaMask for you to sign.

```js
// JavaScript code to interact with the `fund` function
let ethAmount = document.getElementById("ethAmount").value;
let tx = await contract.fund({ value: ethers.utils.parseEther(ethAmount) });
```

Through this process, the website sends a transaction to MetaMask, and MetaMask returns a popup asking whether you want to sign this transaction with your private key.

## Recap and Takeaways

Working with MetaMask and JavaScript websites might seem daunting at first glance, but breaking it down to basics makes it accessible and transparent. MetaMask acts as a liaison connecting the JavaScript website to the Ethereum blockchain all the while prioritizing the security of your private keys. By comfortably setting up local Anvil chains and interfacing smart contracts via JavaScript functions, you can create an interactive, secure, and real-world-ready dApp.
63 changes: 63 additions & 0 deletions src/routes/foundry/3-html-fund-me/3-function-selectors/+page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
---
title: Function Selectors Introduction
---

_Follow along the course with this video._

<iframe width="560" height="315" src="https://www.youtube.com/embed/qZjLWy9b9hI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

---

## Decoding Transaction Data With Ethereum: A Step-by-Step Guide

Have you ever found yourself struggling with transaction data in Ethereum? Muddling through raw transaction data can be quite a challenge, especially if you aren't quite certain if the function you're calling is as it appears on the surface. Let's walk through how you can confirm what function is being called, decode Ethereum transactions, and call functions with parameters.

## The Fund Function

Picture this scenario: You have a system encoded with 'fund' and 'steal money' functions. You enter 0.1, hit _fund_, and find your MetaMask filled with data. At first glance, the data suggests it's calling the 'fund' function, but you'd like to precisely know.

Proving that the system is indeed calling the 'fund' function involves using function selectors. When solidity functions are transformed into function selectors, the human-readable 'fund' is converted into low-level bytecode or Ethereum Virtual Machine (EVM) code to stimulate Ethereum to grasp the function you're calling.

<img src="/html-fundme/3-function-selector/function1.png" style="width: 100%; height: auto;">

## Function Selectors and Checking Functions

Now, every function selector has its unique low-level hex encoding, and that's where the Cast command comes into play. Running 'cat SIG fund' in your system will return a 'fund' function selector. If you'd like to cross-verify this transaction's function, copy and paste the hex data alongside the expected selector in the console.

If they're the same, you can have assurance that it is actually calling the 'fund' function. But if you sense something fishy about the website and suspect it's pulling off some treacherous tactic like calling a malicious function like 'steal money', you can run 'Cast SIG steal money'. This will provide you with the 'steal money' function selector.

Copy the function selectors and verify them against the hex data on MetaMask. If they align, unfortunately, your website is calling the 'steal money' function- not the 'fund' function it should ideally be calling.

<img src="/html-fundme/3-function-selector/function2.png" style="width: 100%; height: auto;">

## Functions With Parameters

Now let's consider the scenario of functions with parameters. In such cases, your hex data is bigger, considering you'll have to accommodate data for calling the function. Cast calldata decode comes in handy in such scenarios.

Running _cast calldata decode_ alongside the call data on the system should reveal all the parameters on a function should they exist. This, however, isn't a perfect example since neither the 'fund' nor the 'steal money' function has any parameters. We'll delve into this a little later.

```
> Cast calldata decode > paste the call data
```

## Withdrawing Funds

Now, consider a different scenario where there's a function to withdraw funds. In this case, let's say this specific withdrawal feature is enabled to the account owner only.

Entering 0.1, hitting _fund_, and confirming the transaction sends the function via the API call. Once sent, calling _get balance_ should reveal that the balance has increased.

Heading to 'function withdraw', the system shows that it's an owner function. Making an attempt to withdraw from another (non-owner) account gets an RPC error since the function is limited to the owner.)However, getting back to the owner account gives a different story. Commanding withdraw and conferring the hex data to the earlier Cast SIG withdraw hex, the matching hexes gives the assurance to confirm the withdrawal. Once the mining is done, just as expected, the balance goes back to zero. So mission accomplished!

```
> Cast SIG withdraw> Withdraw function hex data: copied hex data
```

## Conclusion

In summary, understanding and verifying the transaction data we're handling in MetaMask ensures we're in control of our systems and comfortable in knowing no malicious functions are being called. So go out there and put this to good use, knowing exactly where your transactions are heading.

And remember,

<img src="/html-fundme/3-function-selector/function3.png" style="width: 100%; height: auto;">

We will delve into function parameters, calldata, and much more later. Get started, happy coding!
41 changes: 41 additions & 0 deletions src/routes/foundry/3-html-fund-me/4-summary/+page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
title: Summary
---

_Follow along the course with this video._

<iframe width="560" height="315" src="https://www.youtube.com/embed/EDaD5Ln1_u0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

---

Hello, there! Today, we had a quick lesson, but it was a vital one as it gives you the real feeling of interacting with websites from a very low level. For those excited about engaging themselves in more complex full-stack work, this post will hopefully whet your appetite.

#### Initiating a Transaction - Making a Connection

A website sends a transaction to your wallet by establishing attachment to the wallet in one way or another. Browser extension injection into your browser is one of the most prevalent methods in use today.

```javascript
window.Ethereum;
```

This line of code signals the browser to confirm the presence of the metamask object, an essential step for browsers interacting with wallets such as `wallet connect`, `ledger`, among other types.

While on the surface all wallets seem different, they all perform the fundamental function of consolidating a connection object with the website, thus enabling the website to transmit transactions to your browser. The process involves hitting "connect" on the website and the wallet confirming the establishment of a successful connection.

<img src="/html-fundme/4-summary/summary1.png" style="width: 100%; height: auto;">

#### Send a Transaction, Keep the Private Key

When it comes to sending a transaction to our wallets, the website first extracts the provider or the RPC URL from MetaMask.

<img src="/html-fundme/4-summary/summary2.png" style="width: 100%; height: auto;">

Through the function signature or function selector, our system helps us verify that the transactions from the website are not counterfeit. Later in our course, we will delve deeper into decoding complex transactions and functions.

<img src="/html-fundme/4-summary/summary3.png" style="width: 100%; height: auto;">

#### Conclusion

That tips off our lesson for today. It was short but dense with necessary knowledge, especially for learners who are passionate about smart contracts. Understanding web interactions and the intricate operations of websites aids in conducting intelligent work and being on the lookout for potential threats.

This was a basic introduction to web interactions, and as we continue digging deeper into topics, such as function selectors and signatures, expect to become more proficient in navigating websites. Now would be a perfect time to digest all that we've discussed. Stay tuned for the next lesson. Catch you later!
Binary file added static/html-fundme/1-setup/setup1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/html-fundme/1-setup/setup2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/html-fundme/2-metamask/metamask1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/html-fundme/4-summary/summary1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/html-fundme/4-summary/summary2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/html-fundme/4-summary/summary3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.