# About Ankita

Hi, I'm Ankita!

I'm a passionate Blockchain Engineer with a strong foundation in both Web2 and Web3 development. Since starting my journey in 2016 as an intern, I've continuously expanded my skillset to tackle complex projects and deliver innovative solutions.

I'm  a dedicated and innovative blockchain engineer with over eight years of experience in software development. My journey in technology began as an intern in 2016, and since then, I've continually expanded my skill set, embracing the dynamic worlds of Web2 and Web3 development.

### Expertise and Skills

I specialize in blockchain technologies, with a strong proficiency in Solidity, Ethereum, and various blockchain standards such as ERC-20, ERC-721, and ERC-1155. My technical toolkit includes:

* **Blockchain Technologies:** Ethereum, Solidity, Polygon, foundry
* **Frontend Development**: JavaScript, React, Next.js
* **UI Libraries & Frameworks:** Tailwind, shadcn/ui, Magic UI, Prochakra
* **Backend Development**: Node.js, MongoDB, postgresql, express, MySQL
* **Web3 Integration:** NFTs, DAOs, Vercel, AWS, server-side rendering
* **Protocols:** ERC-4337, ERC-6551, ERC-20, ERC-721, ERC-1155, EIP-1559
* **Concepts:** Blockchain fundamentals, Ethereum, DeFi, dApps, Web3 wallets
* **APIs & Automation:** Working with APIs and building Telegram bots
* **Web3 and dApps**: Wallet integrations, NFT marketplaces, DeFi protocols,Messaging/Caching
* **Technical Frameworks**: Vercel, AWS, server-side architectures
* **Gaming and Bots**: Basic understanding of game development and Web3 bot integration

### **Experience:**

**Freelance Blockchain Engineer**

**(Present)**\
Collaborated with Web3 companies, delivering blockchain-based products that integrate smart contracts, decentralized apps (DApps), NFTs, and wallet systems. Focused on interoperability, security, and user experience.\
**Highlights:**

* Worked with 2-3 Web3 startups on blockchain solutions and ecosystem integrations.
* Built NFT marketplaces, DAO platforms, and custom Web3 dashboards.
* Contributed to Solidity smart contracts and React-based DApps.

***

**Senior Web & Blockchain Developer — Tan Theta Software Studio**

**(June 2022 – Present )**\
Started as a **Junior Developer** and grew into a **Senior Developer** role, bridging the gap between Web2 and Web3 technologies.\
**Key Contributions:**

* Delivered **50+ Web2 projects** using JavaScript, Next.js, and Tailwind CSS.
* Actively contributed to **20+ Blockchain projects**, focusing on ERC-20, ERC-721, and ERC-1155 token standards.
* Developed NFT marketplaces, DAO platforms, and wallet DApps.
* Explored **React Native** for blockchain-based mobile app development.
* Continuously learned and implemented **emerging protocols** like ERC-6551 and advanced Solidity patterns.

***

**Full Stack Web Developer — Technomads Solutions Pvt. Ltd.**

**(May 2018 – June 2022 )**\
Started as an **Intern** and advanced through **Junior** and **Senior Developer** roles, eventually managing project teams.\
**Journey Overview:**

* **Intern (2018):** Learned JavaScript, Node.js, and React through real-world projects.
* **Junior Developer (2018–2020):** Built responsive web apps using JS, Tailwind, and Next.js; collaborated closely with designers.
* **Senior Developer (2020–2022):** Led teams, managed project timelines, and introduced modern frameworks into the workflow.
* Began exploring **Web3 fundamentals** — Ethereum, smart contracts, DeFi, NFTs, and IPFS — to align company projects with blockchain innovation.
* Managed and mentored **teams of 20+ developers**, ensuring smooth delivery and code quality.

Beyond the code:

I believe in continuous learning and staying updated with the latest advancements in the blockchain and software development landscape. My journey has involved facing challenges, overcoming roadblocks, and refining my communication and team leadership skills. I'm always eager to take on new projects and contribute to the ever-evolving world of Web3.

#### Continuous Growth and Learning

Throughout my career, I've embraced challenges and failures as opportunities to learn and grow. These experiences have strengthened my project management skills, enhanced my technical expertise, and inspired a culture of continuous innovation and excellence in all my endeavors.

#### Vision

I’m dedicated to advancing Web3 through secure, scalable solutions in DeFi, NFTs, and DApps. By leveraging my expertise in cryptography, full-stack development, and Telegram Bots, I aim to drive decentralization and prepare blockchain for the post-quantum era. I thrive in remote work environments and am open to global opportunities to innovate and collaborate.

What's next?

Explore my portfolio to delve deeper into the technical aspects of my projects and gain insights into my approach to problem-solving. Feel free to reach out if you have any questions or exciting opportunities you'd like to discuss!


# TECHNOLOGIES

Throughout my career, I have developed a comprehensive skill set across a wide range of technologies. My expertise spans from frontend development to backend infrastructure, databases, blockchain, and more. Below are the categories that represent the key areas of my technological proficiency, detailing the tools, languages, frameworks, and platforms I have mastered.

***

**List of technologies:**

* [**Frontend**](/experience/frontend)
  * React, Angular, Vue.js, Next.js, HTML, CSS, Tailwind CSS
* [**Backend**](/experience/backend)
  * Node.js, Express, Python (Django, Flask), Ruby on Rails, Java (Spring Boot)
* [**Databases**](/experience/database)
  * MySQL, PostgreSQL, MongoDB, SQLite, Firebase Realtime Database
* [**Package Managers**](/experience/packege-mangers)
  * npm, Yarn, pnpm, Bun
* [**API Providers**](/experience/api-providers)
  * Alchemy, Telegram Bot API, CoinMarketCap API, Thirdweb, Infura, Moralis
* [**DevOps**](/experience/devops-infrastructure)
  * Docker, Kubernetes, AWS, Azure, CI/CD Pipelines, GitHub Actions
* [**Protocols**](/experience/protocols)
  * HTTP, TCP/IP, WebSockets, gRPC, ERC & EIPs
* [**Web3 Toolkits**](/experience/web3-toolkits)
  * Web3.js, Ethers.js, Truffle, Ganache, Foundry, Hardhat, Remix IDE
* [**Messaging / Caching**](/experience/messaging-caching)
  * Apache Kafka, Redis, SendGrid
* [**Blockchain**](/experience/blockchain)
  * Ethereum, Bitcoin, Solana, Polygon, Zero-Knowledge Proofs, Solidity
* [**Deployment Platforms**](/experience/deployment-platforms/domain-setup)
  * AWS, Vercel, Heroku, Render, Netlify
* [**SDKs**](/sdks)
  * Google Cloud SDK, AWS SDK, Firebase SDK


# Frontend

## Frontend Expertise

Begin with a brief overview of your frontend development skills and experience.&#x20;

> Experienced frontend developer with 7+ years of expertise in creating responsive, user-friendly web applications using modern JavaScript frameworks and libraries. Proficient in React, Next.js, and Vue.js, with a strong foundation in HTML5, CSS3, tailwindcss, UI Libraries and JavaScript (ES6+).

## Technical Skills

* **Languages:** JavaScript (ES6+), HTML5, CSS3, TypeScript
* **Frameworks/Libraries:** React, Next.js, Vue.js, Angular
* **State Management:** Redux
* **UI Libraries:** Material-UI, Tailwind CSS, Bootstrap, shadncn, Chakra UI ...
* **Build Tools:** Webpack, Vite
* **Version Control:** Git, GitHub, GitLab
* **Testing:**  React Testing Library, Cypress


# Javascript

JavaScript is a versatile, high-level programming language essential for creating dynamic and interactive web applications. Its capabilities span from front-end to back-end development, making it a cornerstone of modern web technology.

## 📚 JavaScript Skills Overview

This guide provides an overview of key JavaScript concepts and advanced topics, showcasing various coding examples and best practices.🚀

### 🏗️ JavaScript Architecture

JavaScript operates on a single-threaded, event-driven architecture, which allows for efficient handling of asynchronous operations.Here's a high-level overview:

<figure><img src="/files/kWgoMxsbnF1180hJOd9h" alt=""><figcaption></figcaption></figure>

This architecture allows JavaScript to handle asynchronous operations efficiently.

### 🔠 Static vs Dynamic Typing in JavaScript

JavaScript is a dynamically typed language, meaning variable types are determined at runtime. This flexibility can lead to runtime errors, but also enables more fluid coding. In contrast, statically typed languages like TypeScript require variable types to be declared at compile time, offering earlier error detection.

Here's an example illustrating dynamic typing in JavaScript:

```jsx
let variable = 42;  // variable is a number
console.log(typeof variable);  // "number"

variable = "Hello, World!";  // Now variable is a string
console.log(typeof variable);  // "string"

variable = true;  // Now variable is a boolean
console.log(typeof variable);  // "boolean"
```

### 🧠 Core JavaScript Concepts

#### 1. Variables and Data Types

JavaScript includes primitive types (like `string`, `number`, and `boolean`) and object types (like `objects`, `arrays`, and `functions`).

{% code overflow="wrap" %}

```jsx
// Primitive types
let string = "Hello, World!";
let number = 42;
let boolean = true;
let nullValue = null;
let undefinedValue;
let symbol = Symbol("unique");

// Object types
let object = { key: "value" };
let array = [1, 2, 3];
let function = () => console.log("I'm a function!");

console.log(typeof string);  // "string"
console.log(typeof number);  // "number"
console.log(typeof boolean); // "boolean"
console.log(typeof nullValue); // "object" (this is a known quirk)
console.log(typeof undefinedValue); // "undefined"
console.log(typeof symbol);  // "symbol"
console.log(typeof object);  // "object"
console.log(typeof array);   // "object"
console.log(typeof function); // "function"
```

{% endcode %}

#### 2. Functions and Scope

Functions are central in JavaScript, allowing for modular code. They can be declared using various syntaxes: traditional functions, function expressions, or arrow functions.

{% code overflow="wrap" %}

```jsx
// Function declaration
function greet(name) {
    return `Hello, ${name}!`;
}

// Function expression
const farewell = function(name) {
    return `Goodbye, ${name}!`;
};

// Arrow function
const introduce = (name, age) => `I'm ${name} and I'm ${age} years old.`;

console.log(greet("Alice"));  // "Hello, Alice!"
console.log(farewell("Bob")); // "Goodbye, Bob!"
console.log(introduce("Charlie", 30)); // "I'm Charlie and I'm 30 years old."

// Demonstrating scope
//Scope in JavaScript can be global or local. Variables declared inside functions are local, while those outside are global.
let globalVar = "I'm global";

function demonstrateScope() {
    let localVar = "I'm local";
    console.log(globalVar);  // "I'm global"
    console.log(localVar);   // "I'm local"
}

demonstrateScope();
console.log(globalVar);  // "I'm global"
// console.log(localVar);   // ReferenceError: localVar is not defined
```

{% endcode %}

#### 3. Object-Oriented Programming in JavaScript **(OOP)**

JavaScript supports OOP through prototype-based inheritance and class syntax.

```jsx
// Constructor function (pre-ES6)
function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.greet = function() {
    console.log(`Hello, I'm ${this.name}`);
};

// Class syntax (ES6+)
class Animal {
    constructor(species) {
        this.species = species;
    }

    makeSound() {
        console.log("Some generic animal sound");
    }
}

class Dog extends Animal {
    constructor(name) {
        super("Canine");
        this.name = name;
    }

    makeSound() {
        console.log("Woof!");
    }
}

const person = new Person("Alice", 30);
person.greet();  // "Hello, I'm Alice"

const dog = new Dog("Buddy");
console.log(dog.species);  // "Canine"
dog.makeSound();  // "Woof!"
```

### 🌟 Real-Time Example: Building a Todo List

Let's create a simple todo list application to demonstrate various JavaScript concepts:

```jsx
class TodoList {
    constructor() {
        this.todos = [];
    }

    addTodo(task) {
        this.todos.push({ task, completed: false });
    }

    toggleTodo(index) {
        this.todos[index].completed = !this.todos[index].completed;
    }

    removeTodo(index) {
        this.todos.splice(index, 1);
    }

    render() {
        const todoList = document.getElementById('todo-list');
        todoList.innerHTML = '';
        this.todos.forEach((todo, index) => {
            const li = document.createElement('li');
            li.textContent = todo.task;
            if (todo.completed) {
                li.style.textDecoration = 'line-through';
            }
            li.addEventListener('click', () => {
                this.toggleTodo(index);
                this.render();
            });
            const removeButton = document.createElement('button');
            removeButton.textContent = 'Remove';
            removeButton.addEventListener('click', (e) => {
                e.stopPropagation();
                this.removeTodo(index);
                this.render();
            });
            li.appendChild(removeButton);
            todoList.appendChild(li);
        });
    }
}

const todoList = new TodoList();

document.getElementById('add-todo').addEventListener('click', () => {
    const input = document.getElementById('todo-input');
    if (input.value) {
        todoList.addTodo(input.value);
        input.value = '';
        todoList.render();
    }
});

todoList.render();
```

### 🔍 Difference between `var`, `let`, and `const`

Understanding variable declaration is crucial in JavaScript:

1. **`var`** is function-scoped and can be redeclared and updated. Its hoisting behavior can cause unexpected results.
2. **`let`** is block-scoped and allows for reassigning but not redeclaration.
3. **`const`** is also block-scoped but cannot be reassigned or redeclared.

Here's an example illustrating the differences:

```jsx
// var
var x = 1;
if (true) {
    var x = 2;  // Same variable!
    console.log(x);  // 2
}
console.log(x);  // 2

// let
let y = 1;
if (true) {
    let y = 2;  // Different variable
    console.log(y);  // 2
}
console.log(y);  // 1

// const
const z = 1;
// z = 2;  // Error: Assignment to a constant variable
console.log(z);  // 1
```

#### Why var is not recommended:

* Lack of block scoping can lead to unexpected behavior and bugs
* Hoisting can cause confusion and make code harder to reason about
* Allows for redeclaration, which can lead to accidental overwrites

Using let and const provides better control over variable scope and mutability, leading to cleaner and more predictable code. It's generally recommended to use const by default, and let when you need to reassign a variable. var should be avoided in modern JavaScript development unless you have a specific reason to use it.

### 🚀 ES6+ Features and Modern JavaScript Concepts

JavaScript has evolved significantly since the introduction of ECMAScript 2015 (ES6). Let's explore some core concepts and features of modern JavaScript:

#### 1. 🏹 Arrow Functions

Arrow functions provide a concise syntax for writing function expressions:

```jsx
// Traditional function
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => a + b;

// Arrow function with implicit return
const square = x => x * x;
```

#### 2. 🎭 Destructuring

Destructuring allows you to unpack values from arrays or properties from objects into distinct variables, making it easier to work with complex data structures.

```jsx
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first, second, rest); // 1 2 [3, 4, 5]

// Object destructuring
const { name, age } = { name: 'Alice', age: 30, country: 'USA' };
console.log(name, age); // Alice 30
```

#### 3. 📦 Spread and Rest Operators

The spread operator (...) can be used to expand elements, while the rest operator can collect multiple elements into an array:

```jsx
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]

// Rest operator
function sum(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
```

#### 4. 🏷️ Template Literals

Template literals allow for easy string interpolation and multiline strings:

```jsx
const name = 'Alice';
const greeting = `Hello, ${name}!
Welcome to ES6+.`;
console.log(greeting);
// Hello, Alice!
// Welcome to ES6+.
```

#### 5. 🔄 Asynchronous Programming

Modern JavaScript provides several ways to handle asynchronous operations:

#### 5.1 Promises

```jsx
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data fetched successfully');
    }, 2000);
  });
}

fetchData()
  .then(data => console.log(data))
  .catch(error => console.error(error));
```

#### 5.2 Async/Await

```jsx
async function getData() {
  try {
    const result = await fetchData();
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

getData();
```

**Callbacks**

Callbacks are functions passed as arguments to other functions, executed after a certain task is completed. They are the foundation of asynchronous programming in JavaScript but can lead to complex code structures known as "callback hell."

```javascript
function fetchData(callback) {
    setTimeout(() => {
        callback("Data fetched");
    }, 1000);
}

fetchData((data) => {
    console.log(data); // Output: Data fetched
});
```

Here's a visual representation of asynchronous operations:

<figure><img src="/files/L4KgPiLyrTbfhnF7uV7U" alt=""><figcaption></figcaption></figure>

#### 6. 🏛️ Object-Oriented Programming

JavaScript supports object-oriented programming through prototypes and classes, enabling you to create reusable and scalable code structures.

**Prototypes**

Prototypes allow JavaScript to implement inheritance, enabling objects to share properties and methods. This model provides a way to extend objects and create shared behavior across instances.

```javascript
function Person(name) {
    this.name = name;
}

Person.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
};

const person1 = new Person("Alice");
person1.greet(); // Output: Hello, my name is Alice
```

**Classes**

Classes offer a more structured and intuitive syntax for defining objects and their behaviors. They simplify the creation of complex applications by organizing code into modular, reusable components.

```jsx
class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Rex');
dog.speak(); // Rex barks.
```

#### 7. 🌳 DOM Manipulation

JavaScript allows you to manipulate the Document Object Model (DOM) to create interactive web pages. This capability is fundamental for updating and managing the content and structure of web pages dynamically.

```jsx
// Creating elements
const div = document.createElement('div');
div.textContent = 'Hello, World!';
document.body.appendChild(div);

// Querying elements
const button = document.querySelector('#myButton');
button.addEventListener('click', () => {
  console.log('Button clicked!');
});

// Modifying styles
const element = document.getElementById('myElement');
element.style.backgroundColor = 'blue';
element.classList.add('highlight');
```

<figure><img src="/files/H78Id9wkpIHmQlEvf8nS" alt=""><figcaption></figcaption></figure>

#### 8. 🐛 Error Handling and Debugging

JavaScript development involves dealing with errors and debugging to ensure code reliability and functionality.

#### Understanding Errors and Exceptions

JavaScript uses error objects to represent exceptional circumstances in your code. These can be created using the `Error` constructor or its subclasses like `TypeError`, `ReferenceError`, or `SyntaxError`.

```javascript
throw new Error("This is a custom error message.");
```

#### Try, Catch, and Finally Blocks

Use `try`, `catch`, and `finally` blocks to handle exceptions and ensure code executes correctly even when errors occur.

```javascript
try {
  // Code that might throw an exception
} catch (error) {
  // Code to handle the exception
} finally {
  // Code to be executed regardless of whether an exception was thrown
}
```

#### Custom Error Handling

Create custom error types for more specific error handling by extending the built-in `Error` class.

```javascript
class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  }
}

try {
  throw new CustomError("This is a custom error.");
} catch (error) {
  if (error instanceof CustomError) {
    console.error("Caught a CustomError:", error.message);
  } else {
    console.error("Caught an unknown error:", error.message);
  }
}
```

These modern JavaScript features and concepts provide powerful tools for building efficient, readable, and maintainable code. As you continue to explore and practice, you'll find even more ways to leverage these capabilities in your projects. 🚀👨‍💻

### 🐞 Debugging Techniques for JavaScript

Here are some powerful debugging techniques to help you troubleshoot your JavaScript code, along with code snippets:

* 🖨️ **Console Logging:** Use `console.log()`, `console.warn()`, and `console.error()` to output values and messages.

```jsx
// Basic console logging
console.log('Debug value:', someVariable);

// Styled console logging
console.log('%cDebug', 'color: blue; font-weight: bold;', 'Value:', someVariable);

// Warning and Error logging
console.warn('Warning: Something might be wrong');
console.error('Error: Something went wrong');
```

* 🔍 **Debugger Statement:** Insert `debugger;` in your code to pause execution and inspect variables.

```jsx
function troublesomeFunction() {
  let x = 5;
  debugger; // Execution will pause here
  x = x * 2;
  return x;
}
```

* 🔬 **Browser DevTools:** Utilize breakpoints, watch expressions, and the console in your browser's developer tools.
* 🔄 **Try-Catch Blocks:** Wrap potentially problematic code in try-catch blocks to handle and log errors gracefully.

```jsx
try {
  // Potentially problematic code
  let result = riskyFunction();
  console.log('Result:', result);
} catch (error) {
  console.error('An error occurred:', error.message);
}
```

* 📊 **Performance Profiling:** Use `console.time()` and `console.timeEnd()` to measure code execution time.

```jsx
console.time('Loop time');
for(let i = 0; i < 1000000; i++) {
  // Some operation
}
console.timeEnd('Loop time');
```

* 🔢 **Stack Trace Analysis:** Examine the call stack to understand the sequence of function calls leading to an error.

```jsx
function firstFunction() {
  secondFunction();
}

function secondFunction() {
  thirdFunction();
}

function thirdFunction() {
  console.trace('Trace at thirdFunction');
  throw new Error('An error occurred');
}

try {
  firstFunction();
} catch (error) {
  console.error('Error Stack:', error.stack);
}
```

* 🧪 **Unit Testing:** Implement unit tests using frameworks like Jest or Mocha to catch bugs early.

```jsx
// Using Jest
test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

function sum(a, b) {
  return a + b;
}
```

* 🔄 **Source Maps:** Use source maps to debug minified or transpiled code in its original form.
* 🧹 **Use Linters and Formatters:** Integrate tools like ESLint and Prettier to maintain consistent code style and catch potential issues early.

```json
// .eslintrc.json
{
  "extends": ["eslint:recommended", "plugin:prettier/recommended"],
  "rules": {
    "no-console": "warn",
    "semi": ["error", "always"],
    "quotes": ["error", "single"]
  },
  "env": {
    "browser": true,
    "node": true
  }
}
```

Using linters and formatters can significantly improve code quality and consistency across your project. They help catch common errors and enforce a uniform coding style, making your codebase more maintainable and easier to read.

***


# React

## 📚 Introduction to React JS

React JS is a powerful JavaScript library for building user interfaces, particularly single-page applications. It's known for its efficiency, flexibility, and component-based architecture. This document will explore advanced React concepts, architectural patterns, and real-world applications.

#### Why React?

* **Component-Based Architecture:** Encourages code reusability and maintainability.
* **Virtual DOM:** Improves performance by minimizing DOM manipulations.
* **Declarative Style:** Focuses on describing the desired UI state rather than imperative updates.
* **Large and Active Community:** Extensive support, libraries, and tools available.
* **JSX:** Makes code more readable and intuitive.

#### Important Features

* **React Hooks:** Allow you to use state and other React features without writing classes.
* **Context API:** Provides a way to share data across components without prop drilling.
* **React Router:** For handling navigation in single-page applications.
* **Redux:** Popular state management library for complex applications.
* **Server-Side Rendering (SSR):** Improves SEO and initial page load performance.

#### Creating a React Page

Bash

```
npx create-react-app my-app
cd my-app
npm start
```

This will create a new React project, install dependencies, and start a development server.

**Note:** This is a basic overview. React offers many more features and concepts.

**Would you like to delve deeper into a specific area of React, such as React Hooks, Redux, or building a particular type of application?**

### 🏗️ React Architecture

React follows a component-based architecture, which allows for reusable UI elements. Let's visualize this with a diagram:

<figure><img src="/files/O810aq4FUukgMmRPNbIC" alt=""><figcaption></figcaption></figure>

This diagram represents a typical e-commerce application structure in React. Each box represents a component, and the arrows show the hierarchy and relationships between components.

### 🔧 Core React Concepts

#### 1. JSX (JavaScript XML)

JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. Here's an example:

```jsx
const element = <h1>Hello, {name}</h1>;


import React from 'react';

function Welcome() {
    return <h1>Welcome to React!</h1>;
}

export default Welcome;
```

#### 2. Components and Props

**Functional Components**

Functional components are simpler and easier to understand. They are defined as JavaScript functions and receive props as arguments.

```javascript
// FunctionalComponent.js
import React from 'react';

function FunctionalComponent(props) {
    return <h1>Hello, {props.name}!</h1>;
}

export default FunctionalComponent;
```

**Class Components**

Class components offer more features and are used for components that require state or lifecycle methods. They are defined using ES6 classes.

```javascript
// ClassComponent.js
import React, { Component } from 'react';

class ClassComponent extends Component {
    render() {
        return <h1>Hello, {this.props.name}!</h1>;
    }
}

export default ClassComponent;
```

Components are the building blocks of React applications. They can be functional or class-based. Props are used to pass data between components.

```jsx
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
```

#### 3. State and Lifecycle

State is used to store component-specific data that can change over time. The lifecycle methods allow you to run code at specific points in a component's life.

```jsx
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
```

#### 4. Hooks

Hooks allow functional components to use state and other React features. The most common hooks are useState and useEffect.

```jsx
import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
```

### 🔄 React Component Lifecycle

Understanding the React component lifecycle is crucial for optimizing performance and managing side effects. Here's a diagram illustrating the lifecycle of a class component:

<figure><img src="/files/YdMdBgStOIiIdzyo7J0D" alt=""><figcaption></figcaption></figure>

For functional components, we use hooks to manage lifecycle-like behavior. The most common hooks are useState, useEffect, and useContext.

### 📊 Detailed Component Lifecycle

#### 1. Mounting Phase

The mounting phase occurs when a component is being added to the DOM. It involves the following methods:

* **constructor(props)**: Initializes state and binds methods.
* **render()**: Returns JSX to be rendered.
* **componentDidMount()**: Runs after the component is mounted to the DOM.

```jsx
class MountingComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: null };
  }

  componentDidMount() {
    fetchData().then(data => this.setState({ data }));
  }

  render() {
    return <div>{this.state.data ? 'Data loaded' : 'Loading...'}</div>;
  }
}
```

#### 2. Updating Phase

The updating phase occurs when a component's state or props change. It involves these methods:

* **shouldComponentUpdate(nextProps, nextState)**: Decides if the component should re-render.
* **render()**: Re-renders the component with updated data.
* **componentDidUpdate(prevProps, prevState)**: Runs after the component updates.

```jsx
class UpdatingComponent extends React.Component {
  shouldComponentUpdate(nextProps) {
    return this.props.value !== nextProps.value;
  }

  componentDidUpdate(prevProps) {
    if (this.props.value !== prevProps.value) {
      console.log('Value changed');
    }
  }

  render() {
    return <div>{this.props.value}</div>;
  }
}
```

#### 3. Unmounting Phase

The unmounting phase occurs when a component is being removed from the DOM. It involves one method:

* **componentWillUnmount()**: Runs just before the component is unmounted and destroyed.

```jsx
class UnmountingComponent extends React.Component {
  componentWillUnmount() {
    console.log('Component is about to be unmounted');
    // Clean up any subscriptions or timers here
  }

  render() {
    return <div>I'm still here!</div>;
  }
}
```

#### 4. Error Handling Phase

This phase is invoked when there's an error during rendering, in a lifecycle method, or in the constructor of any child component.

* **static getDerivedStateFromError(error)**: Used to render a fallback UI after an error has been thrown.
* **componentDidCatch(error, info)**: Used to log error information.

```jsx
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
```

### 📊 Lifecycle Diagram

Here's an architecture diagram with a landscape view representing the React component lifecycle:

<figure><img src="/files/rONTfwkpppWkD5Afm07k" alt=""><figcaption></figcaption></figure>

This architecture diagram presents a landscape view of the React component lifecycle, showcasing the relationships between different layers:

* User Interface Layer: Where user interactions originate
* React Component Layer: Contains the component instance and its props and state
* Lifecycle Methods Layer: Includes mounting, updating, and unmounting methods
* Rendering Layer: Shows the process from Virtual DOM to Actual DOM

The diagram illustrates how user interactions trigger changes in the React component, which then flow through the lifecycle methods and rendering process, ultimately updating the user interface.

### 🔀 State Management

For complex applications, state management becomes crucial. While React's built-in state management is sufficient for many cases, larger applications often benefit from additional libraries like Redux or MobX.

#### Redux Architecture

<figure><img src="/files/xXIPPOWff4MOnz1kS2vw" alt=""><figcaption></figcaption></figure>

This diagram illustrates the unidirectional data flow in Redux, a popular state management library for React applications.

### 🌐 React Router for Navigation

React Router is the standard routing library for React. It keeps your UI in sync with the URL, allowing you to create a single-page application with navigation without the page refreshing.

```jsx
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/users">Users</Link></li>
          </ul>
        </nav>

        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
        <Route path="/users" component={Users} />
      </div>
    </Router>
  );
}
```

### 🔍 Advanced React Patterns

#### 1. Render Props

The render prop pattern allows you to share code between components using a prop whose value is a function.

```jsx
class Mouse extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>
        {this.props.render(this.state)}
      </div>
    );
  }
}

// Usage
<Mouse render={({ x, y }) => (
  <h1>The mouse position is ({x}, {y})</h1>
)}/>
```

#### 2. Higher-Order Components (HOCs)

HOCs are functions that take a component and return a new component with additional props or behavior.

```jsx
function withLogger(WrappedComponent) {
  return class extends React.Component {
    componentDidMount() {
      console.log('Component is mounted');
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }
}

// Usage
const EnhancedComponent = withLogger(MyComponent);
```

### 🚀 Performance Optimization

React provides several ways to optimize the performance of your applications:

#### 1. React.memo

React.memo is a higher-order component that can be used to wrap functional components to prevent unnecessary re-renders.

```jsx
const MyComponent = React.memo(function MyComponent(props) {
  /* render using props */
});
```

#### 2. useMemo and useCallback

These hooks are used to memoize values and functions respectively, preventing unnecessary recalculations or re-creations.

```jsx
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);
```

### 🌟 Real-World Example: Building a Todo App

Let's create a simple todo app to demonstrate these concepts in action.

```jsx
import React, { useState, useCallback, useMemo } from 'react';

function TodoApp() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');

  const addTodo = useCallback(() => {
    if (input) {
      setTodos(prevTodos => [...prevTodos, { id: Date.now(), text: input, completed: false }]);
      setInput('');
    }
  }, [input]);

  const toggleTodo = useCallback((id) => {
    setTodos(prevTodos =>
      prevTodos.map(todo =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  }, []);

  const completedCount = useMemo(() => {
    return todos.filter(todo => todo.completed).length;
  }, [todos]);

  return (
    <div>
      <h1>Todo App</h1>
      <input
        value={input}
        onChange={(e) => setInput(e.target.value)}
        placeholder="Add a todo"
      />
      <button onClick={addTodo}>Add</button>
      <ul>
        {todos.map(todo => (
          <li
            key={todo.id}
            onClick={() => toggleTodo(todo.id)}
            style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
          >
            {todo.text}
          </li>
        ))}
      </ul>
      <p>Completed todos: {completedCount}</p>
    </div>
  );
}

export default TodoApp;
```

This example demonstrates the use of various React hooks (useState, useCallback, useMemo) and showcases how to manage state, handle user input, and optimize performance in a real-world scenario.

### 🚀 Why React Was Introduced

React was introduced by Facebook in 2013 to address several challenges in building large-scale web applications:

* **Efficient DOM manipulation:** React's virtual DOM optimizes updates, reducing expensive direct DOM manipulations.
* **Component-based architecture:** React promotes reusable, modular code through its component system.
* **Unidirectional data flow:** React's one-way data binding simplifies debugging and improves application predictability.
* **Performance:** React's efficient update mechanism allows for building high-performance user interfaces.
* **Developer experience:** React's declarative syntax and powerful ecosystem enhance developer productivity.

These features have made React a popular choice for building modern web applications, addressing pain points in traditional web development approaches.

###

***

Feel free to adjust this content based on your specific experience and projects with React.js!


# NextJS

## Next.js: A Comprehensive Guide 🚀

### Introduction to Next.js 📚

Next.js is a powerful React framework that enables you to build server-side rendered and statically generated web applications. It was introduced by Vercel (formerly Zeit) in 2016 to address common challenges in React development and to provide a more opinionated, yet flexible, structure for building modern web applications.

#### Why Next.js? 🤔

Next.js offers several advantages over traditional React applications:

* Server-Side Rendering (SSR) for improved performance and SEO
* Static Site Generation (SSG) for blazing-fast static websites
* Automatic code splitting for faster page loads
* Built-in CSS support
* API routes for building backend functionality
* Easy deployment and scalability

#### Next.js vs Other Frameworks 🥊

Compared to other frameworks, Next.js stands out in several ways:

| Feature                  | Next.js | Create React App | Gatsby |
| ------------------------ | ------- | ---------------- | ------ |
| Server-Side Rendering    | ✅       | ❌                | ❌      |
| Static Site Generation   | ✅       | ❌                | ✅      |
| API Routes               | ✅       | ❌                | ❌      |
| Automatic Code Splitting | ✅       | ✅                | ✅      |
| Zero Configuration       | ✅       | ✅                | ❌      |

### Next.js Architecture 🏗️

Next.js follows a hybrid architecture that combines server-side rendering, static site generation, and client-side rendering. Here's a high-level overview:

<figure><img src="/files/SoqpOJkuhLfZRnPweimz" alt=""><figcaption></figcaption></figure>

### Example Project Structure

Here is an example structure for a Next.js project with TypeScript:

```
my-next-app/
│
├── public/
│   └── image.jpg
│
├── pages/
│   ├── api/
│   │   └── hello.ts
│   ├── about.tsx
│   ├── index.tsx
│   └── posts/
│       └── [id].tsx
│
├── styles/
│   └── globals.css
│
├── tsconfig.json
└── package.json
```

### User Flow in a Next.js Application 🔄

Here's a typical user flow in a Next.js application:

<figure><img src="/files/bMCuAI4ZcAJR8vQeSatD" alt=""><figcaption></figcaption></figure>

### Core Next.js Concepts and Code Snippets 💻

#### 1. Pages and Routing

Next.js uses a file-system based routing. Each file inside the `pages` directory becomes a route.

```jsx
// pages/index.js
export default function Home() {
  return <h1>Welcome to Next.js!</h1>
}

// pages/about.js
export default function About() {
  return <h1>About Us</h1>
}
```

#### 2. Dynamic Routes

You can create dynamic routes using brackets `[]` in the filename.

```jsx
// pages/posts/[id].js
import { useRouter } from 'next/router'

export default function Post() {
  const router = useRouter()
  const { id } = router.query

  return <p>Post: {id}</p>
}
```

#### 3. API Routes

API routes allow you to build your API endpoints as Node.js serverless functions.

```jsx
// pages/api/hello.js
export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' })
}
```

#### 4. Data Fetching

Next.js provides several methods for data fetching:

#### getStaticProps (Static Generation)

```jsx
export async function getStaticProps() {
  const res = await fetch('<https://api.example.com/data>')
  const data = await res.json()

  return {
    props: { data },
  }
}

export default function Home({ data }) {
  return <div>{data.title}</div>
}
```

#### getServerSideProps (Server-side Rendering)

```jsx
export async function getServerSideProps(context) {
  const res = await fetch(`https://api.example.com/data/${context.params.id}`)
  const data = await res.json()

  return {
    props: { data },
  }
}

export default function Post({ data }) {
  return <div>{data.title}</div>
}
```

#### 5. Custom App Component

Use `_app.js` to initialize pages with custom layouts or global state.

```jsx
// pages/_app.js
import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

export default MyApp
```

#### 5. Image Optimization in Next.js 🖼️

Next.js provides built-in image optimization features through the Image component:

```jsx
import Image from 'next/image'

function MyImage() {
  return (
    <Image
      src="/images/profile.jpg"
      alt="Profile picture"
      width={500}
      height={500}
    />
  )
}
```

This component automatically optimizes images for better performance and user experience.

### TypeScript Integration 🧰

Next.js has excellent TypeScript support out of the box. To use TypeScript in your Next.js project:

```bash
npx create-next-app@latest --typescript
# or
yarn create next-app --typescript
```

#### TypeScript Configuration (`tsconfig.json`)

Next.js automatically creates a `tsconfig.json` file with recommended settings:

```json
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}
```

### Built-In CSS and Sass Support 🎨

Next.js supports CSS and Sass out of the box. You can import CSS files directly in your components:

```jsx
import styles from './Button.module.css'

export function Button() {
  return (
    <button className={styles.error}>
      Delete
    </button>
  )
}
```

### Advantages of Using Next.js with TypeScript 🚀

* Enhanced developer experience with better autocomplete and type checking
* Reduced runtime errors through static type checking
* Improved code maintainability and readability
* Better integration with IDEs for refactoring and navigation

Here's an example of a TypeScript component in Next.js:

```tsx
import { NextPage } from 'next'
import { useState } from 'react'

interface Props {
  initialCount: number
}

const Counter: NextPage<Props> = ({ initialCount }) => {
  const [count, setCount] = useState(initialCount)

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  )
}

export default Counter
```

### Component Lifecycle in Next.js 🔄

Next.js components follow the React component lifecycle with some additional hooks specific to server-side rendering:

#### 1. Mounting

* `constructor()`: Initialize state and bind methods
* `render()`: Render the component
* `componentDidMount()`: Perform side effects after component is mounted

#### 2. Updating

* `shouldComponentUpdate()`: Decide if the component should re-render
* `render()`: Re-render the component
* `componentDidUpdate()`: Perform side effects after component updates

#### 3. Unmounting

* `componentWillUnmount()`: Clean up before component is unmounted

#### 4. Next.js Specific Lifecycle Methods

* `getInitialProps()`: Fetch data on the server (deprecated in favor of getStaticProps and getServerSideProps)
* `getStaticProps()`: Fetch data at build time for static generation
* `getServerSideProps()`: Fetch data on each request for server-side rendering

#### Example: Component Lifecycle

```jsx
import React from 'react'

class LifecycleComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = { count: 0 }
    console.log('Constructor')
  }

  static async getInitialProps() {
    console.log('getInitialProps')
    return { initialCount: 5 }
  }

  componentDidMount() {
    console.log('Component Did Mount')
    this.setState({ count: this.props.initialCount })
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log('Should Component Update')
    return nextState.count !== this.state.count
  }

  componentDidUpdate() {
    console.log('Component Did Update')
  }

  componentWillUnmount() {
    console.log('Component Will Unmount')
  }

  render() {
    console.log('Render')
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={() => this.setState(state => ({ count: state.count + 1 }))}>
          Increment
        </button>
      </div>
    )
  }
}

export default LifecycleComponent
```

### Real-time Example: Building a Blog with Next.js 📝

Let's create a simple blog application to demonstrate Next.js features:

#### 1. Set up the project

```bash
npx create-next-app my-blog
cd my-blog
```

#### 2. Create a layout component

```jsx
// components/Layout.js
import Link from 'next/link'

export default function Layout({ children }) {
  return (
    <div>
      <nav>
        <Link href="/">Home</Link>
        <Link href="/about">About</Link>
      </nav>
      <main>{children}</main>
      <footer>© 2024 My Blog</footer>
    </div>
  )
}
```

#### 3. Update \_app.js to use the layout

```jsx
// pages/_app.js
import Layout from '../components/Layout'

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

export default MyApp
```

#### 4. Create an API route for blog posts

```jsx
// pages/api/posts.js
const posts = [
  { id: 1, title: 'Hello Next.js', content: 'This is my first post!' },
  { id: 2, title: 'Learning Next.js', content: 'Next.js is awesome!' },
]

export default function handler(req, res) {
  res.status(200).json(posts)
}
```

#### 5. Update the home page to display blog posts

```jsx
// pages/index.js
import Link from 'next/link'

export async function getServerSideProps() {
  const res = await fetch('<http://localhost:3000/api/posts>')
  const posts = await res.json()
  return { props: { posts } }
}

export default function Home({ posts }) {
  return (
    <div>
      <h1>My Blog</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>
            <Link href={`/posts/${post.id}`}>{post.title}</Link>
          </li>
        ))}
      </ul>
    </div>
  )
}
```

#### 6. Create a dynamic route for individual blog posts

```jsx
// pages/posts/[id].js
import { useRouter } from 'next/router'

export async function getServerSideProps({ params }) {
  const res = await fetch(`http://localhost:3000/api/posts`)
  const posts = await res.json()
  const post = posts.find(p => p.id === parseInt(params.id))
  return { props: { post } }
}

export default function Post({ post }) {
  const router = useRouter()

  if (router.isFallback) {
    return <div>Loading...</div>
  }

  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  )
}
```

### FAQs🧠

1. What is the purpose of the `getStaticProps` function in Next.js?

   > Answer: `getStaticProps` is used to fetch data at build time for static generation. It allows you to pre-render pages with dynamic content by fetching data and passing it as props to the page component.
2. How does Next.js handle routing?

   > Answer: Next.js uses a file-system based routing. Each file inside the `pages` directory automatically becomes a route. For example, `pages/about.js` will be accessible at `/about`.
3. What is the difference between `getServerSideProps` and `getStaticProps`?

   > Answer: `getServerSideProps` runs on every request and is used for server-side rendering, while `getStaticProps` runs at build time and is used for static site generation.
4. How can you create dynamic routes in Next.js?

   > Answer: Dynamic routes in Next.js are created by using square brackets `[]` in the filename. For example, `pages/posts/[id].js` will match `/posts/1`, `/posts/2`, etc.
5. What is the purpose of the `_app.js` file in Next.js?

   > Answer: The `_app.js` file is used to initialize pages. It can be used to add global styles, layouts, or state management that should be applied to all pages in the application.

### Conclusion 🎉

Next.js provides a powerful and flexible framework for building modern web applications. Its server-side rendering capabilities, coupled with static site generation and API routes, make it an excellent choice for a wide range of projects. TypeScript integration further improves code quality and development efficiency, making this combination an excellent choice for both small and large-scale projects. By mastering Next.js, you'll be well-equipped to create fast, scalable, and SEO-friendly web applications.

***


# HTML & CSS

### HTML (HyperText Markup Language)

&#x20;**HTML** stands for **HyperText Markup Language**. It's the standard language for creating web pages and web applications. HTML is the backbone of web development, providing the structure. It defines the structure and content of a webpage.

#### HTML Structure

This basic structure forms the foundation of every HTML document.

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Web Page</title>
</head>
<body>
    <h1>Welcome to My Web Page</h1>
    <p>This is a paragraph.</p>
</body>
</html>
```

&#x20; The \<!DOCTYPE html> declaration is a crucial element in HTML documents for several reasons:

* 🎨 Ensures proper rendering by telling browsers to use standards mode
* 📌 Declares the document as HTML5
* 🔄 Improves cross-browser compatibility
* ✅ Enables accurate HTML validation
* 🔮 Future-proofs your document for upcoming web standards

While a webpage might display without it, including \<!DOCTYPE html> is essential for consistent functionality and adherence to web development best practices. It's a simple line of code that significantly impacts how browsers interpret and render your HTML.

* **\<!DOCTYPE html>:** Declares the document type.
* **\<html>\</html>:** Represents the root of an HTML document.
* **\<head>\</head>:** Contains meta-information about the webpage, like title, links, scripts, etc.
* **\<meta>**:&#x20;

&#x20;      Specifies metadata about an HTML document. Common attributes include:

&#x20;      charset: Specifies the character encoding for the HTML document

&#x20;      name: Specifies a name for the metadata

&#x20;     content: Specifies the value associated with the name or http-equiv attribute

&#x20;     viewport: Controls the page's dimensions and scaling on different devices

* **\<body>\</body>:** Contains the visible content of the webpage.
* **\<h1>\</h1>:** Defines a heading.
* **\<p>\</p>:** Defines a paragraph.

#### HTML Elements

HTML uses various elements to structure content. Here are some common elements:

* **Headings:** `<h1>` to `<h6>`

&#x20;         Define HTML headings, \<h1> with being the highest level and \<h6> the lowest.

* **Paragraphs:** `<p>` Defines a paragraph.
* **Links:** `<a> </a>`Defines a hyperlink, used to link from one page to another.
* **Images:** `<img>`Defines an image in an HTML page.
* **Lists:** `<ul>`, `<ol>`, `<li>`
* **Divisions:** `<div>` Defines a division or a section in an HTML document.
* **Spans:** `<span>` Used to group inline-elements in a document.
* **Tables:** `<table>`, `<tr>`, `<td>`
* **Forms:** `<form>`, `<input>`, `<label>.`
* **\<ul>\</ul>:** Defines an unordered list.
* **\<ol>\</ol>:** Defines an ordered list.
* **\<li>\</li>:** Defines a list item.

#### HTML Attributes

Attributes provide additional information about elements:

```html
<a href="<https://www.example.com>" target="_blank">Visit Example.com</a>
<img src="image.jpg" alt="A beautiful landscape" width="300" height="200">
```

#### HTML5 New Features

HTML5 introduced several new elements and features:

* **Semantic elements:** \<header>, \<nav>, \<article>, \<section>, \<aside>, \<footer>
* **Multimedia elements:** \<video>, \<audio>
* **Canvas and SVG:** For graphics and animations
* **Form enhancements:** New input types like date, email, range
* **Local storage:** For client-side data storage

#### HTML Diagram

<figure><img src="/files/Ov059krO6HJBHphDKm4t" alt=""><figcaption></figcaption></figure>

#### HTML Element Nesting

HTML elements can be nested inside each other, creating a hierarchical structure. This nesting is crucial for organizing content and applying styles effectively. Here's a diagram illustrating HTML element nesting:

<figure><img src="/files/dGBaUxtCgqUuS2eCygn1" alt=""><figcaption></figcaption></figure>

### CSS (Cascading Style Sheets)

CSS **(Cascading Style Sheets)** is a style sheet language used to describe the presentation and layout of HTML (and XML) documents. It allows web developers to control the appearance of web pages, including elements' colors, fonts, spacing, positioning, and more. By separating the content (HTML) from its presentation (CSS), developers can create consistent and visually appealing websites.

#### CSS Basic Syntax

```css
selector {
    property: value;
}
```

#### CSS Selectors

Selectors target HTML elements to apply styles:

* **Element selector:** p { }
* **Class selector:** .classname { }
* **ID selector:** #idname { }
* **Attribute selector:** \[attribute="value"] { }
* **Pseudo-class selector:** a:hover { }

#### Common CSS Properties

Here are some frequently used CSS properties:

```css
body {
    font-family: Arial, sans-serif;
    color: #333;
    background-color: #f0f0f0;
    margin: 0;
    padding: 20px;
}

h1 {
    font-size: 24px;
    font-weight: bold;
    text-align: center;
}

.container {
    width: 80%;
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
}
```

#### CSS Types

There are three ways to include CSS in a web page:

* **Inline CSS:** Styles are applied directly to HTML elements using the `style` attribute.
* **Internal CSS:** Styles are defined within the `<head>` section of an HTML document.
* **External CSS:** Styles are defined in a separate `.css` file and linked to the HTML document.

**Explanation of CSS Selectors, Properties, and Values**

#### 1. Selectors

Selectors are used to target specific HTML elements for styling. The diagram shows four types of selectors:

* **Element Selectors:** Target elements by their HTML tag name (e.g., p, div, h1).
* **Class Selectors:** Target elements with a specific class attribute (e.g., .classname).
* **ID Selectors:** Target a unique element with a specific id attribute (e.g., #idname).
* **Attribute Selectors:** Target elements based on their attributes or attribute values (e.g., \[type="text"]).

#### 2. Properties

Properties define what aspect of the selected element you want to style. The diagram highlights three categories of properties:

* **Layout Properties:** Control the positioning and sizing of elements (e.g., width, height, margin, padding).
* **Typography Properties:** Affect text appearance (e.g., font-size, font-family, text-align).
* **Color Properties:** Set colors for elements (e.g., color, background-color).

#### 3. Values

Values are assigned to properties to specify how the property should be applied. The diagram shows three types of values:

* **Keywords:** Predefined words that represent specific styles (e.g., auto, none, inherit).
* **Units:** Measurements used for size-related properties (e.g., px, em, %, rem).
* **Functions:** Special CSS functions that compute values (e.g., rgb(), calc(), url()).

Together, these components form the structure of CSS rules. For example:

```css
/* Selector */
h1 {
    /* Property: Value */
    font-size: 24px;
    color: #333;
    margin-bottom: 1em;
}
```

In this example, 'h1' is the selector, 'font-size', 'color', and 'margin-bottom' are properties, and '24px', '#333', and '1em' are their respective values.

#### Common CSS Properties with Examples

Here's a list of common CSS properties grouped by category, along with examples:

#### Font Properties

```css
p {
    font-family: Arial, sans-serif;
    font-size: 16px;
    font-weight: bold;
    color: #333;
}
```

#### Text Properties

```css
h1 {
    text-align: center;
    text-decoration: underline;
    line-height: 1.5;
}
```

#### Background Properties

```css
body {
    background-color: #f0f0f0;
    background-image: url('background.jpg');
    background-repeat: no-repeat;
    background-size: cover;
}
```

#### Dimension Properties

```css
.box {
    width: 300px;
    height: 200px;
    margin: 10px;
    padding: 20px;
    border: 1px solid #000;
}
```

#### Display and Positioning Properties

```css
.container {
    display: flex;
    justify-content: space-between;
}

.absolute-box {
    position: absolute;
    top: 50px;
    left: 100px;
}

.float-left {
    float: left;
    margin-right: 10px;
}
```

These examples demonstrate how to use common CSS properties to style various aspects of web elements, from text and fonts to layout and positioning. Experiment with these properties to achieve the desired look for your web pages.

### Real-Time Example: Portfolio Website

Let's create a simple portfolio website to demonstrate HTML and CSS skills:

#### HTML Structure

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Portfolio</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>John Doe</h1>
        <nav>
            <ul>
                <li><a href="#about">About</a></li>
                <li><a href="#projects">Projects</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
        </nav>
    </header>
    <main>
        <section id="about">
            <h2>About Me</h2>
            <p>I'm a web developer passionate about creating beautiful and functional websites.</p>
        </section>
        <section id="projects">
            <h2>My Projects</h2>
            <div class="project">
                <h3>Project 1</h3>
                <p>Description of project 1.</p>
            </div>
            <div class="project">
                <h3>Project 2</h3>
                <p>Description of project 2.</p>
            </div>
        </section>
        <section id="contact">
            <h2>Contact Me</h2>
            <form>
                <label for="name">Name:</label>
                <input type="text" id="name" name="name" required>
                <label for="email">Email:</label>
                <input type="email" id="email" name="email" required>
                <label for="message">Message:</label>
                <textarea id="message" name="message" required></textarea>
                <button type="submit">Send</button>
            </form>
        </section>
    </main>
    <footer>
        <p>&copy; 2024 John Doe. All rights reserved.</p>
    </footer>
</body>
</html>
```

#### CSS Styling

```css
/* styles.css */
body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 0;
}

header {
    background-color: #333;
    color: #fff;
    text-align: center;
    padding: 1rem;
}

nav ul {
    list-style-type: none;
    padding: 0;
}

nav ul li {
    display: inline;
    margin-right: 10px;
}

nav a {
    color: #fff;
    text-decoration: none;
}

main {
    padding: 2rem;
}

.project {
    background-color: #f4f4f4;
    border: 1px solid #ddd;
    padding: 1rem;
    margin-bottom: 1rem;
}

form {
    display: grid;
    gap: 1rem;
}

footer {
    background-color: #333;
    color: #fff;
    text-align: center;
    padding: 1rem;
    position: fixed;
    bottom: 0;
    width: 100%;
}
```

By combining HTML and CSS, you can create visually appealing and interactive web pages.


# UI Libraries & Frameworks

### The Role of UI Libraries & Frameworks in Modern Web Development

UI Libraries and Frameworks play a crucial role in modern web development by providing pre-built components and design systems that streamline the process of creating user interfaces. They offer several key benefits:

* **Efficiency:** Developers can rapidly prototype and build interfaces using ready-made components, significantly reducing development time.
* **Consistency:** These libraries ensure a consistent look and feel across an application, improving user experience.
* **Accessibility:** Many modern UI libraries come with built-in accessibility features, helping developers create more inclusive applications.
* **Responsiveness:** Most libraries offer responsive design out of the box, making it easier to create applications that work well on various devices and screen sizes.
* **Community and Support:** Popular libraries often have large communities, providing extensive documentation, tutorials, and third-party extensions.

When choosing a UI library or framework, developers should consider factors such as project requirements, team expertise, performance needs, and design flexibility. While these tools can greatly accelerate development, it's important to evaluate their long-term impact on the project's maintainability and scalability.

As the web development landscape continues to evolve, UI libraries and frameworks will likely play an increasingly important role in shaping how we build and interact with digital interfaces.


# Tailwind CSS

### 1. Introduction to Tailwind CSS

Tailwind CSS is a utility-first CSS framework that provides low-level utility classes to build custom designs quickly and efficiently. It's designed to be highly customizable and promotes a component-based approach to web development.

#### 1.1 What is Tailwind CSS?

Tailwind CSS is a highly customizable, low-level CSS framework that gives you all of the building blocks you need to build bespoke designs without any annoying opinionated styles you have to fight to override.

#### 1.2 Key Features of Tailwind CSS

* Utility-first approach
* Highly customizable
* Responsive design
* Component-friendly
* Dark mode support
* JIT (Just-In-Time) compiler

### 2. Tailwind CSS vs Traditional CSS

#### 2.1 Differences

| Aspect         | Traditional CSS                  | Tailwind CSS                       |
| -------------- | -------------------------------- | ---------------------------------- |
| Approach       | Writing custom CSS               | Using pre-defined utility classes  |
| File Size      | Can grow large                   | Optimized with PurgeCSS            |
| Customization  | Full control, but time-consuming | Highly customizable through config |
| Learning Curve | Steeper for beginners            | Easier to pick up                  |
| Consistency    | Requires discipline              | Enforced by framework              |

#### 2.2 When to Use Tailwind CSS

Tailwind CSS is particularly useful in the following scenarios:

* Rapid prototyping
* Building consistent user interfaces
* Working on large-scale projects
* When you need a highly customizable design system

#### 2.3 Why Use Tailwind CSS

* Faster development process
* Consistent designs across projects
* Reduced CSS file size
* Easy responsiveness
* Customizable to fit your brand

### 3. Getting Started with Tailwind CSS

#### 3.1 Installation

To install Tailwind CSS, you can use npm:

```bash
npm install tailwindcss
```

#### 3.2 Configuration

Create a Tailwind configuration file:

```bash
npx tailwindcss init
```

This will create a `tailwind.config.js` file in your project root.

#### 3.3 Integration

Add Tailwind to your CSS:

```css
@tailwind base;
@tailwind components;
@tailwind utilities;
```

### 4. Core Concepts

#### 4.1 Utility-First Workflow

Tailwind CSS promotes a utility-first workflow, where you build designs by combining small, single-purpose classes.

```html
<div class="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-md flex items-center space-x-4">
  <div class="flex-shrink-0">
    <img class="h-12 w-12" src="/img/logo.svg" alt="ChitChat Logo">
  </div>
  <div>
    <div class="text-xl font-medium text-black">ChitChat</div>
    <p class="text-gray-500">You have a new message!</p>
  </div>
</div>
```

#### 4.2 Responsive Design

Tailwind makes it easy to build responsive designs with breakpoint prefixes:

```html
<div class="w-full md:w-1/2 lg:w-1/3">
  <!-- This div will be full width on small screens, 1/2 width on medium screens, and 1/3 width on large screens -->
</div>
```

#### 4.3 Hover, Focus, and Other States

Tailwind provides easy ways to style elements on different states:

```html
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
  Hover me
</button>
```

### 5. Advanced Topics

#### 5.1 Custom Plugins

You can extend Tailwind's functionality by writing custom plugins:

```jsx
// tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function({ addUtilities }) {
      const newUtilities = {
        '.rotate-45': {
          transform: 'rotate(45deg)',
        },
        '.rotate-90': {
          transform: 'rotate(90deg)',
        },
      }
      addUtilities(newUtilities)
    })
  ]
}
```

#### 5.2 PurgeCSS Integration

Tailwind integrates with PurgeCSS to remove unused styles in production:

```jsx
// tailwind.config.js
module.exports = {
  purge: [
    './src/**/*.html',
    './src/**/*.js',
  ],
  // ...
}
```


# Comprehensive Guide to UI Libraries and Frameworks

In the ever-evolving world of web development, UI libraries and frameworks play a crucial role in creating beautiful, functional, and responsive user interfaces. This guide will explore several popular UI libraries and frameworks, their purposes, advantages, and use cases.

### 1. shadcn/ui 🎨

shadcn/ui is a collection of re-usable components built using Radix UI and Tailwind CSS.

* **Component Library:** Offers a wide range of pre-built components.
* **Tailwind CSS Integration:** Leverages Tailwind CSS for styling.
* **Customization:** Allows customization of component styles.
* **Accessibility:** Built with accessibility in mind.
* **Purpose:** To provide a set of accessible, customizable, and beautiful UI components
* **Best suited for:** React applications
* **Famous for:** Its flexibility and ease of customization
* **Link:** <https://ui.shadcn.com/>

#### Advantages:

* Highly customizable
* Built with accessibility in mind
* Easy to integrate with existing projects

#### Disadvantages:

* Requires knowledge of Tailwind CSS
* Not a complete out-of-the-box solution

```jsx
import { Button } from "@/components/ui/button"

export function ButtonDemo() {
  return (
    <Button variant="outline">Click me</Button>
  )
}
```

### 2. MUI (Material-UI) 🎭

MUI is a popular React UI framework that implements Google's Material Design.

* **Design System:** Offers a comprehensive design system with typography, color palette, spacing, and component guidelines.
* **Component Library:** Provides pre-built components for various UI elements.
* **Accessibility:** Prioritizes accessibility in design principles.
* **Responsiveness:** Focuses on creating responsive designs for different screen sizes.
* **Purpose:** To provide a comprehensive set of React components that follow Material Design principles
* **Best suited for:** React applications
* **Famous for:** Its extensive component library and Material Design aesthetics
* **Link:** <https://mui.com/>

#### Advantages:

* Extensive documentation
* Large community and ecosystem
* Customizable themes

#### Disadvantages:

* Can be heavy for small projects
* Styling overrides can be complex

```jsx
import React from 'react';
import Button from '@mui/material/Button';

function App() {
  return (
    <Button variant="contained" color="primary">
      Hello World
    </Button>
  );
}

export default App;
```

### 3. Chakra UI ⚡

Chakra UI is a simple, modular and accessible component library for React applications.

* **Purpose:** To provide a set of accessible and customizable React components
* **Best suited for:** React applications
* **Famous for:** Its focus on accessibility and ease of use
* **Link:** <https://chakra-ui.com/>

#### Advantages:

* Highly accessible components
* Easy to customize
* Great documentation

#### Disadvantages:

* Limited set of components compared to some other libraries
* Styling can be verbose in some cases

```jsx
import { Box, Button } from "@chakra-ui/react"

function Example() {
  return (
    <Box>
      <Button colorScheme="blue">Button</Button>
    </Box>
  )
}
```

### 4. Ant Design 🐜

Ant Design is a design system for enterprise-level products.

* **Purpose:** To provide a set of high-quality React components out of the box
* **Best suited for:** Enterprise-level React applications
* **Famous for:** Its comprehensive design system and extensive component library
* **Link:** <https://ant.design/>

#### Advantages:

* Extensive component library
* Consistent design language
* Good documentation and community support

#### Disadvantages:

* Can be overkill for smaller projects
* Customization can be challenging

```jsx
import { Button } from 'antd';

const App = () => (
  <Button type="primary">Primary Button</Button>
);

export default App;
```

### 5. Mantine 🌟

Mantine is a fully featured React component library with a focus on usability and accessibility.

* **Purpose:** To provide a set of over 100 customizable React components
* **Best suited for:** React applications of all sizes
* **Famous for:** Its flexibility and extensive feature set
* **Link:** <https://mantine.dev/>

#### Advantages:

* Large number of components
* Good TypeScript support
* Built-in dark mode

#### Disadvantages:

* Learning curve can be steep due to the large API surface
* Bundle size can be large if not properly optimized

```jsx
import { Button } from '@mantine/core';

function Demo() {
  return <Button>Click me</Button>;
}
```

### 6. Magic UI 🪄

Magic UI is a modern and lightweight UI library for React applications.

* **React Component Library:** Offers a wide range of components for building complex UIs.
* **Material Design:** Adheres to Google's Material Design guidelines.
* **Customization:** Allows customization of themes and components.
* **Accessibility:** Built with accessibility in mind.
* **Purpose:** To provide a set of customizable and easy-to-use React components
* **Best suited for:** Small to medium-sized React projects
* **Famous for:** Its simplicity and ease of integration
* **Link:** <https://www.magic-ui.com/>

#### Advantages:

* Lightweight and fast
* Easy to learn and use
* Good documentation

#### Disadvantages:

* Limited number of components compared to larger libraries
* Smaller community and ecosystem

```jsx
import { Button } from 'magic-ui';

function App() {
  return (
    <Button variant="primary">Click me</Button>
  );
}
```

### 7. UIACeternity 🌈

UIACeternity is a modern UI component library for React applications with a focus on aesthetics and customization.

* **User-Centric Design:** Prioritizes user needs and accessibility.
* **Component Library:** Offers a set of pre-built components.
* **Design Guidelines:** Provides clear design principles and standards.
* **Accessibility:** Built with accessibility in mind.
* **Purpose:** To provide a set of beautiful and highly customizable React components
* **Best suited for:** React applications with unique design requirements
* **Famous for:** Its unique design system and extensive customization options
* **Link:** <https://uiaceternity.com/>

#### Advantages:

* Unique and modern design
* Highly customizable components
* Good performance

#### Disadvantages:

* Steeper learning curve due to unique API
* May require more effort to integrate with existing design systems

```jsx
import { Button } from 'uiaceternity';

function App() {
  return (
    <Button theme="gradient" size="large">
      Explore Now
    </Button>
  );
}
```

### 8. Prochakra 🔮

Prochakra is an extension of Chakra UI that adds more advanced components and features.

* **Chakra UI Integration:** Leverages Chakra UI for styling and components.
* **Next.js Compatibility:** Optimized for use with Next.js.
* **Component Library:** Offers a range of pre-built components.
* **Customization:** Allows customization of themes and components.
* **Purpose:** To enhance Chakra UI with additional components and functionalities
* **Best suited for:** React applications already using Chakra UI that need more advanced features
* **Famous for:** Its seamless integration with Chakra UI and advanced component offerings
* **Link:** <https://pro.chakra-ui.com/>

#### Advantages:

* Builds upon the accessibility and ease of use of Chakra UI
* Provides more complex components for advanced use cases
* Maintains consistency with Chakra UI's design principles

#### Disadvantages:

* Requires Chakra UI as a base, which may not suit all projects
* Can increase bundle size significantly

```jsx
import { Button } from '@chakra-ui/react'
import { DataTable } from '@chakra-ui/pro-components'

function App() {
  return (
    <>
      <Button colorScheme="blue">Chakra Button</Button>
      <DataTable columns={columns} data={data} />
    </>
  );
}
```

### Comparison Diagram

<figure><img src="/files/N6BLoq0ICkgsw3wmsKnR" alt=""><figcaption></figcaption></figure>

Each library is connected to its key characteristic, providing a clear and concise overview of the different options available to developers. This portrait-style diagram is easier to read on most screens and maintains a logical flow from the main category to individual libraries and their distinctive features.

### Real-world Example: Building a Dashboard

Let's consider a scenario where you're building a dashboard for a financial application. Each UI library/framework has its strengths:

* **shadcn/ui:** Great for custom-designed components that match your brand
* **MUI:** Excellent for a Material Design-based dashboard with complex data tables
* **Chakra UI:** Ideal if accessibility is a top priority
* **Ant Design:** Perfect for enterprise-level dashboards with a wide variety of data visualization components
* **Mantine:** Good all-rounder with a large set of components to choose from

Here's a simple example of how you might create a dashboard header using MUI:

```jsx
import React from 'react';
import { AppBar, Toolbar, Typography, Button } from '@mui/material';

function DashboardHeader() {
  return (
    <AppBar position="static">
      <Toolbar>
        <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
          Financial Dashboard
        </Typography>
        <Button color="inherit">Logout</Button>
      </Toolbar>
    </AppBar>
  );
}

export default DashboardHeader;
```


# Backend

## &#x20;Summary of Backend Expertise

> Proficient backend developer with extensive experience in building scalable and efficient server-side applications using Node.js and Express.js. Skilled in creating RESTful APIs, implementing authentication systems, and integrating with databases to support robust web applications.

## Technical Skills

* **Core Technologies:** Node.js, Express.js
* **Databases:** MongoDB, PostgreSQL, MySQL
* **ORM/ODM:** Mongoose, Sequelize
* **Authentication:** JWT, Passport.js, OAuth
* **API Development:** RESTful APIs, GraphQL
* **Testing:** Mocha, Chai, Jest
* **Deployment:** Docker, Kubernetes, AWS, Heroku

## Node.js and Express.js Expertise

#### Node.js:

* Proficient in asynchronous programming and event-driven architecture
* Experience with core modules (fs, http, path, etc.) and NPM ecosystem
* Implementing microservices architecture using Node.js
* Performance optimization and memory management in Node.js applications

#### Express.js:

* Building scalable and maintainable web applications and APIs
* Implementing middleware for request processing, authentication, and error handling
* Integrating template engines (e.g., EJS, Pug) for server-side rendering
* Structuring Express.js applications for optimal performance and code organization

## &#x20;**Database Management Skills**

Experienced in designing, implementing, and optimizing both SQL and NoSQL databases. Proficient in data modeling, query optimization, and database administration, with a focus on ensuring data integrity, security, and performance in web applications.

* Database performance tuning and query optimization
* Implementing data security measures and access control
* Setting up database replication and backup strategies
* Database health monitoring and maintenance


# Node.js

### Introduction to Node.js 🌟

Node.js is a powerful JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server-side, enabling the creation of scalable and high-performance web applications.

#### Why Use Node.js? 🤔

* Asynchronous and Event-Driven: Perfect for non-blocking, event-driven servers
* Fast: Executes code quickly due to its V8 JavaScript Engine
* Single-threaded but Highly Scalable: Can handle a huge number of simultaneous connections
* No Buffering: Node.js applications never buffer any data
* Large Ecosystem: npm (Node Package Manager) has a vast library of open-source packages

#### Installation Guide 🛠️

Follow these steps to install Node.js:

1. Visit the official Node.js website: <https://nodejs.org>
2. Download the installer for your operating system
3. Run the installer and follow the prompts
4. Verify installation by opening a terminal and running:

   ```bash
   node --version
   npm --version
   ```

### Node.js Architecture 🏗️

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Here's a simplified diagram of its architecture:

<figure><img src="/files/WednTxUsMhjGjePRbdkd" alt=""><figcaption></figcaption></figure>

### Parts of Node.js <a href="#parts_of_nodejs" id="parts_of_nodejs"></a>

<figure><img src="/files/Aix9HlmDdrb7IxfdZgyv" alt=""><figcaption></figcaption></figure>

### Core Concepts 🧠

#### 1. Event Loop ⚙️

The event loop is the heart of Node.js. It allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded.

```jsx
const fs = require('fs');

// Asynchronous file read
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

console.log('This will be printed first!');
```

#### 2. Modules 📦

Node.js uses the CommonJS module system. You can create and use modules to organize your code.

```jsx
// math.js
module.exports = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b
};

// app.js
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8
```

#### 3. Streams 🌊

Streams are objects that let you read data from a source or write data to a destination continuously.

```jsx
const fs = require('fs');
const readStream = fs.createReadStream('input.txt');
const writeStream = fs.createWriteStream('output.txt');

readStream.pipe(writeStream);

readStream.on('end', () => {
  console.log('Read and write completed');
});
```

#### 4. Buffers 🧊

Buffers are used to handle binary data in Node.js.

```jsx
const buf = Buffer.from('Hello, World!', 'utf8');
console.log(buf.toString('hex')); // Output: 48656c6c6f2c20576f726c6421
console.log(buf.toString('base64')); // Output: SGVsbG8sIFdvcmxkIQ==
```

### Advanced Concepts 🚀

#### 1. Clustering 🖥️

Node.js clustering allows you to create child processes that run simultaneously, sharing the same server port.

```jsx
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}
```

* **Master process:** The code runs as a master if `cluster.isMaster` is true. The master process is responsible for forking worker processes.
* **Workers:** Each worker is a new Node.js process, created by `cluster.fork()`. Workers share the same server port but run on different CPU cores, enabling better resource utilization.
* **Restart workers:** If a worker crashes, the master process listens to the `exit` event and restarts the worker using `cluster.fork()`.

#### 2. Worker Threads 🧵

Worker threads allow running JavaScript in parallel, useful for CPU-intensive tasks.

```jsx
const { Worker, isMainThread, parentPort } = require('worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);
  worker.on('message', (msg) => {
    console.log('From worker:', msg);
  });
  worker.postMessage('Hello, worker!');
} else {
  parentPort.on('message', (msg) => {
    console.log('From parent:', msg);
    parentPort.postMessage('Hello, parent!');
  });
}
```

* **Main thread:** When `isMainThread` is true, the current thread is the main thread, which creates a new worker using the `Worker` constructor. The file to be executed in the worker thread is the same file (`__filename`), but it will run different code based on whether it's in the main thread or the worker thread.
* **Worker thread:** In the worker, we receive `workerData` (input) and perform a CPU-intensive calculation. After the calculation is done, the result is sent back to the main thread using `parentPort.postMessage()`.
* **Communication:** The main thread listens for messages using the `'message'` event, and error handling is done through the `'error'` and `'exit'` events.

#### 3. Performance Optimization 🏎️

Optimizing Node.js applications involves various techniques:

* Use asynchronous methods whenever possible
* Implement caching strategies
* Optimize database queries
* Use compression for network responses
* Implement load balancing

#### 4. Security Best Practices 🔒

Ensuring the security of your Node.js application is crucial:

* Keep dependencies up to date
* Use HTTPS
* Implement proper authentication and authorization
* Validate and sanitize user inputs
* Set appropriate HTTP headers
* Use security linters like eslint-plugin-security

### Conclusion 🎓

Node.js is a powerful platform that enables developers to build scalable and efficient applications. By mastering these concepts and continuously learning, you can become a proficient Node.js developer capable of tackling complex backend challenges.


# Express.js

### Express.js: A Powerful Web Application Framework for Node.js 🚀

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It's designed for building single-page, multi-page, and hybrid web applications.

#### Why Use Express.js? 🤔

* Fast and minimalist web framework
* Easy to set up and configure
* Large community and extensive plugin ecosystem
* Flexible routing system
* Supports various templating engines

#### Installation and Basic Setup 🛠️

To install Express.js, run the following command in your project directory:

```bash
npm install express
```

Here's a basic example of an Express.js application:

```jsx
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Example app listening at <http://localhost>:${port}`);
});
```

#### Key Features of Express.js 🔑

* Routing
* Middleware support
* Template engine integration
* Static file serving
* Error handling

#### Types of Applications Using Express.js 🌐

* RESTful APIs
* Single-page applications (SPAs)
* E-commerce platforms
* Real-time applications (with [Socket.io](http://Socket.io))
* Content management systems (CMS)

#### Core Concepts of Express.js 🧠

Here's a diagram illustrating the core concepts of Express.js:

<figure><img src="/files/O54lwu32VKDxqcgnGO0M" alt=""><figcaption></figcaption></figure>

#### Key Functions in Express.js 🛠️

* `express()`: Creates an Express application
* `app.use()`: Mounts middleware
* `app.get(), app.post(), app.put(), app.delete()`: HTTP method routing
* `app.all()`: Handles all HTTP methods
* `app.param()`: Adds callback triggers to route parameters
* `res.send()`: Sends a response
* `res.json()`: Sends a JSON response
* `res.render()`: Renders a view template

#### Advanced Topics in Express.js 🚀

#### 1. Middleware Chaining

```jsx
app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});
```

#### 2. Error Handling Middleware

```jsx
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});
```

#### 3. Template Engines

```jsx
app.set('view engine', 'pug');
app.get('/', (req, res) => {
  res.render('index', { title: 'Hey', message: 'Hello there!' });
});
```

#### 4. Database Integration

```jsx
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp', {useNewUrlParser: true, useUnifiedTopology: true});
```

#### 5. Authentication Middleware

```jsx
const auth = (req, res, next) => {
  if (req.session && req.session.userId) {
    return next();
  } else {
    return res.sendStatus(401);
  }
};

app.get('/profile', auth, (req, res) => {
  res.send('Profile Page');
});
```

By mastering these concepts and features, you can build robust and efficient web applications with Express.js. 💪


# Database

Types of Databases

Databases are categorized based on their structure, data organization, and access methods. Here are some common types:

#### 1. Relational/SQL Databases

* **Relational Database Management System (RDBMS):** Organizes data in tables with rows and columns. Each row represents a record, and each column represents a field. Relationships between tables are defined using foreign keys.
  * **Examples:** MySQL,PostgreSQL,Oracle,SQL Server

* **Object-Relational Database Management System (ORDBMS):** Combines the features of relational databases with object-oriented programming concepts. It allows for the storage and retrieval of complex data objects.
  * **Examples:** Microsoft SQL Server,Oracle Database,PostgreSQL,DB2

#### 2. NoSQL Databases

* **Document Databases:** Store data in flexible, document-oriented structures, often using JSON or BSON.
  * **Examples:**&#x4D;ongoDB,CouchDB,Firebase
* **Key-Value Stores:** Store data as key-value pairs, where keys are unique identifiers and values can be any type of data.
  * **Examples:**&#x52;edis,Memcached,DynamoDB
* **Wide-Column Stores:** Store data in wide columns, where each column can have multiple values associated with a specific row.
  * **Examples:**&#x43;assandra,HBase
* **Graph Databases:** Store data as nodes and relationships between them, forming a graph structure.
  * **Examples:**&#x4E;eo4j,ArangoDB,OrientDB

#### 3. Other Types

* **Time Series Databases:** Specialized for handling time-stamped data, often used in IoT, finance, and scientific applications.
  * **Examples:**&#x49;nfluxDB,TimescaleDB
* **Spatial Databases:** Designed to store and query spatial data, such as geographic locations and shapes.
  * **Examples:**&#x50;ostGIS,MongoDB
* **Multi-Model Databases:** Support multiple data models, allowing you to choose the best approach for different types of data.
  * **Examples:**&#x43;ouchbase,ArangoDB

### Types of Databases and Their Examples

**Here's a more detailed table with examples for each type:**

| Database Type                       | Data Format                    | Example                                                           |
| ----------------------------------- | ------------------------------ | ----------------------------------------------------------------- |
| Relational Database (RDBMS)         | Tables with rows and columns   | Customer database with tables for customers, orders, and products |
| Object-Relational Database (ORDBMS) | Tables with complex data types | E-commerce database storing products as objects                   |
| Document Database                   | JSON or BSON documents         | Blog database storing posts, comments, and authors as documents   |
| Key-Value Store                     | Key-value pairs                | Caching system storing frequently accessed data                   |
| Wide-Column Store                   | Wide columns                   | Sensor data database storing measurements                         |
| Graph Database                      | Nodes and relationships        | Social network database representing users and connections        |
| Time Series Database                | Time-stamped data              | Financial database storing stock prices                           |
| Spatial Database                    | Spatial data                   | Mapping application storing locations                             |
| Multi-Model Database                | Varies                         | Complex application using document, graph, and key-value models   |

**The choice of database and data format depends on the specific requirements of  application, such as the type of data, query patterns, and scalability needs.**


# Mongodb, Mongoose

## MongoDB: A NoSQL Database 🍃

**MongoDB** is a popular NoSQL (Not Only SQL) document-oriented database. Unlike traditional relational databases, MongoDB stores data in flexible, JSON-like documents. This structure makes it highly adaptable to various data models and enables efficient handling of large volumes of unstructured data. &#x20;

#### Key Features of MongoDB 🛠️

* **Document-Oriented:** Stores data in flexible, JSON-like documents. &#x20;
* **Schema-less:** Allows for flexible data structures, accommodating evolving data requirements. &#x20;
* **Scalability:** Handles large datasets and high-traffic applications effectively. &#x20;
* **High Performance:** Delivers fast read and write operations. &#x20;
* **Rich Query Language:** Supports complex queries and aggregations. &#x20;
* **Indexing:** Provides robust indexing capabilities for efficient data retrieval. &#x20;

#### When to Use MongoDB 📈

* Applications with rapidly changing data structures. &#x20;
* Handling large volumes of unstructured or semi-structured data. &#x20;
* Real-time analytics and processing. &#x20;
* High-performance apps requiring fast read/write operations.

***

## Mongoose: ODM for MongoDB 🧑‍💻

Mongoose is an Object Data Modeling (ODM) library for Node.js, providing a structured way to interact with MongoDB. It simplifies data modeling, validation, and database interactions.

### Key Features of Mongoose ⚙️

* **Schema Definition**: Defines the structure of documents in MongoDB.
* **Model Creation**: Creates Mongoose models based on schemas.
* **Data Validation**: Enforces data integrity through schema validation.
* **Query Building**: Fluent API for building complex queries.
* **Middleware Support**: Customizes document lifecycle events.
* **Population**: Populates referenced documents.

#### Why Use Mongoose? 🤔

* Simplified data modeling for MongoDB.
* Enhanced data integrity via schema validation.
* A familiar object-oriented interface for Node.js developers.

***

## Example: Mongoose Code 📝

```javascript
//const mongoose = require('mongoose');

// Define schema
const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  age: Number
});

// Create model
const User = mongoose.model('User', userSchema);

// Create a new user
const newUser = new User({ name: 'John Doe', email: 'johndoe@example.com', age: 30 });
newUser.save();

```

***

## MongoDB Document Structure 🗂️

MongoDB stores data in a flexible document-based format similar to JSON. Each document is a collection of key-value pairs, with values that can be:

* **Strings**: e.g., "John Doe"
* **Numbers**: e.g., 30
* **Arrays**: e.g., `["reading", "coding"]`
* **Objects**: Nested key-value pairs
* **Booleans**: `true` or `false`
* **Date Objects**: Representing specific times
* **Null**: Representing missing values

#### Example of a MongoDB Document:

```json
jsonCopy code{
    "_id": ObjectId("64e8a2200000000000000001"),
    "name": "John Doe",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "New York",
        "state": "NY"
    },
    "hobbies": ["reading", "traveling", "coding"]
}
```

This document represents a person with various attributes, including a nested address and hobbies stored in an array.

***

## BSON: MongoDB's Native Format 🔄

While MongoDB can handle JSON, its native format is **BSON** (Binary JSON), which is more compact and efficient.

#### Advantages of BSON over JSON:

* **Efficiency**: More compact and faster to store/transmit.
* **Additional Data Types**: Supports binary data, timestamps, and regular expressions.
* **Performance**: Optimized for MongoDB’s internal operations.

***

## MongoDB Skills 🍃

As a MongoDB expert, here’s a snapshot of my skills:

#### 1. MongoDB Architecture 🏗️

MongoDB follows a document-oriented NoSQL database architecture. Here's a simplified diagram of its structure:

<figure><img src="/files/rL1kU1v6DYbtlPhn77PU" alt=""><figcaption></figcaption></figure>

#### 2. Key Concepts 🔑

* **Documents:** JSON-like data structures, the basic unit of data in MongoDB
* **Collections:** Groups of documents, similar to tables in relational databases
* **Databases:** Containers for collections
* **BSON:** Binary JSON, the binary-encoded serialization of JSON-like documents

#### 3. CRUD Operations 🔄

Proficient in performing Create, Read, Update, and Delete operations:

```jsx
// Create
db.users.insertOne({
  name: "John Doe",
  email: "john@example.com",
  age: 30
});

// Read
db.users.find({ age: { $gt: 25 } });

// Update
db.users.updateOne(
  { name: "John Doe" },
  { $set: { age: 31 } }
);

// Delete
db.users.deleteOne({ email: "john@example.com" });
```

#### 4. Indexing and Query Optimization 🚀

Experienced in creating and managing indexes for improved query performance:

```jsx
// Create an index
db.users.createIndex({ email: 1 });

// Analyze query performance
db.users.find({ email: "john@example.com" }).explain("executionStats");
```

#### 5. Aggregation Framework 📊

Skilled in using MongoDB's powerful aggregation framework for complex data processing:

```jsx
db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$customerId", totalSpent: { $sum: "$total" } } },
  { $sort: { totalSpent: -1 } },
  { $limit: 5 }
]);
```

#### 6. Replication and Sharding 🔄🔀

Knowledgeable in setting up and managing replica sets for high availability and sharding for horizontal scaling:

<figure><img src="/files/fF5nzZYWha0YproX6Bsn" alt=""><figcaption></figcaption></figure>

#### 7. Security and Authentication 🔒

Experienced in implementing MongoDB's security features:

* Role-Based Access Control (RBAC)
* SSL/TLS encryption for data in transit
* Field-level encryption for sensitive data

#### 8. Performance Monitoring and Optimization 📈

Proficient in using MongoDB's built-in tools and third-party solutions for monitoring and optimizing database performance:

* MongoDB Compass for visual query analysis
* mongostat and mongotop for real-time performance monitoring
* Implementing database profiling for slow query analysis

With these skills, I can design, implement, and maintain scalable MongoDB databases that meet your needs! 💪


# PostgresSQl

### PostgreSQL: A Robust Object-Relational Database System 🐘

**PostgreSQL** is an advanced, open-source object-relational database system (ORDBMS) that combines the power of relational databases with the flexibility of object-oriented programming. It's known for its reliability, performance, and rich feature set.

### Key Features 🌟

* **Object-Relational**: Supports both relational (tables, rows, columns) and object-oriented concepts (inheritance, polymorphism, complex data types).
* **ACID Compliance**: Ensures data integrity and consistency through ACID properties (Atomicity, Consistency, Isolation, Durability).
* **Extensibility**: Users can create custom data types, functions, and operators.
* **Advanced Features**: Includes stored procedures, triggers, views, indexes, and foreign keys.
* **JSON Support**: Natively handles JSON data, useful for modern applications.
* **High Performance**: Optimized for handling large datasets and complex queries.
* **Open Source**: Free to use, modify, and distribute.

### Core Concepts 💡

* **Tables**: Organize data into rows and columns.
* **Rows**: Represent individual records of data.
* **Columns**: Define attributes or fields of each row.
* **Schemas**: Group related tables and objects.
* **SQL**: The standard language for database interactions.
* **Transactions**: A unit of work that is either fully committed or rolled back.
* **Indexes**: Improve query performance by speeding up data retrieval.

#### Example

```sql
CREATE TABLE customers (
    id SERIAL PRIMARY KEY,
    first_name TEXT NOT NULL,
    last_name TEXT NOT NULL,
    email TEXT UNIQUE
);
```

This SQL code creates a table named `customers` with columns for `id`, `first_name`, `last_name`, and `email`. The `id` column is set as the primary key, and the `email` column is defined as unique.

#### When to Use PostgreSQL 🔍

* Applications requiring complex data relationships and transactions.
* Handling large volumes of structured data.
* Building enterprise-grade applications with high availability and performance needs.
* When you need a database that supports both relational and JSON data.

### PostgreSQL Skills Overview 🏆

As a PostgreSQL expert, I have extensive knowledge of its architecture, concepts, and best practices. Here's a comprehensive overview of my PostgreSQL skills:

#### 1. PostgreSQL Architecture 🏗️

PostgreSQL follows a client-server model with a multi-process architecture. Here's a simplified diagram of its structure:

<figure><img src="/files/H60A4GjKxVtfWxtehjYA" alt=""><figcaption></figcaption></figure>

#### 2. Key Concepts 🔑

* **Tables:** The basic structure for storing data in rows and columns
* **Schemas:** Namespaces that organize database objects
* **Indexes:** Data structures that improve query performance
* **Views:** Virtual tables based on the result of a SELECT query
* **Stored Procedures:** Reusable blocks of SQL code
* **Triggers:** Functions automatically executed in response to certain events

#### 3. CRUD Operations and Advanced Queries 🔄

Proficient in performing Create, Read, Update, and Delete operations, as well as complex queries:

```sql
-- Create a table
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100) UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Insert data
INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com');

-- Select data with a JOIN
SELECT u.name, o.order_date
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE o.total > 100;

-- Update data
UPDATE users SET name = 'Jane Doe' WHERE id = 1;

-- Delete data
DELETE FROM users WHERE email = 'john@example.com';
```

#### 4. Indexing and Query Optimization 🚀

Experienced in creating and managing indexes for improved query performance:

```sql
-- Create an index
CREATE INDEX idx_user_email ON users(email);

-- Analyze query performance
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'john@example.com';
```

#### 5. Advanced Features 🔬

* **JSON/JSONB**: Querying and handling JSON data.
* **Full-text Search**: Using `tsvector` and `tsquery` for text search.
* **Window Functions**: Analytical queries.
* **Common Table Expressions (CTEs)**: Complex or recursive queries.

```sql
-- JSON query
SELECT data->>'name' AS name
FROM users
WHERE data @> '{"age": 30}';

-- Full-text search
SELECT title
FROM articles
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'postgresql & database');

-- Window function
SELECT name, salary, 
       AVG(salary) OVER (PARTITION BY department) as dept_avg
FROM employees;

-- CTE
WITH RECURSIVE subordinates AS (
    SELECT employee_id, manager_id, name
    FROM employees
    WHERE name = 'John Doe'
    UNION ALL
    SELECT e.employee_id, e.manager_id, e.name
    FROM employees e
    INNER JOIN subordinates s ON s.employee_id = e.manager_id
)
SELECT * FROM subordinates;
```

#### 6. Replication and High Availability 🔄🔀

Knowledgeable in setting up and managing replication for high availability:

<figure><img src="/files/lrIgLgmyDxzf76e5P21B" alt=""><figcaption></figcaption></figure>

#### 7. Security and Authentication 🔒

* Role-Based Access Control (RBAC)
* SSL/TLS encryption for data in transit
* Row-Level Security (RLS) for fine-grained access control

```sql
-- Create a role
CREATE ROLE readonly LOGIN PASSWORD 'secret';

-- Grant privileges
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;

-- Enable row-level security
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

-- Create a policy
CREATE POLICY user_orders ON orders
    FOR SELECT
    USING (user_id = current_user_id());
```

#### 8. Performance Monitoring and Optimization 📈

Proficient with PostgreSQL tools for performance monitoring:

* `pg_stat_statements` for query analysis.
* `EXPLAIN` and `EXPLAIN ANALYZE` for query plans.
* **Vacuum and Analyze**: Maintain table statistics.
* **Partitioning**: Improve performance for large tables.

With these skills, I can design, implement, and maintain highly efficient PostgreSQL databases for various applications, ensuring performance, scalability, and reliability. 💪🚀


# MySQL

## MySQL: (RDBMS) 🐬

MySQL is a widely-used, open-source relational database management system (RDBMS) designed for efficiently storing, managing, and retrieving data. Known for its **reliability**, **scalability**, and **ease of use**, it powers many web applications and large-scale systems.

***

#### 🚀 **How MySQL Works**

MySQL organizes data into **tables** with rows and columns. Each row represents a record, while columns define the attributes of that record. This logical structure makes data retrieval fast and efficient.

***

#### 🗝️ **Key Components**

* **Relationships**: Connections between tables (e.g., one-to-one, one-to-many).
* **Tables:** The basic structure for storing data in rows and columns
* **Indexes:** Data structures that improve query performance
* **Views:** Virtual tables based on the result of a SELECT query
* **Stored Procedures:** Reusable blocks of SQL code
* **Triggers:** Functions automatically executed in response to certain events
* **Transactions:** Units of work that ensure data integrity

***

#### 💻 **SQL (Structured Query Language)**

MySQL uses SQL to interact with the database. SQL is used for:

* **Creating** and **modifying** tables.
* **Inserting**, **updating**, and **deleting** data.
* **Querying** data efficiently.

***

#### 📝 **Example SQL Code**:

```sql
sqlCopy codeCREATE TABLE customers (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE
);
```

This SQL command creates a table named `customers` with `id`, `name`, and `email` columns. The `id` column is the primary key and auto-increments, and the `email` column must be unique.

***

#### 🛠️ **When to Use MySQL**

MySQL is ideal for:

* **Web applications** (e.g., WordPress).
* **E-commerce platforms**.
* **Content management systems** (CMS).
* **Enterprise-grade systems**.

***

#### 📈 **Advantages of MySQL**

* **Open-source**: Free to use and distribute.
* **Reliable**: Proven performance and stability.
* **Scalable**: Manages large datasets and high traffic efficiently.
* **Community Support**: Extensive resources and help.
* **Easy to Learn**: Intuitive for beginners.

***

#### ⚖️ **Disadvantages of MySQL**

* **Performance**: May lag behind some databases for highly complex queries.
* **Schema Rigidity**: Requires predefined structures, making it less flexible compared to NoSQL databases.

***

### **MySQL Skills Overview** 🐬💡

As an experienced MySQL developer, I have comprehensive expertise in designing and managing databases using best practices. Here's a breakdown of my MySQL skills:

#### MySQL Architecture 🏗️

MySQL follows a client-server architecture. Here's a simplified diagram of its structure:

<figure><img src="/files/vMtoX7UOFKLcclqu9Lt1" alt=""><figcaption></figcaption></figure>

#### &#x20;CRUD Operations and Advanced Queries 🔄

Proficient in **Create**, **Read**, **Update**, and **Delete** operations and executing complex queries.

```sql
-- Create a table
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100) UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Insert data
INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com');

-- Select data with a JOIN
SELECT u.name, o.order_date
FROM users u
INNER JOIN orders o ON u.id = o.user_id
WHERE o.total > 100;

-- Update data
UPDATE users SET name = 'Jane Doe' WHERE id = 1;

-- Delete data
DELETE FROM users WHERE email = 'john@example.com';
```

#### &#x20;Indexing and Query Optimization 🚀

Experienced in creating and managing indexes for improved query performance:

```sql
-- Create an index
CREATE INDEX idx_user_email ON users(email);

-- Analyze query performance
EXPLAIN SELECT * FROM users WHERE email = 'john@example.com';
```

#### &#x20;Advanced Features 🔬

* **Partitioning:** Dividing large tables into smaller, more manageable parts
* **Full-text Search:** Using FULLTEXT indexes for text searching
* **Stored Functions:** For complex calculations and logic
* **Events:** Scheduled tasks that run automatically

```sql
-- Table partitioning
CREATE TABLE orders (
    id INT,
    order_date DATE,
    total DECIMAL(10,2)
)
PARTITION BY RANGE (YEAR(order_date)) (
    PARTITION p0 VALUES LESS THAN (2020),
    PARTITION p1 VALUES LESS THAN (2021),
    PARTITION p2 VALUES LESS THAN (2022),
    PARTITION p3 VALUES LESS THAN MAXVALUE
);

-- Full-text search
CREATE FULLTEXT INDEX idx_article_content ON articles(content);
SELECT * FROM articles 
WHERE MATCH(content) AGAINST('MySQL database' IN NATURAL LANGUAGE MODE);

-- Stored function
DELIMITER //
CREATE FUNCTION calculate_discount(price DECIMAL(10,2), discount_percent INT)
RETURNS DECIMAL(10,2)
BEGIN
    RETURN price - (price * discount_percent / 100);
END //
DELIMITER ;

-- Event
CREATE EVENT daily_cleanup
ON SCHEDULE EVERY 1 DAY
DO
    DELETE FROM temp_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY);
```

#### Security and Authentication 🔒

Experienced in implementing MySQL's security features:

* User Authentication and Privileges
* SSL/TLS encryption for data in transit
* MySQL Enterprise Audit for tracking database activity

```sql
-- Create a user
CREATE USER 'readonly'@'localhost' IDENTIFIED BY 'secret';

-- Grant privileges
GRANT SELECT ON mydatabase.* TO 'readonly'@'localhost';

-- Enable SSL for a user
ALTER USER 'username'@'localhost' REQUIRE SSL;

-- View current connections
SELECT * FROM information_schema.processlist;
```

#### Performance Monitoring and Optimization 📈

Proficient in using MySQL's built-in tools and third-party solutions for monitoring and optimizing database performance:

* SHOW PROCESSLIST for viewing current database connections
* EXPLAIN for query plan analysis
* Performance Schema for detailed performance metrics
* MySQL Enterprise Monitor for comprehensive monitoring and alerting

```sql
-- Check table status
SHOW TABLE STATUS;

-- Optimize a table
OPTIMIZE TABLE mytable;

-- View query cache statistics
SHOW STATUS LIKE 'Qcache%';

-- Enable slow query log
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;
```

With these skills, I can design, implement, and maintain efficient and scalable MySQL databases for various applications, ensuring optimal performance, security, and reliability. 💪🚀


# Packege Mangers

## Package Manager Overview

### Introduction

* **What is a Package Manager?**\
  A brief description of what a package manager is, how it simplifies software development, and why it is essential.\
  Example: "A package manager is a tool that automates the process of installing, upgrading, configuring, and managing software dependencies and libraries within a project. Popular examples include npm, Yarn, and pip."

***

### Key Features

#### 1. **Dependency Management**

* **Definition**: Manage and resolve dependencies between software libraries.
* **Functionality**: Automatically fetches the required versions of dependencies, ensuring compatibility.
* **Example**: “In `npm`, you specify dependencies in `package.json` and the manager installs them.”

#### 2. **Version Control**

* **Definition**: Handles different versions of packages.
* **Functionality**: Allows the user to install specific versions of a package or automatically fetch the latest stable version.
* **Example**: “In Yarn, you can lock package versions using `yarn.lock`.”

#### 3. **Package Distribution**

* **Definition**: Distributes libraries or software across projects or users.
* **Functionality**: Hosts packages in centralized repositories (e.g., npm registry, PyPI).
* **Example**: “Publish your JavaScript package to npm with the `npm publish` command.”

#### 4. **Local vs Global Installation**

* **Local Installation**: Installs packages within the project scope (e.g., `node_modules`).
* **Global Installation**: Installs packages globally on the system, accessible by any project.
* **Example**: "`npm install express --save` (local) vs `npm install -g create-react-app` (global)."

#### 5. **Scripts and Automation**

* **Definition**: Use scripts to automate common tasks.
* **Functionality**: Automate tasks like building, testing, or linting the project using scripts defined in the configuration file (e.g., `npm run build`).
* **Example**: "Define `scripts` in `package.json` to streamline commands for the development workflow."

***

### Commonly Used Package Managers

### NPM (Node Package Manager)

NPM is the default package manager for Node.js and is widely used in the JavaScript ecosystem.

* Key skills:
  * Efficient dependency management
  * Publishing and maintaining packages
  * Scripts and automation
  * Security audits and updates

### Yarn

Yarn is an alternative to NPM, known for its speed and reliability.

* Key skills:
  * Faster package installation
  * Offline mode usage
  * Yarn workspaces for monorepo management
  * License checking

### Yarn 2 (Berry)

Yarn 2, also known as Berry, is a major update to Yarn with significant improvements.

* Experience level: Intermediate
* Key skills:
  * Plug'n'Play for improved performance
  * Zero-installs for faster CI/CD pipelines
  * Constraints for managing monorepos
  * Improved caching mechanisms

### PNPM

PNPM is a fast, disk space efficient package manager that uses a unique approach to dependency management.

* Key skills:
  * Content-addressable storage for efficient disk usage
  * Monorepo management with workspaces
  * Fast parallel installation
  * Strict mode for better dependency tree consistency

### Bun

Bun is an all-in-one JavaScript runtime and toolkit that includes a package manager.

* Key skills:
  * Ultra-fast package installation
  * Native support for TypeScript and JSX
  * Built-in bundler and transpiler
  * Compatibility with existing Node.js projects

***

## Best Practices for Managing Packages

1. **Use Lock Files**: Always commit lock files to ensure consistent environments across development, testing, and production.
2. **Semantic Versioning**: Stick to semantic versioning for better compatibility and to avoid unnecessary breaking changes.
3. **Audit Dependencies**: Regularly run audits (e.g., `npm audit`) to check for security vulnerabilities in dependencies.
4. **Remove Unused Packages**: Clean up unused dependencies with commands like `npm prune`.

***

## Comparative Analysis

My experience with these package managers allows me to choose the most appropriate tool for each project based on factors such as:

* Project size and complexity
* Team familiarity and preferences
* Performance requirements
* Monorepo vs. polyrepo architecture
* CI/CD integration needs

***

## Conclusion

My diverse knowledge of package managers enables me to optimize dependency management, improve build times, and enhance overall project efficiency across various JavaScript and Node.js environments.


# NPM-Node Packege Manager

## **NPM (Node Package Manager)** <a href="#id-2502" id="id-2502"></a>

NPM (Node Package Manager) is considered to be the largest software registry in the world. It is free, open-source, installed with Node.js, contains packages written in JSON. The main purpose of NPM is to provide automated dependency and package management. Those who use npm say it helps to improve your experience and the overall efficiency of Node.js development by allowing you to install the exact modules you need. The advantages of NPM are:

* ease of use for developers
* local package installation which helps save on space
* helps reduce the development time

That’s pretty much it, it’s very simple and performs its main function – uploading, storing, sharing, reusing software packages.

### How to Install NPM

NPM should be automatically installed when you install Node.js. To check is you have Node.js installed, run this command in your terminal:

```
node -v
```

If you already have Node.js installed and want to verify whether you also have NPM, run the following command in your terminal:

```
npm -v
```

FYI, npm updates happen more frequently than Node.js, and there are many npm versions out there, so you might want to keep your npm up to date, and possibly even update it right after you installed Node.js. To do that, run the following command:

```
npm install npm@latest -g
```

It might also be a good idea to use a version manager with your Node.js package, e.g. nodist or NVM.

### 🏗️ Architecture and Concepts

NPM follows a client-server architecture:

* 📡 Client: The NPM CLI tool installed on developers' machines
* 🖥️ Server: The NPM registry, a large public database of JavaScript packages

Key concepts I'm well-versed in:

* 📁 package.json: The heart of any Node.js project, defining project metadata and dependencies
* 🔒 package-lock.json: Ensures consistent installs across environments
* 📦 node\_modules: Directory where packages are installed
* 🌳 Dependency tree: Hierarchical structure of project dependencies
* 🔄 Semantic Versioning (SemVer): Version number scheme for packages

### 🖼️ NPM Architecture Diagram

<figure><img src="/files/xFUNhSK9XFxXq4gxl28F" alt=""><figcaption></figcaption></figure>

### 🛠️ NPM Commands

I am proficient in using a wide range of NPM commands for various tasks:

#### 📥 Installation Commands

```bash
# Install all dependencies
npm install

# Install a specific package
npm install lodash

# Install as dev dependency
npm install --save-dev jest

# Install globally
npm install -g typescript

# Install specific version
npm install react@17.0.2
```

#### 📜 Script Commands

I can efficiently manage and use NPM scripts defined in package.json:

```json
{
  "scripts": {
    "start": "node server.js",
    "dev": "next dev",
    "test": "jest",
    "build": "tsc",
    "lint": "eslint .",
    "deploy": "node deploy.js"
  }
}
```

Running these scripts:

```bash
npm run start
npm run dev
npm test
npm run build
npm run lint
npm run deploy
```

#### 🚀 Other Useful Commands

```bash
# Initialize a new project
npm init -y

# Update packages
npm update

# Remove a package
npm uninstall moment

# List installed packages
npm list

# Run security audit
npm audit

# Publish a package
npm publish
```

### 💻 Code Snippets

I can effectively use NPM packages in JavaScript/TypeScript projects. Here are some examples:

#### 🧩 Using a third-party package (lodash)

```tsx
import _ from 'lodash';

const numbers = [1, 2, 3, 4, 5];
const sum = _.sum(numbers);
console.log(`Sum: ${sum}`);

const users = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 28 },
  { name: 'Bob', age: 35 }
];
const sortedUsers = _.sortBy(users, 'age');
console.log('Sorted users:', sortedUsers);
```

#### 🛠️ Creating and publishing an NPM package

1. Create a new directory and initialize:

```bash
mkdir my-awesome-package
cd my-awesome-package
npm init -y
```

1. Create your main file (index.js):

```jsx
// index.js
function greet(name) {
  return `Hello, ${name}!`;
}

module.exports = { greet };
```

1. Update package.json:

```json
{
  "name": "my-awesome-package",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \\"Error: no test specified\\" && exit 1"
  },
  "keywords": ["greeting", "npm", "package"],
  "author": "Your Name",
  "license": "MIT"
}
```

1. Publish the package:

```bash
npm login
npm publish
```

### 🎓 Advanced NPM Skills

* 🔍 Troubleshooting dependency conflicts
* 🔒 Managing package security with npm audit
* 🚀 Optimizing install times with npm ci
* 📊 Analyzing package sizes with npm package-size
* 🔧 Configuring NPM for different environments

My comprehensive understanding of NPM enables me to efficiently manage dependencies, optimize project structures, and streamline development workflows in Node.js environments.


# Yarn

## YARN 🧶

YARN is a fast, reliable, and secure dependency management tool for Node.js. It was developed by Facebook in 2016 as an alternative to npm (Node Package Manager).

### Architecture and Concepts 🏗️

YARN's architecture is designed for efficiency and reliability:

* 📁 **Workspace:** The root directory of your project
* 📄 **package.json:** Defines project dependencies and scripts
* 🔒 **yarn.lock:** Ensures consistent installs across machines
* 📦 **node\_modules:** Directory where packages are installed
* 🌐 **Registry:** Default is npm registry, but can be changed

#### Key Concepts:

* 🔄 **Offline Mode:** Install packages without internet connection
* 🚀 **Parallel Installation:** Faster package installations
* 🔍 **Flat Mode:** Resolves version conflicts efficiently
* 🔐 **Checksums:** Verifies integrity of installed packages

### YARN Architecture Diagram 📊

<figure><img src="/files/zVa8f9e6eEOPa7tvhnR4" alt=""><figcaption></figcaption></figure>

### Common YARN Commands 🖥️

#### Installation:

```bash
npm install -g yarn
```

#### Initialize a new project:

```bash
yarn init
```

#### Add a dependency:

```bash
yarn add [package-name]
yarn add [package-name]@[version]
yarn add [package-name] --dev
```

#### Remove a dependency:

```bash
yarn remove [package-name]
```

#### Install all dependencies:

```bash
yarn install
```

#### Run a script:

```bash
yarn run [script-name]
```

#### Upgrade packages:

```bash
yarn upgrade
yarn upgrade [package-name]
yarn upgrade [package-name]@[version]
```

### Code Snippets 💻

#### Example package.json:

```json
{
  "name": "my-project",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "jest": "^27.0.6"
  },
  "scripts": {
    "start": "node index.js",
    "test": "jest"
  }
}
```

#### Example JavaScript file (index.js):

```jsx
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Example app listening at <http://localhost>:${port}`);
});
```

#### Running the application:

```bash
yarn start
```

Output:

```
Example app listening at <http://localhost:3000>
```

### Deployment Commands 🚀

Deployment commands may vary depending on your hosting platform. Here are some general examples:

#### Build for production:

```bash
yarn build
```

#### Run tests before deployment:

```bash
yarn test
```

#### Start in production mode:

```bash
yarn start:prod
```

Remember to add these scripts to your package.json file:

```json
{
  "scripts": {
    "build": "your-build-command",
    "test": "jest",
    "start:prod": "NODE_ENV=production node index.js"
  }
}
```

### Conclusion 🎉

YARN is a powerful and efficient package manager for Node.js projects. Its architecture and features make it a popular choice for many developers. By understanding its concepts and commands, you can streamline your development process and manage dependencies more effectively.


# Yarn 2 (Berry)

## YARN 2 (Berry) - The Modern Package Manager 🧶

Yarn 2, also known as Berry, is a significant evolution of the original Yarn package manager. It brings improved performance, enhanced security, and new features to JavaScript and Node.js development.

### Architecture and Concepts 🏗️

Yarn 2's architecture is designed for efficiency, reliability, and improved developer experience:

* 📁 **Plug'n'Play (PnP):** A new resolution strategy that replaces node\_modules
* 🔒 **Zero-Installs:** Allows committing dependencies to version control
* 🌐 **Workspaces:** Improved monorepo support
* 🔧 **Constraints:** Enforce rules across your project
* 📦 **Protocols:** Flexible ways to fetch packages

#### Key Concepts:

* 🚀 **Performance:** Faster installs and reduced disk usage
* 🔐 **Security:** Improved package resolution and validation
* 🛠️ **Extensibility:** Plugin system for custom functionality
* 📜 **TypeScript Support:** Better integration with TypeScript projects

### Yarn 2 Architecture Diagram 📊

<figure><img src="/files/lBeleVj2Orq1u1sLxGIq" alt=""><figcaption></figcaption></figure>

### Common Yarn 2 Commands 🖥️

#### Installation:

```bash
npm install -g yarn
yarn set version berry
```

#### Initialize a new project:

```bash
yarn init -2
```

#### Add a dependency:

```bash
yarn add [package-name]
yarn add [package-name]@[version]
yarn add -D [package-name]  # Add as dev dependency
```

#### Remove a dependency:

```bash
yarn remove [package-name]
```

#### Install all dependencies:

```bash
yarn install
```

#### Run a script:

```bash
yarn [script-name]
```

#### Update packages:

```bash
yarn up
yarn up [package-name]
```

### Code Snippets 💻

#### Example package.json:

```json
{
  "name": "my-yarn2-project",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "typescript": "^4.5.4"
  },
  "scripts": {
    "start": "ts-node src/index.ts",
    "build": "tsc",
    "test": "jest"
  }
}
```

#### Example TypeScript file (src/index.ts):

```tsx
import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World from Yarn 2 project!');
});

app.listen(port, () => {
  console.log(`Server running at <http://localhost>:${port}`);
});
```

#### Running the application:

```bash
yarn start
```

Output:

```jsx
Server running at <http://localhost:3000>
```

### Deployment Commands 🚀

Here are some common deployment commands:

#### Build for production:

```bash
yarn build
```

#### Run tests before deployment:

```bash
yarn test
```

#### Start in production mode:

```bash
yarn start:prod
```

Add these scripts to your package.json:

```json
{
  "scripts": {
    "build": "tsc",
    "test": "jest",
    "start:prod": "NODE_ENV=production node dist/index.js"
  }
}
```

### Conclusion 🎉

Yarn 2 (Berry) is a powerful and efficient package manager for Node.js projects. Its innovative features like Plug'n'Play and Zero-Installs provide significant improvements in performance and project management. By leveraging Yarn 2's capabilities, developers can create more efficient, secure, and maintainable JavaScript and TypeScript applications.


# PNPM

## PNPM (Performant NPM) 📦

PNPM is a fast, disk space efficient package manager for Node.js. It was created as an alternative to npm and Yarn, focusing on performance and disk space optimization.

### Architecture and Concepts 🏗️

PNPM's architecture is designed for efficiency and disk space savings:

* 📁 **Content-addressable store:** Packages are stored in a global store, shared across projects
* 🔗 **Symlinks:** Used to create the node\_modules structure
* 📄 **package.json:** Defines project dependencies and scripts
* 🔒 **pnpm-lock.yaml:** Ensures consistent installs across machines
* 📦 **node\_modules:** Directory where packages are symlinked

#### Key Concepts:

* 💾 **Disk Space Efficiency:** Saves disk space by using a single copy of each package version
* 🚀 **Fast Installation:** Efficient algorithm for resolving and linking dependencies
* 🌳 **Non-flat node\_modules:** Prevents phantom dependencies
* 🔄 **Workspace Support:** Manages multiple packages in a single repository

### PNPM Architecture Diagram 📊

<figure><img src="/files/sBd6vBBuwYM7JVpPVuiZ" alt=""><figcaption></figcaption></figure>

### Common PNPM Commands 🖥️

#### Installation:

```bash
npm install -g pnpm
```

#### Initialize a new project:

```bash
pnpm init
```

#### Add a dependency:

```bash
pnpm add [package-name]
pnpm add [package-name]@[version]
pnpm add -D [package-name]  # Add as dev dependency
```

#### Remove a dependency:

```bash
pnpm remove [package-name]
```

#### Install all dependencies:

```bash
pnpm install
```

#### Run a script:

```bash
pnpm run [script-name]
```

#### Update packages:

```bash
pnpm update
pnpm update [package-name]
```

### Code Snippets 💻

#### Example package.json:

```json
{
  "name": "my-pnpm-project",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "typescript": "^4.5.4"
  },
  "scripts": {
    "start": "ts-node src/index.ts",
    "build": "tsc",
    "test": "jest"
  }
}
```

#### Example TypeScript file (src/index.ts):

```tsx
import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World from PNPM project!');
});

app.listen(port, () => {
  console.log(`Server running at <http://localhost>:${port}`);
});
```

#### Running the application:

```bash
pnpm start
```

Output:

```jsx
Server running at <http://localhost:3000>
```

### Deployment Commands 🚀

Here are some common deployment commands:

#### Build for production:

```bash
pnpm run build
```

#### Run tests before deployment:

```bash
pnpm test
```

#### Start in production mode:

```bash
pnpm start:prod
```

Add these scripts to your package.json:

```json
{
  "scripts": {
    "build": "tsc",
    "test": "jest",
    "start:prod": "NODE_ENV=production node dist/index.js"
  }
}
```

#### Improved speed[​](https://refine.dev/blog/pnpm-vs-npm-and-yarn/#improved-speed) <a href="#improved-speed" id="improved-speed"></a>

The speed of package installation with pnpm is significantly better than npm and yarn. If you look at the below benchmark tests, you can see that pnpm performs better in most cases thano npm and yarn.

<figure><img src="https://refine.ams3.cdn.digitaloceanspaces.com/blog/2022-10-13-pnpm-post/pnpm-image-4.png" alt=""><figcaption></figcaption></figure>

### Conclusion 🎉

PNPM is a powerful and efficient package manager for Node.js projects. Its unique architecture provides significant disk space savings and improved performance. By leveraging PNPM's features and commands, you can optimize your development workflow and manage dependencies more effectively.

pnpm has overall performed much better than npm and yarn. No wonder giant tech companies like Vue3, Prism, and Microsoft are quickly adopting pnpm.


# BUN

## BUN - The Modern JavaScript Runtime 🚀

Bun is a fast all-in-one JavaScript runtime, bundler, transpiler, and package manager. It's designed as a drop-in replacement for Node.js, offering significant performance improvements and a streamlined developer experience.

### Architecture and Concepts 🏗️

Bun's architecture is built for speed and efficiency:

* ⚡ **JavaScriptCore Engine:** Uses Apple's JavaScriptCore for faster execution
* 🔄 **Built-in Bundler:** Native bundling capabilities for quicker builds
* 📦 **Package Manager:** Integrated package management with npm compatibility
* 🔧 **Native Modules:** Written in Zig for low-level performance
* 🌐 **Web Standard APIs:** Implements standard web APIs for better compatibility

#### Key Concepts:

* 🚀 **Speed:** Significantly faster than Node.js in many operations
* 🔌 **Node.js Compatibility:** Runs most Node.js applications out of the box
* 🛠️ **All-in-One Tool:** Bundler, transpiler, and package manager in one
* 📜 **TypeScript Support:** Native TypeScript and JSX support without additional tools

### Bun Architecture Diagram 📊

<figure><img src="/files/tSsz7cSPzuoRePyidT0R" alt=""><figcaption></figcaption></figure>

### Common Bun Commands 🖥️

#### Installation:

```bash
curl -fsSL <https://bun.sh/install> | bash
```

#### Initialize a new project:

```bash
bun init
```

#### Add a dependency:

```bash
bun add [package-name]
bun add -d [package-name]  # Add as dev dependency
```

#### Remove a dependency:

```bash
bun remove [package-name]
```

#### Install all dependencies:

```bash
bun install
```

#### Run a script:

```bash
bun run [script-name]
```

#### Start a development server:

```bash
bun --hot run index.ts
```

### Code Snippets 💻

#### Example package.json:

```json
{
  "name": "my-bun-project",
  "version": "1.0.0",
  "module": "index.ts",
  "type": "module",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "bun-types": "latest"
  },
  "scripts": {
    "start": "bun run index.ts",
    "dev": "bun --hot run index.ts",
    "build": "bun build ./index.ts --outdir ./dist"
  }
}
```

#### Example TypeScript file (index.ts):

```tsx
import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World from Bun!');
});

app.listen(port, () => {
  console.log(`Server running at <http://localhost>:${port}`);
});
```

#### Running the application:

```bash
bun run start
```

Output:

```jsx
Server running at <http://localhost:3000>
```

### Deployment Commands 🚀

Here are some common deployment commands for Bun:

#### Build for production:

```bash
bun run build
```

#### Run tests:

```bash
bun test
```

#### Start in production mode:

```bash
NODE_ENV=production bun run index.ts
```

Add these scripts to your package.json:

```json
{
  "scripts": {
    "build": "bun build ./index.ts --outdir ./dist",
    "test": "bun test",
    "start:prod": "NODE_ENV=production bun run ./dist/index.js"
  }
}
```

### Conclusion 🎉

Bun is a powerful and efficient JavaScript runtime and toolkit that offers significant performance improvements over traditional Node.js setups. Its all-in-one approach simplifies the development workflow, making it an attractive option for modern JavaScript and TypeScript projects. By leveraging Bun's features and commands, developers can create faster, more efficient applications with ease.


# Commands cheatsheet

If you want to get rid off all those different commands on each package manager I higly recommened to install [SWPM](https://www.npmjs.com/package/swpm) and say good bye to package manager confussion. It will do all the commands translation for you.

### Package Commands

<table><thead><tr><th width="142">command</th><th>npm</th><th>yarn</th><th>yarn (berry)</th><th>pnpm</th><th>bun</th></tr></thead><tbody><tr><td>clean cache</td><td><code>npm cache clean</code></td><td><code>yarn cache clean</code></td><td><code>yarn cache clean</code></td><td>N/A</td><td><code>bun pm cache rm</code></td></tr><tr><td>install from <code>package.json</code></td><td><code>npm install</code></td><td><code>yarn [install]</code></td><td><code>yarn [install]</code></td><td><code>pnpm install</code></td><td><code>bun install</code></td></tr><tr><td>don't read or generate a lockfile</td><td><code>npm install --no-package-lock</code></td><td><code>yarn install --no-lockfile</code></td><td><code>yarn install --no-lockfile</code></td><td>N/A</td><td><code>bun install --no-save</code></td></tr><tr><td>don't generate a lockfile</td><td></td><td><code>yarn install --pure-lockfile</code></td><td><code>yarn install --pure-lockfile</code></td><td></td><td>N/A</td></tr><tr><td>lockfile is not updated</td><td><code>npm ci</code></td><td><code>yarn install --frozen-lockfile</code></td><td><code>yarn install --immutable</code></td><td><code>pnpm install --frozen-lockfile</code></td><td><code>bun install --frozen-lockfile</code></td></tr><tr><td>add package</td><td><code>npm install &#x3C;package> [--location=global]</code></td><td><code>yarn [global] add &#x3C;package></code></td><td><code>yarn [global] add &#x3C;package></code></td><td><code>pnpm add &#x3C;package> [--global]</code></td><td><code>bun add &#x3C;package> [--global]</code></td></tr><tr><td>add package as <code>dependencies</code></td><td><code>npm install &#x3C;package></code></td><td><code>yarn add &#x3C;package></code></td><td><code>yarn add &#x3C;package></code></td><td><code>pnpm add &#x3C;package></code></td><td><code>bun add &#x3C;package></code></td></tr><tr><td>add package as <code>devDependencies</code></td><td><code>npm install &#x3C;package> --save-dev</code></td><td><code>yarn add &#x3C;package> --dev</code></td><td><code>yarn add &#x3C;package> --dev</code></td><td><code>pnpm add &#x3C;package> --save-dev</code></td><td><code>bun add &#x3C;package> --dev</code></td></tr><tr><td>add package as <code>optionalDependencies</code></td><td><code>npm install &#x3C;package> --save-optional</code></td><td><code>yarn add &#x3C;package> --optional</code></td><td><code>yarn add &#x3C;package> --optional</code></td><td><code>pnpm add &#x3C;package> --save-optional</code></td><td><code>bun add &#x3C;package> --optional</code></td></tr><tr><td>add package as <code>peerDependencies</code></td><td><code>npm install &#x3C;package> --save-peer</code></td><td><code>yarn add &#x3C;package> --peer</code></td><td><code>yarn add &#x3C;package> --peer</code></td><td><code>pnpm add &#x3C;package> --save-peer</code></td><td>N/A</td></tr><tr><td>add exact version</td><td><code>npm install &#x3C;package> --save-exact</code></td><td><code>yarn add &#x3C;package> --exact</code></td><td><code>yarn add &#x3C;package> --exact</code></td><td><code>pnpm add &#x3C;package> --save-exact</code></td><td><code>bun add &#x3C;package> --exact</code></td></tr><tr><td>remove package</td><td><code>npm uninstall &#x3C;package> [--location=global]</code></td><td><code>yarn [global] remove &#x3C;package></code></td><td><code>yarn [global] remove &#x3C;package></code></td><td><code>pnpm uninstall &#x3C;package> [--global]</code></td><td><code>bun remove [&#x3C;package>] [--global]</code></td></tr><tr><td>remove package as <code>dependencies</code></td><td><code>npm uninstall &#x3C;package></code></td><td><code>yarn remove &#x3C;package></code></td><td><code>yarn remove &#x3C;package></code></td><td><code>pnpm uninstall &#x3C;package></code></td><td><code>bun remove &#x3C;package></code></td></tr><tr><td>remove package as <code>devDependencies</code></td><td><code>npm uninstall &#x3C;package> --save-dev</code></td><td><code>yarn remove &#x3C;package> --dev</code></td><td><code>yarn remove &#x3C;package> --dev</code></td><td><code>pnpm uninstall &#x3C;package> --save-dev</code></td><td><code>bun remove &#x3C;package> --dev</code></td></tr><tr><td>remove package as <code>optionalDependencies</code></td><td><code>npm uninstall &#x3C;package> --save-optional</code></td><td><code>yarn remove &#x3C;package> --optional</code></td><td><code>yarn remove &#x3C;package> --optional</code></td><td><code>pnpm uninstall &#x3C;package> --save-optional</code></td><td><code>bun remove &#x3C;package> --optional</code></td></tr><tr><td>remove package as <code>peerDependencies</code></td><td><code>npm uninstall &#x3C;package> --save-peer</code></td><td><code>yarn remove &#x3C;package> --peer</code></td><td><code>yarn remove &#x3C;package> --peer</code></td><td><code>pnpm uninstall &#x3C;package> --save-peer</code></td><td>N/A</td></tr><tr><td>update package (no <code>package.json</code>)</td><td><code>npm update [&#x3C;package>] [--location=global]</code></td><td><code>yarn [global] upgrade [&#x3C;package>]</code></td><td><code>yarn [global] semver up [&#x3C;package>]</code></td><td><code>pnpm update [&#x3C;package>] [--global]</code></td><td>N/A</td></tr><tr><td>upgrade package on <code>package.json</code></td><td><code>npm install &#x3C;package>@latest [--location=global]</code></td><td><code>yarn [global] upgrade &#x3C;package> --latest</code></td><td><code>yarn [global] up &#x3C;package></code></td><td><code>pnpm update &#x3C;package> --latest [--global]</code></td><td>N/A</td></tr><tr><td>upgrade interactive</td><td>N/A</td><td><code>yarn upgrade-interactive</code></td><td><code>yarn upgrade-interactive</code></td><td><code>pnpm update --interactive</code></td><td>N/A</td></tr><tr><td>list all package at the top level</td><td><code>npm list --depth 0 [--location=global]</code></td><td><code>yarn [global] list --depth 0</code></td><td><code>yarn [global] list --depth 0</code></td><td><code>pnpm list --depth 0 [--global]</code></td><td><code>bun pm ls</code></td></tr><tr><td>audit vulnerable dependencies</td><td><code>npm audit [fix]</code></td><td><code>yarn audit</code></td><td><code>yarn audit</code></td><td><code>pnpm audit [--fix]</code></td><td></td></tr></tbody></table>

### Shared Commands

Use the same command structure between package managers.

| command                            | npm                                            | yarn                                         | yarn (berry)                                    | pnpm                                         | bun                        |
| ---------------------------------- | ---------------------------------------------- | -------------------------------------------- | ----------------------------------------------- | -------------------------------------------- | -------------------------- |
| init or create                     | `npm init`                                     | `yarn init`                                  | `yarn init`                                     | `pnpm init`                                  | `bun init`                 |
| login/logout                       | `npm <login or logout>`                        | `yarn <login or logout>`                     | `yarn <login or logout>`                        | `pnpm <login or logout>`                     | TBA                        |
| run scripts                        | `npm run <script>`                             | `yarn run <script>`                          | `yarn run <script>`                             | `pnpm [run] <script>`                        | `bun run <script>`         |
| run test                           | `npm test`                                     | `yarn test`                                  | `yarn test`                                     | `pnpm test`                                  | `bun test`                 |
| crate bundle package               | `npm build`                                    | `yarn build`                                 | `yarn build`                                    | `pnpm build`                                 | `bun build`                |
| publish                            | `npm publish`                                  | `yarn publish`                               | `yarn npm publish`                              | `pnpm publish`                               | TBA                        |
| unpublish                          | `npm unpublish <package>[@#.#.#]`              | `yarn unpublish <package>[@#.#.#]`           | `yarn unpublish <package>[@#.#.#]`              | `pnpm unpublish <package>[@#.#.#]`           | TBA                        |
| deprecate                          | `npm deprecate <package>[@#.#.#] <message>`    | `yarn deprecate <package>[@#.#.#] <message>` | `yarn deprecate <package>[@#.#.#] <message>`    | `pnpm deprecate <package>[@#.#.#] <message>` | TBA                        |
| config list                        | `npm config list`                              | `yarn config list`                           | `yarn config list`                              | `pnpm config list`                           | TBA                        |
| config `--save-default` as default | `npm config set save-exact true`               | `yarn config set save-exact true`            | `yarn config set save-exact true`               | `pnpm config set save-exact true`            | TBA                        |
| config `~` as default instead `^`  | `npm config set save-prefix '~'`               | `yarn config set save-prefix '~'`            | `yarn config set save-prefix '~'`               | `pnpm config set save-prefix '~'`            | TBA                        |
| list outdated packages             | `npm outdated [<package>] [--location=global]` | `yarn [global] [<package>] outdated`         | `yarn [global] [<package>] upgrade-interactive` | `pnpm outdated [<package>] [--global]`       | TBA                        |
| link local package                 | `npm link [<folder>]`                          | `yarn link [<folder>]`                       | `yarn link [<folder>]`                          | `pnpm link [<folder>]`                       | `bun link [<folder>]`      |
| unlink local package               | \`npm unlink \[\<folder\\                      | package> --no-save]\`                        | \`yarn unlink \[\<folder\\                      | package>]\`                                  | \`yarn unlink \[\<folder\\ |

### Run Remotely

Run a command without installing it.

| command     | npm                      | yarn                 | yarn (berry)         | pnpm                 | bun              |
| ----------- | ------------------------ | -------------------- | -------------------- | -------------------- | ---------------- |
| run package | {% raw %}`npx <package>` | `yarn dlx <package>` | `yarn dlx <package>` | `pnpm dlx <package>` | `bunx <package>` |

### CLI documentation

* [npm](https://docs.npmjs.com/cli/v8/commands)
* [yarn](https://classic.yarnpkg.com/en/docs/cli/)
* [pnpm](https://pnpm.io/cli/install)
* [bun](https://github.com/oven-sh/bun#using-bun-as-a-package-manager)


# API Providers

### 1. Web3 SDKs 🛠️

Web3 SDKs (Software Development Kits) are comprehensive toolkits that simplify the process of building decentralized applications (dApps) and interacting with blockchain networks. These SDKs provide developers with pre-built functions, libraries, and tools to streamline Web3 development.

#### Core Concepts:

* &#x20;🖥️**Blockchain Interaction:** Simplified methods to connect to various blockchain networks
* 🔧**Smart Contract Integration:** Tools for deploying, interacting with, and testing smart contracts
* 👛**Wallet Management:** Functions to handle cryptocurrency wallets and transactions
* &#x20;🔔**Event Handling:** Mechanisms to listen and respond to blockchain events
* 🔢 **Data encoding/decoding** **:** Utilities for handling blockchain-specific data formats

#### Structure:

<figure><img src="/files/viv5Yi3tZ19pj3kqZfPI" alt=""><figcaption></figcaption></figure>

#### Advantages:

* ✅ Abstraction of complex blockchain operations
* ✅ Faster development process
* ✅ Standardized development practices

#### Disadvantages:

* ❌ Learning curve for specific SDK features
* ❌ Potential limitations based on SDK capabilities

#### Popular Web3 SDKs

* **Web3.js:** A collection of libraries for interacting with Ethereum nodes
* **Ethers.js:** A complete Ethereum wallet implementation and utilities in JavaScript
* **Truffle:** A development environment, testing framework, and asset pipeline for Ethereum
* **Hardhat:** An Ethereum development environment for professionals
* **Moralis:** A cross-chain SDK for building dApps quickly

#### Code Snippet (Using Web3.js):

```jsx
const Web3 = require('web3');
const web3 = new Web3('<https://mainnet.infura.io/v3/YOUR-PROJECT-ID>');

async function getBalance(address) {
    const balance = await web3.eth.getBalance(address);
    console.log(web3.utils.fromWei(balance, 'ether'), 'ETH');
}

getBalance('0x742d35Cc6634C0532925a3b844Bc454e4438f44e');
```

### 2. Web3 API Providers  🌐

Web3 API providers are essential services that offer developers access to blockchain networks and related functionalities. They act as intermediaries between decentralized applications (dApps) and blockchain networks, simplifying the process of interacting with and retrieving data from these networks.&#x20;

Here's a more in-depth look at the main types of Web3 API providers:

#### 1. Node Providers 🖥️

Node providers offer direct access to blockchain networks by maintaining full nodes on behalf of developers.

* **Examples:** Infura, Alchemy, QuickNode
* **Features:** RPC endpoints, transaction broadcasting, smart contract interaction
* **Benefits:** Reduced infrastructure costs, high availability, multi-chain support

#### 2. Data Indexers 📊

Data indexers specialize in organizing and indexing blockchain data, making it easily queryable for developers.

* **Examples:** The Graph, Covalent
* **Features:** Custom data queries, historical data analysis, event tracking
* **Benefits:** Faster data retrieval, complex query support, reduced backend complexity

#### 3. NFT APIs 🖼️

NFT APIs focus on Non-Fungible Token related operations and data retrieval.

* **Examples:** OpenSea API, Rarible API
* **Features:** NFT metadata retrieval, ownership verification, marketplace interactions
* **Benefits:** Simplified NFT integration, access to marketplace data

#### 4. DeFi APIs 💹

DeFi APIs provide data and functionality related to various Decentralized Finance protocols and services.

* **Examples:** 0x API, 1inch API
* **Features:** Token swaps, liquidity pool data, yield farming information
* **Benefits:** Easy integration of DeFi features, access to real-time financial data

#### 5. Identity and Authentication APIs 🔐

These APIs handle Web3 identity solutions and decentralized authentication services.

* **Examples:** Civic, Spruce ID
* **Features:** Decentralized identity verification, login with Ethereum
* **Benefits:** Enhanced security, user-controlled identity

#### 6. Oracle APIs 🔮

Oracle APIs provide external data to smart contracts, bridging the gap between on-chain and off-chain data.

* **Examples:** Chainlink, Band Protocol
* **Features:** Price feeds, random number generation, off-chain data integration
* **Benefits:** Access to real-world data, enhanced smart contract functionality

By leveraging these diverse types of Web3 API providers, developers can create robust, feature-rich decentralized applications while focusing on core business logic rather than infrastructure management. 🚀

#### Structure:

<figure><img src="/files/1F1cIPjZA9oUMHbRW7ue" alt=""><figcaption></figcaption></figure>

#### Advantages:

* ✅ Reduced infrastructure costs
* ✅ Increased reliability and uptime
* ✅ Access to specialized services

#### Disadvantages:

* ❌ Vendor lock-in risks
* ❌ Potential single point of failure

#### Code Snippet (Using Alchemy SDK):

```jsx
const { Alchemy, Network } = require("alchemy-sdk");

const config = {
    apiKey: "YOUR-ALCHEMY-API-KEY",
    network: Network.ETH_MAINNET,
};
const alchemy = new Alchemy(config);

async function getLatestBlock() {
    const latestBlock = await alchemy.core.getBlockNumber();
    console.log("The latest block number is", latestBlock);
}

getLatestBlock();
```

By leveraging these Web3 API providers, developers can focus on creating innovative features and user experiences in their dApps while relying on established infrastructure for blockchain interactions and data management. This approach significantly reduces development time and complexity, allowing for more rapid innovation in the Web3 space.


# Alchemy


# Telegram Bot


# CoinMarket


# Thirdweb


# Infura


# Moralis


# DevOps/Infrastructure

### 1. Docker 🐳

Docker is a platform for developing, shipping, and running applications in containers.

#### Key Concepts:

* Containers: Lightweight, standalone executable packages
* Images: Read-only templates used to create containers
* Dockerfile: Script to build Docker images
* Docker Hub: Cloud-based registry for Docker images

#### Architecture:

<figure><img src="/files/TFa2XTK8nbUYVbwxf3GV" alt=""><figcaption></figcaption></figure>

#### Example Dockerfile:

```
FROM node:14
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
```

### 2. Kubernetes ☸️

Kubernetes is an open-source container orchestration platform for automating deployment, scaling, and management of containerized applications.

#### Key Concepts:

* Pods: Smallest deployable units in Kubernetes
* Nodes: Worker machines in a Kubernetes cluster
* Clusters: Set of nodes that run containerized applications
* Services: Abstract way to expose applications running on pods

#### Architecture:

<figure><img src="/files/AkihcCMdc1pWthHcoCBg" alt=""><figcaption></figcaption></figure>

#### Example Kubernetes Deployment:

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
```

### 3. CI/CD 🔄

Continuous Integration and Continuous Deployment (CI/CD) is a method to frequently deliver apps to customers by introducing automation into the stages of app development.

#### Key Concepts:

* Continuous Integration: Merging code changes frequently
* Continuous Delivery: Automatically preparing code for release
* Continuous Deployment: Automatically releasing to production
* Pipelines: Automated processes for building, testing, and deploying

#### CI/CD Pipeline:

<figure><img src="/files/ooOJYveEd0AXgHtRxppT" alt=""><figcaption></figcaption></figure>

#### Example GitLab CI/CD Configuration:

```yaml
stages:
  - build
  - test
  - deploy

build:
  stage: build
  script:
    - npm install
    - npm run build

test:
  stage: test
  script:
    - npm run test

deploy:
  stage: deploy
  script:
    - npm run deploy
  only:
    - master
```

### 4. Docker Swarm 🐝

Docker Swarm is a native clustering and orchestration solution for Docker.

#### Key Concepts:

* Nodes: Docker hosts participating in the swarm
* Services: Definition of tasks to execute on nodes
* Tasks: Docker containers executing commands
* Load Balancing: Distributing service containers across nodes

#### Architecture:

<figure><img src="/files/ts9cE6mNBlzWBgXAv42y" alt=""><figcaption></figcaption></figure>

#### Example Docker Swarm Service:

```bash
docker service create --name my-web-server \\
                      --replicas 3 \\
                      --publish 80:80 \\
                      nginx
```

The core of modern DevOps and Infrastructure management, enabling efficient development, deployment, and scaling of applications. 🚀


# Docker

## Docker: A Platform for Containerization

**Docker** is a popular platform that simplifies the process of building, shipping, and running applications in containers. It provides a standardized way to package and distribute applications, making it easier to deploy and manage them across different environments.

### What are we using docker for?

Docker let’s you do a lot of things.It let’s you `containerise` your applications.It let’s you run other people’s `code + packages` in your machine.It let’s you run common software packages inside a `container` (For eg - Mongo, Postgres etc)&#x20;

<figure><img src="/files/92YIj5Q7PqKrQDxnhxJB" alt=""><figcaption></figcaption></figure>

### Where can we get packages from?

Just like you can push your `code` to Github/Gitlab.You can push `images` to `docker registries`&#x20;

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F5da9bacc-13d0-4461-a847-c4ca38ceb939%2FScreenshot_2024-02-21_at_10.34.55_AM.png?table=block&#x26;id=d4e2900d-b6f8-491e-b89d-04d57581f47e&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## Common commands to know

1. docker run
2. docker ps
3. docker kill

### Running an image

**1. Running a simple image**

Let’s say you wan’t to run MongoDB locally <https://hub.docker.com/_/mongo>

```javascript
docker run mongo
```

You will notice you can’t open it in `MongoDB Compass` .

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F80528531-81d4-4447-91fb-cd39313f4835%2FScreenshot_2024-02-21_at_10.38.43_AM.png?table=block&#x26;id=e92e39a4-51e4-4208-ae6f-a21860e1b6af&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

**Adding a port mapping**

The reason is that you haven’t added a `port mapping`

```javascript
docker run  -p 27017:27017 mongo
```

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F4601c1cd-5b4c-41c9-826b-93f33f9d4f7f%2FScreenshot_2024-02-21_at_10.41.02_AM.png?table=block&#x26;id=5f8e22c8-f13b-46df-ac13-255708e0f54a&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

**Starting in detached mode**

Adding `-d` will ensure it starts in the background

```javascript
docker run -d -p 27017:27017 mongo
```

Inspecting a container

```javascript
docker ps
```

This will show you all the containers you are running.

#### Stopping a container

```javascript
docker kill <container_id>
```

Will stop the container that you are running In the end, this is the flow of commands -

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F2c747f8e-458e-4500-bbbf-4cf7ee7acf40%2FScreenshot_2024-02-21_at_10.43.18_AM.png?table=block&#x26;id=ac6834b0-fbab-4d50-ab3e-73093b99d662&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## Common packages

&#x20;Mongo

```javascript
docker run -d -p 27017:27017 mongo
```

&#x20;Postgres

```javascript
docker run -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres
```

The connection string for this postgres would be

```javascript
postgresql://postgres:mysecretpassword@localhost:5432/postgres
```

<details>

<summary>Code to test it out</summary>

```javascript
// Import the pg library
const { Client } = require('pg');

// Define your connection string (replace placeholders with your actual data)
const connectionString = 'postgresql://postgres:mysecretpassword@localhost:5432/postgres';

// Create a new client instance with the connection string
const client = new Client({
  connectionString: connectionString
});

// Connect to the database
client.connect(err => {
  if (err) {
    console.error('connection error', err.stack);
  } else {
    console.log('connected to the database');
  }
});

// Run a simple query (Example: Fetching the current date and time from PostgreSQL)
client.query('SELECT NOW()', (err, res) => {
  if (err) {
    console.error(err);
  } else {
    console.log(res.rows[0]);
  }

  // Close the connection
  client.end();
});
```

</details>

#### Key Concepts

* **Containers:** A container is a lightweight, standalone unit that packages an application and its dependencies into a single, portable artifact. It includes everything the application needs to run, from the operating system to libraries and configuration settings.
* **Images:** Docker images are read-only templates that serve as the basis for creating containers. They contain the application code, dependencies, and configuration files.
* **Dockerfile:** A Dockerfile is a text document that contains instructions for building a Docker image. It specifies the base image, dependencies, and commands needed to create the container.

#### Benefits of Docker

* **Portability:** Containers can be easily moved and run on different environments, from development machines to production servers.
* **Efficiency:** Containers are lightweight and start up quickly, making them ideal for microservices architectures.
* **Isolation:** Each container runs in its own isolated environment, preventing conflicts between applications.
* **Scalability:** Docker makes it easy to scale applications horizontally by adding more containers.
* **Consistency:** Docker ensures that applications run consistently across different environments, reducing the risk of errors.

#### How Docker Works

1. **Create a Dockerfile:** Define the instructions for building your container image in a Dockerfile.
2. **Build the Image:** Use the `docker build` command to create the image from the Dockerfile.
3. **Run the Container:** Use the `docker run` command to start a container based on the image.
4. **Manage Containers:** Use Docker commands to start, stop, restart, and remove containers.

#### Use Cases for Docker

* **Microservices Architecture:** Docker is ideal for building and deploying microservices applications, as it allows you to package each microservice into its own container.
* **Continuous Integration/Continuous Deployment (CI/CD):** Docker can be used to automate the building, testing, and deployment of applications.
* **Application Development:** Developers can use Docker to create isolated development environments, ensuring that their code runs consistently.
* **Cloud Deployment:** Docker can be used to deploy applications to cloud platforms like AWS, Azure, and GCP(google cloud provider).

In summary, Docker is a powerful tool for modern application development and deployment. By providing a standardized way to package and distribute applications, Docker simplifies the development process and improves portability, efficiency, and scalability.

**Windows:**

1. **Download Docker Desktop:** Visit the official Docker website (<https://www.docker.com/>) and download the latest Docker Desktop for Windows installer.
2. **Install Docker Desktop:** Double-click the installer and follow the on-screen instructions. By default, Docker Desktop will install WSL2 for optimal performance.
3. **Verify Installation:** Open a command prompt or PowerShell and run the following command:Bash

   ```
   docker run hello-world
   ```

   If Docker is installed correctly, you should see a message indicating a successful container run.
4. if you want to start container

`docker run image`

**macOS:**

1. **Download Docker Desktop:** Visit the official Docker website (<https://www.docker.com/>) and download the latest Docker Desktop for macOS installer.
2. **Install Docker Desktop:** Double-click the installer and follow the on-screen instructions.
3. **Verify Installation:** Open a Terminal and run the following command:Bash

   ```
   docker run hello-world
   ```

   If Docker is installed correctly, you should see a message indicating a successful container run.

**Additional Tips:**

* **Check for Updates:** Regularly update Docker Desktop to ensure you have the latest features and security fixes.
* **Configure WSL2 (Windows only):** If you're using WSL2, ensure it's enabled and configured correctly. You can find instructions on the Docker documentation.
* **Troubleshoot Issues:** If you encounter any problems, refer to the Docker documentation or community forums for troubleshooting tips.
* **Consider Docker Desktop Alternatives:** While Docker Desktop is a popular choice, there are other options available, such as Docker Toolbox for older Windows systems or standalone Docker installations on both Windows and macOS.

By following these steps and considering the additional tips, you should be able to successfully install Docker on your Windows or macOS system and start using it for containerization.

### Common Docker Commands

\
[**https://github.com/shaikhshahbaz4022/Docker**](https://github.com/shaikhshahbaz4022/Docker)

Here are some of the most frequently used Docker commands:

#### Image Management

* **`docker pull <image_name>:<tag>`:** Pulls an image from a Docker registry (e.g., Docker Hub).
* **`docker push <image_name>:<tag>`:** Pushes an image to a Docker registry.
* **`docker build -t <image_name>:<tag> .`:** Builds an image from a Dockerfile in the current directory.
* **`docker images`:** Lists all images on your system.
* **`docker rmi <image_name>:<tag>`:** Removes an image.

#### Container Management

* **`docker run <image_name>:<tag>`:** Creates and starts a container from an image.
* **`docker ps`:** Lists running containers.
* **`docker ps -a`:** Lists all containers, including stopped ones.
* **`docker   start <container_id>`:** Starts a stopped container.
* **`docker stop <container_id>`:** Stops a running container.
* **`docker restart <container_id>`:** Restarts a container.
* **`docker rm <container_id>`:** Removes a container.
* **`docker exec -it <container_id> <command>`:** Executes a command inside a running container.

#### Network Management

* **`docker network create <network_name>`:** Creates a new network.
* **`docker network ls`:** Lists all networks.
* **`docker network rm <network_name>`:** Removes a network.

#### Volume Management

* **`docker volume create <volume_name>`:** Creates a new volume.
* **`docker volume ls`:** Lists all volumes.
* **`docker volume rm <volume_name>`:** Removes a volume.

#### Other Commands

* **`docker compose up`:** Starts multiple containers defined in a `docker-compose.yml` file.
* **`docker-machine ls`:** Lists Docker machines (remote Docker hosts).
* **`docker login`:** Logs in to a Docker registry.

**Here are some key reasons why developers use Docker:**

* **Portability:** Docker containers can be run on any system that supports Docker, making it easy to move applications between different environments (development, testing, production).
* **Consistency:** Docker ensures that applications run consistently across different environments, reducing the risk of errors due to differences in configuration or dependencies.
* **Efficiency:** Containers are lightweight and start up quickly, making them ideal for microservices architectures and other applications that require fast deployment and scaling.
* **Isolation:** Each container runs in its own isolated environment, preventing conflicts between applications.
* **Scalability:** Docker makes it easy to scale applications horizontally by adding or removing containers as needed.
* **Automation:** Docker can be integrated with continuous integration/continuous deployment (CI/CD) pipelines to automate the building, testing, and deployment of applications.

**Docker is used for various purposes, including:**

* **Development:** Creating isolated development environments for different projects or teams.
* **Testing:** Running automated tests in consistent environments.
* **Deployment:** Deploying applications to production servers.
* **Microservices Architecture:** Building and managing microservices-based applications.
* **Cloud Deployment:** Deploying applications to cloud platforms like AWS, Azure, and GCP.

**According to surveys, Docker is widely used by developers:**

* A significant majority of developers use Docker for application development and deployment.
* Docker is particularly popular for microservices architectures and cloud-native applications.

In conclusion, Docker is a valuable tool for developers who want to build, ship, and run applications efficiently and consistently. It offers numerous benefits, including portability, consistency, efficiency, isolation, scalability, and automation.


# Kubernetes

## Kubernetes: A Container Orchestration Platform

**Kubernetes** is an open-source platform for automating the deployment, scaling, and management of containerized applications. It provides a declarative way to define the desired state of your application, and Kubernetes takes care of the underlying infrastructure to make it happen. &#x20;

**Key differences between Docker and Kubernetes:**

* **Purpose:** Docker is a container runtime that allows you to create and run individual containers. Kubernetes, on the other hand, is a platform for managing multiple containers at scale. &#x20;
* **Scope:** Docker focuses on the creation and management of individual containers, while Kubernetes orchestrates entire clusters of containers. &#x20;
* **Features:** Kubernetes provides advanced features like service discovery, load balancing, secrets management, and self-healing, making it suitable for complex applications. &#x20;

#### Common Kubernetes Commands

* **`kubectl get pods`:** Lists all running pods. &#x20;
* **`kubectl run <name> --image=<image_name>`:** Deploys a new pod. &#x20;
* **`kubectl get services`:** Lists all services.
* **`kubectl expose deployment <deployment_name> --type=NodePort`:** Exposes a deployment as a NodePort service. &#x20;
* **`kubectl apply -f <manifest_file>`:** Applies a Kubernetes manifest file. &#x20;
* **`kubectl delete <resource_type> <name>`:** Deletes a Kubernetes resource.

#### Use Cases for Kubernetes

* **Microservices Architecture:** Kubernetes is ideal for managing complex microservices-based applications. &#x20;
* **Cloud-Native Applications:** It provides the infrastructure for building and deploying cloud-native applications. &#x20;
* **Large-Scale Applications:** Kubernetes can handle large-scale applications with thousands of containers. &#x20;
* **Continuous Delivery:** Kubernetes can be integrated with CI/CD pipelines for automated deployments.

### Starting docker

ensurae docker desktop is running&#x20;

```
docker run hello-world
choco install kind
kind --version
docker info
kind create cluster --name local
docker ps
```

&#x20; after this all command you can get local-control-plane that is help to start master node

after this you have to add .yml file with name of master and worker node what you have

**Single node setup**

* Create a 1 node cluster

```javascript
kind create cluster --name local
```

* Check the docker containers you have running

```javascript
docker ps
```

* without docker kubernetes install \
  `docker run -p 3000:80 nginx`
* You will notice a single container running (control-pane)
* Delete the cluster

```javascript
kind delete cluster -n local
```

**Multi node setup**

* Create a `clusters.yml` file

```javascript
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
- role: worker
```

* Create the node setup

```javascript
 kind create cluster --config clusters.yml --name local
```

* Check docker containers

```javascript
docker ps
```

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F6777a996-53c8-426f-a40e-86e16202f1df%2FScreenshot_2024-06-01_at_5.24.54_AM.png?table=block&#x26;id=95959b33-dce8-4efc-b679-de5e53cbbba9&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

&#x20;Now you have a node cluster running locally

#### Using minikube

* Install minikube - <https://minikube.sigs.k8s.io/docs/start/?arch=%2Fmacos%2Fx86-64%2Fstable%2Fbinary+download>
* Start a k8s cluster locally

```javascript
minikube start
```

* Run `docker ps` to see the single node setup

&#x20;Kubernetes API

The master node (control pane) exposes an API that a developer can use to start pods.

**Try the API**

* Run `docker ps` to find where the control pane is running

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fed848804-79a9-4232-8f50-9ff4cfaa919c%2FScreenshot_2024-06-01_at_5.32.21_AM.png?table=block&#x26;id=93fba35b-e982-4bd5-a65f-f9cb90207f11&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

* Try hitting various endpoints on the API server - <https://127.0.0.1:50949/api/v1/namespaces/default/pods>

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F80b0d641-1105-4898-a2b3-d57c642f21ed%2FScreenshot_2024-06-01_at_5.31.04_AM.png?table=block&#x26;id=2059e490-aec5-4295-b86b-5b9a0b49273c&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

&#x20;Kubernetes API server does authentication checks and prevents you from getting in.All of your authorization credentials are stored by `kind` in \~/.kube/config

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F43b9c30e-b0ed-4455-8c86-3acb3779ddac%2FScreenshot_2024-06-01_at_5.36.03_AM.png?table=block&#x26;id=1b7ff330-74c5-43b8-a25a-ed8862e91c74&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## kubectl

`kubectl` is a command-line tool for interacting with Kubernetes clusters. It provides a way to communicate with the Kubernetes API server and manage Kubernetes resources.

**Install kubectl**

<https://kubernetes.io/docs/tasks/tools/#kubectl>&#x20;

**Ensure kubectl works fine**

```javascript
 kubectl get nodes
 kubectl get pods
```

&#x20;If you want to see the exact HTTP request that goes out to the API server, you can add `--v=8` flag

```javascript
kubectl get nodes --v=8
```

## Creating a Pod

There were 5 jargons we learnt about

1. Cluster
2. Nodes
3. Images
4. Containers
5. Pods

&#x20;We have created a `cluster` of `3 nodes`How can we deploy a `single container` from `an image` inside a `pod` ?

#### Finding a good image

Let’s try to start this image locally - <https://hub.docker.com/_/nginx>

**Starting using docker**

```javascript
docker run -p 3005:80 nginx
```

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F11a5e55c-2a4f-4929-b1de-ce300ad59f97%2FScreenshot_2024-06-01_at_6.04.17_AM.png?table=block&#x26;id=1d1b8aa2-5578-48f8-adff-184be3458e58&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

&#x20;Try visiting localhost:3005

**Starting a pod using k8s**

* Start a pod

```javascript
kubectl run nginx --image=nginx --port=80
```

* Check the status of the pod

```javascript
kubectl get pods
```

* Check the logs

```javascript
kubectl logs nginx
```

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F26d04a50-52d7-4bdf-8e9a-b147f51e52a2%2FScreenshot_2024-06-01_at_6.09.40_AM.png?table=block&#x26;id=feafd6ac-29bd-4736-8ab6-d4ddcb7959c9&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

* Describe the pod to see more details

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F7a280791-aab0-4729-b1f7-dee91a074f4c%2FScreenshot_2024-06-01_at_6.11.29_AM.png?table=block&#x26;id=339cc01e-a3b7-439e-b2b4-73018723bf75&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

#### What our system looks like right now

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fae88030d-2973-4add-adcb-3bbb88007e40%2FScreenshot_2024-06-01_at_6.13.20_AM.png?table=block&#x26;id=038f5630-6c6b-4129-aef7-818aebf19ac2&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## Stop the pod

&#x20;Stop the pod by running

```javascript
 kubectl delete pod nginx
```

&#x20;Check the current state of pods

```javascript
kubectl get pods
```

## Kubernetes manifest

A manifest defines the desired state for Kubernetes resources, such as Pods, Deployments, Services, etc., in a declarative manner.&#x20;

**Original command**

```javascript
kubectl run nginx --image=nginx --port=80
```

**Manifest**

```javascript
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - containerPort: 80
```

**Breaking down the manifest**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F2e1f9bdf-0d18-460a-8e31-3124a79a7278%2FScreenshot_2024-06-01_at_6.29.59_AM.png?table=block&#x26;id=ca3401f3-d207-4af7-b493-34cac3c4cce9&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

**Applying the manifest**

```javascript
kubectl apply -f manifest.yml
```

**Delete the pod**

```javascript
 kubectl delete pod nginx
```

## Deployment

A Deployment in Kubernetes is a higher-level abstraction that manages a set of Pods and provides declarative updates to them. It offers features like scaling, rolling updates, and rollback capabilities, making it easier to manage the lifecycle of applications.&#x20;

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F8a18b080-4a2b-4c8b-a677-ea7542ba42c3%2FScreenshot_2024-06-01_at_6.54.23_AM.png?table=block&#x26;id=aa8babe1-9dd3-4751-b6dc-d9962443e8f6&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

* Pod: A Pod is the smallest and simplest Kubernetes object. It represents a single instance of a running process in your cluster, typically containing one or more containers.
* Deployment: A Deployment is a higher-level controller that manages a set of identical Pods. It ensures the desired number of Pods are running and provides declarative updates to the Pods it manages.

&#x20;

**Key Differences Between Deployment and Pod:**

1. **Abstraction Level:**

* Pod: A Pod is the smallest and simplest Kubernetes object. It represents a single instance of a running process in your cluster, typically containing one or more containers.
* Deployment: A Deployment is a higher-level controller that manages a set of identical Pods. It ensures the desired number of Pods are running and provides declarative updates to the Pods it manages.

2. **Management:**

* Pod: They are ephemeral, meaning they can be created and destroyed frequently.
* Deployment: Deployments manage Pods by ensuring the specified number of replicas are running at any given time. If a Pod fails, the Deployment controller replaces it automatically.

3. **Updates:**

* Pod: Directly updating a Pod requires manual intervention and can lead to downtime.
* Deployment: Supports rolling updates, allowing you to update the Pod template (e.g., new container image) and roll out changes gradually. If something goes wrong, you can roll back to a previous version.

4. **Scaling**:

* Pod: Scaling Pods manually involves creating or deleting individual Pods.
* Deployment: Allows easy scaling by specifying the desired number of replicas. The Deployment controller adjusts the number of Pods automatically.

5. Self-Healing:

* Pod: If a Pod crashes, it needs to be restarted manually unless managed by a higher-level controller like a Deployment.
* Deployment: Automatically replaces failed Pods, ensuring the desired state is maintained.

## Series of events

When you run the following command, a bunch of things happen

```javascript
kubectl create deployment nginx-deployment --image=nginx --port=80 --replicas=3
```

**Step-by-Step Breakdown:**

1. Command Execution:

* You execute the command on a machine with `kubectl` installed and configured to interact with your Kubernetes cluster.

2. API Request:

* `kubectl` sends a request to the Kubernetes API server to create a Deployment resource with the specified parameters.

3. API Server Processing:

* The API server receives the request, validates it, and then processes it. If the request is valid, the API server updates the desired state of the cluster stored in etcd. The desired state now includes the new Deployment resource.

4. Storage in etcd:

* The Deployment definition is stored in etcd, the distributed key-value store used by Kubernetes to store all its configuration data and cluster state. etcd is the source of truth for the cluster's desired state.

5. Deployment Controller Monitoring:

* The Deployment controller, which is part of the `kube-controller-manager`, continuously watches the API server for changes to Deployments. It detects the new Deployment you created.

6. ReplicaSet Creation:

* The Deployment controller creates a ReplicaSet based on the Deployment's specification. The ReplicaSet is responsible for maintaining a stable set of replica Pods running at any given time.

7. Pod Creation:

* The ReplicaSet controller (another part of the `kube-controller-manager`) ensures that the desired number of Pods (in this case, 3) are created and running. It sends requests to the API server to create these Pods.

8. Scheduler Assignment:

* The Kubernetes scheduler watches for new Pods that are in the "Pending" state. It assigns these Pods to suitable nodes in the cluster based on available resources and scheduling policies.

9. Node and Kubelet:

* The kubelet on the selected nodes receives the Pod specifications from the API server. It then pulls the necessary container images (nginx in this case) and starts the containers.

<details>

<summary>Hierarchical Relationship</summary>

Deployment:

* High-Level Manager: A Deployment is a higher-level controller that manages the entire lifecycle of an application, including updates, scaling, and rollbacks.
* Creates and Manages ReplicaSets: When you create or update a Deployment, it creates or updates ReplicaSets to reflect the desired state of your application.
* Handles Rolling Updates and Rollbacks: Deployments handle the complexity of updating applications by managing the creation of new ReplicaSets and scaling down old ones.

ReplicaSet:

* Mid-Level Manager: A ReplicaSet ensures that a specified number of identical Pods are running at any given time.
* Maintains Desired State of Pods: It creates and deletes Pods as needed to maintain the desired number of replicas.
* Label Selector: Uses label selectors to identify and manage Pods.

Pods:

* Lowest-Level Unit: A Pod is the smallest and simplest Kubernetes object. It represents a single instance of a running process in your cluster and typically contains one or more containers.

</details>

&#x20;💡A good question to ask at this point is why do you need a `deployment` when a `replicaset` is good enough to bring up and heal pods

## Create a replicaset

Let’s not worry about deployments, lets just create a replicaset that starts 3 pods

* Create `rs.yml`

```javascript
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: nginx-replicaset
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80
```

* Apply the manifest

```javascript
kubectl apply -f rs.yml
```

* Get the rs details

```javascript
kubectl get rs

NAME               DESIRED   CURRENT   READY   AGE
nginx-replicaset   3         3         3       23s
```

* Check the pods

```javascript
kubectl get pods

NAME                     READY   STATUS    RESTARTS   AGE
nginx-replicaset-7zp2v   1/1     Running   0          35s
nginx-replicaset-q264f   1/1     Running   0          35s
nginx-replicaset-vj42z   1/1     Running   0          35s
```

* Try deleting a pod and check if it self heals

```javascript
kubectl delete pod nginx-replicaset-7zp2v
kubectl get pods
```

* Try adding a pod with the `app=nginx`

```javascript
kubectl run nginx-pod --image=nginx --labels="app=nginx"
```

* Ensure it gets terminated immedietely because the `rs` already has 3 pods
* Delete the replicaset

```javascript
 kubectl delete rs nginx-deployment-576c6b7b6
```

💡Note the naming convention of the pods. The pods are named after the `replicaset` followed by a unique id (for eg nginx-replicaset-vj42z)&#x20;

## Create a deployment

Lets create a deployment that starts 3 pods&#x20;

* Create deployment.yml

```javascript
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80
```

&#x20;

* Apply the deployment

```javascript
 kubectl apply -f deployment.yml
```

* Get the deployment

```javascript
kubectl get deployment

NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   3/3     3            3           18s
```

* Get the rs

```javascript
kubectl get rs
NAME                         DESIRED   CURRENT   READY   AGE
nginx-deployment-576c6b7b6   3         3         3       34s
```

* Get the pod

```javascript
kubectl get pod
NAME                               READY   STATUS    RESTARTS   AGE
nginx-deployment-576c6b7b6-b6kgk   1/1     Running   0          46s
nginx-deployment-576c6b7b6-m8ttl   1/1     Running   0          46s
nginx-deployment-576c6b7b6-n9cx4   1/1     Running   0          46s
```

* Try deleting a pod

```javascript
kubectl delete pod nginx-deployment-576c6b7b6-b6kgk
```

* Ensure the pods are still up

```javascript
kubectl get pods
```

**Installing Kubernetes on Windows and macOS**

**Windows:**

1. **Install WSL2:** Ensure you have Windows Subsystem for Linux 2 (WSL2) enabled. You can enable it through the Windows Terminal settings.
2. **Install Docker Desktop:** Download and install Docker Desktop for Windows. This will also install the Kubernetes runtime.
3. **Verify Installation:** Open a PowerShell or Command Prompt window and run the following command:Bash

   ```
   kubectl get pods
   ```

   If Kubernetes is installed correctly, you should see a list of pods.

**macOS:**

1. **Install Homebrew (if not already installed):** Open Terminal and run:Bash

   ```
   /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
   ```
2. **Install Kubernetes:** Run the following command in Terminal:Bash

   ```
   brew install kubectl
   ```

   &#x20;
3. **Verify Installation:** Run the following command in Terminal:Bash

   ```
   kubectl get pods
   ```

   If Kubernetes is installed correctly, you should see a list of pods.

**Additional Notes:**

* You may need to restart your computer after installing WSL2 or Docker Desktop for the changes to take effect.
* If you encounter any issues, refer to the official Kubernetes documentation or community forums for troubleshooting.
* For more advanced Kubernetes setups, consider using tools like Minikube or kind to create local Kubernetes clusters.

By following these steps, you should be able to successfully install Kubernetes on your Windows or macOS system and start using it to manage your containerized applications.

**A pod in Kubernetes is a group of containers that share a common network namespace and volume.** It's the smallest deployable unit in Kubernetes.

**Key characteristics of a pod:**

* **Containers:** A pod can contain one or more containers. These containers share the same network namespace, which means they can communicate with each other directly without needing to go through a network service.
* **Volumes:** Pods can mount volumes, which are persistent storage units that can be shared between containers within the pod or across multiple pods.
* **Lifecycle:** Kubernetes manages the lifecycle of pods, including creation, deletion, and restarting if necessary.
* **Labels:** Pods can be labeled to group and identify them.

**Why use pods?**

* **Co-locating containers:** Pods are used to co-locate containers that need to work closely together. For example, a web server and a database container might be placed in the same pod.
* **Sharing resources:** Pods can share resources like volumes and network interfaces, which can improve efficiency and reduce overhead.
* **Isolation:** Each pod is isolated from other pods, providing a level of security and preventing conflicts.

In summary, a pod is a fundamental building block in Kubernetes, providing a way to group and manage containers and their associated resources.&#x20;


# CI/CD

**Continuous Integration**

Continuous Integration (CI) is a development practice where developers frequently integrate their code changes into a shared repository, preferably several times a day. Each integration is automatically verified by

1. Building the project and
2. Running automated tests.

This process allows teams to detect problems early, improve software quality, and reduce the time it takes to validate and release new software updates.

**Continuous Deployment**

As the name suggests, deploying your code `continuously` to various environments (dev/stage/prod)

## Continuous Deployment in Github

We’ll be deploying a next.js app to EC2 servers via Docker💡You don’t really need Docker here, since it’s deploying on a simple EC2 server. If you deploy to 1. GCP App runner 2. ECS 3. Kubernetes then it makes more sense to deploy a `dockerised`

**Architecture diagram**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F22c1c7b4-3fa2-46b4-80e0-49f8b66ea635%2FScreenshot_2024-03-20_at_8.51.20_PM.png?table=block&#x26;id=c62fe199-6f4b-413d-8c68-4d5d465759e7&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## How to create a CI/CD pipeline?

For Github, you can add all your pipelines to `.github/workflows`

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F604e322e-77ba-4a33-a0ab-9252321ef0fa%2FScreenshot_2024-03-31_at_4.23.03_PM.png?table=block&#x26;id=da42c1d0-4cb7-40a7-b7a6-c88914f2caeb&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

**CD pipelines look like this finally -**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fbb9b9e1f-5313-4c6a-a89d-00b699134969%2FScreenshot_2024-03-31_at_4.24.16_PM.png?table=block&#x26;id=baad753d-9a8f-4b2f-8ee7-d34874cda47a&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

&#x20;Hint - Use <https://onlineyamltools.com/convert-yaml-to-json> to see the pipeline in json

## Step 1 - Create the CI pipeline

Make sure that whenever someone tries to create a PR, we build the project and make sure that it builds as expected

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F7804a4e7-a34e-4796-8d26-5cb236c5d199%2FScreenshot_2024-03-31_at_6.50.45_PM.png?table=block&#x26;id=ae992744-1143-4ebc-9848-de2ed6733ca6&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## Lets add a build pipeline for our repo

Anytime a user creates a PR, we need to run `npm run build` and only if it succeeds should the workflow succeed&#x20;

* Fork the main repo&#x20;
* Add `.github/workflows/build.yml` in the root folder
* Create the workflow

```javascript
name: Build on PR

on:
  pull_request:
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Use Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'
      
      - name: Install Dependencies
        run: npm install
        
      - name: Run Build
        run: npm run build
```

* Push this to master branch
* Create a new branch with some minimal changes and create a PR from it
* You should see the workflow run

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fe66100ee-cdad-46d8-8b5b-0e97563aaf28%2FScreenshot_2024-03-31_at_4.37.16_PM.png?table=block&#x26;id=6b012946-2705-4ae3-889d-d64fa8d0b112&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## Let’s add a deploy step

* Create dockerfiles for the `apps` you have
* Create `docker/Dockerfile.user`
* ```javascript
  FROM node:20.12.0-alpine3.19

  WORKDIR /usr/src/app

  COPY package.json package-lock.json turbo.json tsconfig.json ./

  COPY apps ./apps
  COPY packages ./packages

  # Install dependencies
  RUN npm install
  # Can you add a script to the global package.json that does this?
  RUN cd packages/db && npx prisma generate && cd ../..

  # Can you filter the build down to just one app?
  RUN npm run build

  CMD ["npm", "run", "start-user-app"]
  ```
* Add `start-user-app` script to the root `package.json`
* ```javascript
  "start-user-app": "cd ./apps/user-app && npm run start"
  ```

&#x20;💡You dont really need to build every app for every dockerfile. Can you change the build command so that only a single app is built for each dockerfile?

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F51df3aa8-aeaa-480b-ba8c-2199f4f024b2%2FScreenshot_2024-03-31_at_5.44.18_PM.png?table=block&#x26;id=2610106d-6187-4732-9ab3-2d6de23e3918&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

* Create the CD pipeline that
* Clones the repo
* Builds the docker image
* Pushes the docker image
* ```javascript
  name: Build and Deploy to Docker Hub

  on:
    push:
      branches:
        - master

  jobs:
    build-and-push:
      runs-on: ubuntu-latest
      steps:
      - name: Check Out Repo
        uses: actions/checkout@v2

      - name: Log in to Docker Hub
        uses: docker/login-action@v1
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Build and Push Docker image
        uses: docker/build-push-action@v2
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: 100xdevs/web-app:latest  # Replace with your Docker Hub username and repository

      - name: Verify Pushed Image
        run: docker pull 100xdevs/web-app:latest  # Replace with your Docker Hub username and repository
  ```
* Make sure to add the `dockerhub` secrets to `github secrets` of the repo (DOCKER\_USERNAME, DOCKER\_PASSWORD)
* You should see a workflow running

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F58c0244b-9fc2-4a73-bf6b-18e8c96186df%2FScreenshot_2024-03-31_at_5.58.58_PM.png?table=block&#x26;id=f5fa90e6-b914-4fd7-a729-944a1b165902&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Faeeaea90-055b-4eae-814c-f0dc4d3f059f%2FScreenshot_2024-03-31_at_6.00.25_PM.png?table=block&#x26;id=3e12a6d3-a563-4c14-a3f3-0bcf96e50061&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

&#x20;

**Check dockerhub to ensure the image has indeed reached there**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F12f5ab3c-a7e7-424f-99c6-358995e68649%2FScreenshot_2024-03-31_at_6.01.41_PM.png?table=block&#x26;id=ab1aea6b-37b7-4313-93cb-758bda7687f2&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

&#x20;💡You might have to inject more environment variables (like DB URL) in there for the build to work as expected

## Let’s pull the docker image

Ref - <https://github.com/appleboy/ssh-action>

* Create an ec2 server
* Download its keypair file
* Allow http/https traffic
* Ubuntu base image
* Download docker on the machine
* <https://docs.docker.com/engine/install/ubuntu/>
* sudo docker run hello-world
* Update workflow to pull the latest image on the ec2 machine

```javascript
name: Build and Deploy to Docker Hub

on:
  push:
    branches:
      - master  # Adjusted to trigger on pushes to master

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    steps:
    - name: Check Out Repo
      uses: actions/checkout@v2

    - name: Prepare Dockerfile
      run: cp ./docker/Dockerfile.user ./Dockerfile

    - name: Log in to Docker Hub
      uses: docker/login-action@v1
      with:
        username: ${{ secrets.DOCKER_USERNAME }}
        password: ${{ secrets.DOCKER_PASSWORD }}

    - name: Build and Push Docker image
      uses: docker/build-push-action@v2
      with:
        context: .
        file: ./Dockerfile
        push: true
        tags: 100xdevs/web-app:latest

    - name: Verify Pushed Image
      run: docker pull 100xdevs/web-app:latest

    - name: Deploy to EC2
      uses: appleboy/ssh-action@master
      with:
        host: ${{ secrets.SSH_HOST }}
        username: ${{ secrets.SSH_USERNAME }}
        key: ${{ secrets.SSH_KEY }}
        script: |
          sudo docker pull 100xdevs/web-app:latest
          sudo docker stop web-app || true
          sudo docker rm web-app || true
          sudo docker run -d --name web-app -p 3005:3000 100xdevs/web-app:latest
```

* Point userapp.your\_domain.com to the IP of the server
* Add nginx reverse proxy to forward requests from userapp.your\_domain.com to port on which the app is running

```javascript

server {
        server_name userapp.100xdevs.com;

        location / {
            proxy_pass http://localhost:3005;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;


                # Basic Authentication
                auth_basic "Restricted Content";
                auth_basic_user_file /etc/nginx/.htpasswd;
        }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/userapp.100xdevs.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/userapp.100xdevs.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
```

* Install certbot and Refresh certificate

```javascript
sudo certbot --nginx
```

&#x20;&#x20;


# Docker Swam

&#x20;<https://docs.docker.com/engine/swarm/>Docker swarm is a container orchestration system, very similar to kubernetes.

**Core concepts**

ServicesTasksContainers

**Kubernetes vs Docker swarm**

| Kubernetes                             | Docker swarm              |
| -------------------------------------- | ------------------------- |
| Very hard to understand                | Much easier to understand |
| Much more prod ready, adopted and used | Not used as often         |
| Supports autoscaling                   | Have to scale it manually |
| Need to install/understand kubectl     | Works with the docker cli |

\
Architecture

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fbe1569ad-51ef-48bd-9fd8-01e3f11c3432%2Fswarm-diagram.webp?table=block&#x26;id=a3b18027-1f74-4e7c-a730-8de851750ae8&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

&#x20;

#### Manager Node

Manager nodes handle cluster management tasks:

* Maintaining cluster state
* Scheduling services

#### Worker Node

Worker nodes are also instances of Docker Engine whose sole purpose is to execute containers.&#x20;

## Services, tasks, containers

To deploy an application image when Docker Engine is in Swarm mode, you create a service. Frequently a service is the image for a microservice within the context of some larger application (eg - HTTP Server)

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fd95ff778-b2c9-4298-bb21-ccc427f267fb%2Fservices-diagram.webp?table=block&#x26;id=14fc1df4-52cf-4cd4-8766-4d1c25cbb9bd&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

&#x20;

* Service - A service is the definition of how you want to run your application in the swarm. It specifies the desired state, including the number of replicas, the image to use, the command to run, and other configurations such as networks and volumes.
* Task - A task is a single instance of a service running on a node. Each task represents one container and its associated metadata. When you create a service with multiple replicas, Docker Swarm creates a task for each replica.
* Container - A container is a running instance of a Docker image. Each task maps to one container. The swarm orchestrator ensures the tasks (and thus the containers) are distributed across the nodes in the swarm according to the defined service specifications.

## Services, tasks, containers

To deploy an application image when Docker Engine is in Swarm mode, you create a service. Frequently a service is the image for a microservice within the context of some larger application (eg - HTTP Server)

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fd95ff778-b2c9-4298-bb21-ccc427f267fb%2Fservices-diagram.webp?table=block&#x26;id=14fc1df4-52cf-4cd4-8766-4d1c25cbb9bd&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

&#x20;

* Service - A service is the definition of how you want to run your application in the swarm. It specifies the desired state, including the number of replicas, the image to use, the command to run, and other configurations such as networks and volumes.
* Task - A task is a single instance of a service running on a node. Each task represents one container and its associated metadata. When you create a service with multiple replicas, Docker Swarm creates a task for each replica.
* Container - A container is a running instance of a Docker image. Each task maps to one container. The swarm orchestrator ensures the tasks (and thus the containers) are distributed across the nodes in the swarm according to the defined service specifications.

## Deploying a service

* Deploy the nginx service

```javascript
docker service create --replicas 3 --name helloworld -p 3000:80 nginx
```

* Check the status of the service

```javascript
docker service ls
```

* Go to the machine URL on port 3000 and ensure you see it running

```javascript
your_machine_ip:3000
```

* Try deleting a few pods and see if they come back up
* Delete the service

```javascript
docker service rm helloworld
```

&#x20;


# Protocols

## 1. Protocols: The Backbone of Communication 🌐

Protocols are sets of rules and procedures that govern how data is transmitted between devices or systems. They are essential for ensuring reliable, efficient, and secure communication in various technological contexts, including traditional networks and emerging Web3 technologies.

### 2. Types of Protocols and Their Functions 📊

#### 1. Network Protocols

* **TCP/IP (Transmission Control Protocol/Internet Protocol):** The fundamental protocol suite for internet communication.
* **HTTP/HTTPS (Hypertext Transfer Protocol/Secure):** Used for transmitting web pages and ensuring secure data transfer.
* **FTP (File Transfer Protocol):** Facilitates file transfers between computers on a network.

#### 2. Security Protocols

* **SSL/TLS (Secure Sockets Layer/Transport Layer Security):** Encrypts data for secure internet communication.
* **IPsec (Internet Protocol Security):** Provides secure communication for Virtual Private Networks (VPNs).

#### 3. Email Protocols

* **SMTP (Simple Mail Transfer Protocol):** Used for sending emails.
* **POP3 (Post Office Protocol):** Retrieves emails from a server.
* **IMAP (Internet Message Access Protocol):** Allows access and management of emails on a server.

#### 4. Wireless Protocols

* **Wi-Fi:** Enables wireless local area networking.
* **Bluetooth:** Facilitates short-range wireless communication between devices.
* **Ethernet:** Defines how data is transmitted over a local area network (LAN).

### 3. Why We Use Protocols 🤔

Protocols are crucial for several reasons:

* **Standardization:** They ensure consistent communication across different devices and systems.
* **Interoperability:** Protocols allow diverse systems to work together seamlessly.
* **Efficiency:** They optimize data transfer and reduce errors in communication.
* **Security:** Many protocols incorporate security measures to protect data during transmission.

### 4. Problems Solved by Protocols 🛠️

* **Data Integrity:** Protocols ensure that data arrives intact and uncorrupted.
* **Network Congestion:** They manage traffic flow to prevent network overload.
* **Compatibility Issues:** Protocols bridge gaps between different systems and technologies.
* **Security Vulnerabilities:** They provide mechanisms for secure data exchange.

### 5. Protocols in Web3 🌐3️⃣

Web3 introduces new protocols designed for decentralized systems:

* **Blockchain Protocols:** Like Bitcoin and Ethereum, governing cryptocurrency transactions and smart contracts.
* **InterPlanetary File System (IPFS):** A protocol for decentralized file storage and sharing.
* **Decentralized Identity Protocols:** Enabling self-sovereign identity management.
* **Streaming protocols:** HTTP Live Streaming (HLS), RTMP (Real-Time Messaging Protocol), etc., for streaming media.
* **VPN protocols:** OpenVPN, PPTP, L2TP/IPSec for creating secure network connections.

### 6. Important and Widely Used Web3 Protocols

Web3 is a complex ecosystem with numerous protocols serving various functions. Here's a breakdown of some of the most critical and widely used ones:

#### Core Layer-1 Protocols

* **Ethereum:** The pioneer of smart contracts, offering a robust platform for decentralized applications (dApps).
* **Bitcoin:** While primarily a cryptocurrency, its underlying blockchain technology is fundamental to the Web3 space.
* **Solana:** Known for its high speed and scalability, it's gaining traction for dApp development.
* **Binance Smart Chain (BSC):** A popular platform for DeFi and NFT applications due to its lower transaction fees.
* **Cardano:** Emphasizes research and development, focusing on security and sustainability.

#### Layer-2 Solutions

* **Optimism and Arbitrum:** Optimistic rollups that enhance Ethereum's scalability.
* **Polygon:** A versatile platform offering multiple scaling solutions.
* **zkSync:** Zero-knowledge rollups prioritizing privacy and security.

#### Decentralized Finance (DeFi) Protocols

* **Uniswap:** A leading decentralized exchange (DEX) facilitating token swaps.
* **Aave:** A prominent lending and borrowing platform.
* **Compound:** Another key player in the DeFi lending space.
* **MakerDAO:** A decentralized stablecoin platform.

#### Oracle Networks

* **Chainlink:** Provides real-world data to smart contracts.

#### Interoperability Protocols

* **Polkadot:** Connects different blockchains into a unified network.
* **Cosmos:** Another interoperability solution focusing on independent blockchains.

#### Other Notable Protocols

* **The Graph:** An indexing protocol for querying blockchain data.
* **Filecoin:** A decentralized storage network.
* **Helium:** A decentralized wireless network for IoT devices.

#### Factors Influencing Protocol Adoption

Several factors contribute to the success and adoption of Web3 protocols:

* **Scalability:** The ability to handle increasing transaction volume.
* **Security:** Robustness against attacks and vulnerabilities.
* **Decentralization:** Resistance to censorship and control.
* **Developer Experience:** Ease of use and development tools.
* **Community and Ecosystem:** The strength of the community and the number of dApps built on the protocol.
* **Token Economics:** The design of the token and its distribution.

&#x20;The Web3 landscape is rapidly evolving, and new protocols emerge frequently.&#x20;


# ERCs & EIPs

#### ERCs (Ethereum Request for Comments)

ERCs are a subset of EIPs specifically focused on application-level standards. They define rules and specifications for creating new tokens and smart contracts on the Ethereum blockchain. In essence, they provide a blueprint for developers to build on Ethereum. &#x20;

#### EIPs (Ethereum Improvement Proposals)

EIPs are the backbone of Ethereum's evolution. They are formal proposals for changes to the Ethereum protocol. These changes can range from minor tweaks to major upgrades. Essentially, they are the roadmap for Ethereum's growth. &#x20;

### 1. Introduction to ERCs and EIPs

#### 1.1 What are ERCs?

ERC stands for Ethereum Request for Comments. These are application-level standards and conventions for the Ethereum platform. ERCs define a set of rules that Ethereum-based tokens must follow.

#### 1.2 What are EIPs?

EIP stands for Ethereum Improvement Proposal. These are design documents providing information to the Ethereum community, describing a new feature or its processes or environment.

#### 1.3 Importance of ERCs and EIPs

ERCs and EIPs play a crucial role in maintaining consistency, interoperability, and standardization across the Ethereum ecosystem. They allow developers to create tokens and applications that can easily interact with each other, fostering innovation and growth.&#x20;

### 2.🌐 ERCs & EIPs: Ethereum's Building Blocks

Ethereum Request for Comments (ERCs) and Ethereum Improvement Proposals (EIPs) are fundamental components that shape the Ethereum ecosystem and, by extension, much of the Web3 world.

#### &#x20;2.1📘 Overview of ERCs and EIPs

ERCs (Ethereum Request for Comments):

* Application-level standards for tokens, smart contracts, and dApps
* Define common interfaces for developers to follow
* Ensure interoperability between different Ethereum-based projects
* Examples include ERC-20 for fungible tokens and ERC-721 for NFTs

EIPs (Ethereum Improvement Proposals):

* Formal design documents for new features or processes in Ethereum
* Cover core protocol specifications, client APIs, and contract standards
* Drive the evolution of the Ethereum network
* Can lead to significant changes like EIP-1559 (fee structure reform)

#### 2.2🏗️ ERCs: Foundations of Web3 Applications

ERCs serve as standardized interfaces for decentralized applications (dApps) and smart contracts, enabling:

* DeFi protocol development
* NFT marketplace creation
* DAO infrastructure
* Consistent user experiences across different platforms

#### &#x20;2.3🔧 EIPs: Evolving the Ethereum Ecosystem

EIPs guide Ethereum's growth by:

* Improving core protocols
* Introducing new features and functionalities
* Addressing scalability and security challenges
* Facilitating major upgrades like the transition to Ethereum 2.0

#### &#x20;2.4💡 Impact on Blockchain Innovation

Together, ERCs and EIPs foster innovation in the blockchain space by:

* Encouraging standardization and best practices
* Promoting community-driven development
* Enabling interoperable and composable Web3 applications
* Facilitating rapid experimentation and iteration in blockchain technology

As the Web3 ecosystem continues to evolve, ERCs and EIPs remain essential tools for developers, entrepreneurs, and innovators building the decentralized future.

### 3. ERCs vs EIPs: Understanding the Difference

#### 3.1 ERCs (Ethereum Request for Comments)

ERCs are application-level standards and conventions for the Ethereum platform. They define specific rules and interfaces that Ethereum-based tokens and smart contracts should follow to ensure compatibility and interoperability within the ecosystem.

Key characteristics of ERCs:

* Focus on application-level functionality
* Define standards for tokens, smart contracts, and dApps
* Ensure consistency across different projects
* Examples include ERC-20 (fungible tokens) and ERC-721 (non-fungible tokens)

#### 3.2 EIPs (Ethereum Improvement Proposals)

EIPs are broader in scope and encompass all aspects of the Ethereum network. They are formal design documents proposing new features or processes for Ethereum.

Key characteristics of EIPs:

* Cover core protocol specifications, client APIs, and contract standards
* Can propose changes to the network's fundamental operations
* Go through a rigorous review and approval process
* Examples include EIP-1559 (fee structure reform) and EIP-3675 (upgrade to Proof of Stake)

#### 3.3 Key Differences

While ERCs and EIPs are both crucial for Ethereum's development, they differ in several ways:

* **Scope:** ERCs are specific to application-level standards, while EIPs can cover any aspect of the Ethereum ecosystem.
* **Implementation:** ERCs are typically implemented by developers in their smart contracts, while EIPs may require network-wide upgrades.
* **Process:** ERCs have a less formal process and can be adopted by community consensus, while EIPs go through a more structured proposal and review process.
* **Impact:** ERCs influence how applications interact within Ethereum, while EIPs can fundamentally change how the Ethereum network operates.

In summary, ERCs and EIPs work together to shape the Ethereum ecosystem, with ERCs focusing on standardizing application-level interactions and EIPs driving the overall evolution of the Ethereum protocol.

### 4. Comprehensive Overview of ERCs and EIPs in Blockchain

Ethereum Request for Comments (ERCs) and Ethereum Improvement Proposals (EIPs) have been instrumental in shaping the blockchain landscape. Let's explore some of the most significant ones:

#### 4.1 ERCs (Ethereum Request for Comments)

* **ERC-20:** The standard for fungible tokens, enabling seamless exchange and interoperability.
* **ERC-721:** Non-fungible token (NFT) standard, crucial for unique digital assets.
* **ERC-1155:** Multi-token standard, allowing for both fungible and non-fungible tokens in a single contract.
* **ERC-4626:** Tokenized Vault Standard, providing a unified interface for yield-bearing vaults.
* **ERC-777:** Advanced token standard, backwards compatible with ERC-20, offering improved control over token transactions.
* **ERC-3643:** Security Token Standard, facilitating compliant transfer of regulated tokens.
* **ERC-4337:** Account Abstraction standard, enabling smart contract wallets and improved user experience.
* **ERC-6551:** Non-fungible Token Bound Accounts, allowing NFTs to own assets and interact with smart contracts.
* **ERC-223:** Token standard aimed at preventing accidental token loss when transferring to contracts.
* **ERC-1400:** Security Token Standard, providing a set of interfaces for issuing and managing security tokens.
* **ERC-165:** Standard Interface Detection, allowing smart contracts to publish and detect what interfaces they implement.
* **ERC-777:** Advanced token standard with added features like operator management and hooks.

#### 4.2 EIPs (Ethereum Improvement Proposals)

* **EIP-1559:** Fee market change for more predictable gas fees and ETH burning mechanism.
* **EIP-3675:** Consensus layer upgrade from Proof of Work to Proof of Stake.
* **EIP-155:** Simple replay attack protection between Ethereum and Ethereum Classic.
* **EIP-1884:** Repricing for trie-size-dependent opcodes to maintain network health.
* **EIP-2718:** Typed Transaction Envelope for future-proofing transaction formats.
* **EIP-2930:** Optional access lists to optimize gas costs for complex transactions.
* **EIP-4844:** Shard Blob Transactions, introducing a new transaction type for cheaper and faster Layer 2 solutions.

These standards and proposals have not only shaped Ethereum but have influenced the broader blockchain ecosystem. They demonstrate the power of community-driven development and standardization in fostering innovation and interoperability in the blockchain space.


# ERC-20

## ERC-20: Fungible Token Standard 💰

ERC-20 is the most widely used token standard in the Ethereum ecosystem. It was introduced to create a common set of rules for fungible tokens, enabling seamless exchange and interoperability.

Key functions of ERC-20:

* totalSupply(): Returns the total token supply
* balanceOf(address account): Returns the token balance of a given address
* transfer(address recipient, uint256 amount): Transfers tokens to a specified address
* approve(address spender, uint256 amount): Allows a spender to withdraw tokens from your account
* transferFrom(address sender, address recipient, uint256 amount): Transfers tokens from one address to another

Example ERC-20 implementation:

```solidity
pragma solidity ^0.8.0;

contract ERC20Token {
    string public name;
    string public symbol;
    uint8 public decimals;
    uint256 private _totalSupply;
    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 initialSupply) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;
        _totalSupply = initialSupply * 10**uint256(decimals);
        _balances[msg.sender] = _totalSupply;
        emit Transfer(address(0), msg.sender, _totalSupply);
    }

    function totalSupply() public view returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view returns (uint256) {
        return _balances[account];
    }

    function transfer(address recipient, uint256 amount) public returns (bool) {
        _transfer(msg.sender, recipient, amount);
        return true;
    }

    function approve(address spender, uint256 amount) public returns (bool) {
        _approve(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
        _transfer(sender, recipient, amount);
        uint256 currentAllowance = _allowances[sender][msg.sender];
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
        unchecked {
            _approve(sender, msg.sender, currentAllowance - amount);
        }
        return true;
    }

    function _transfer(address sender, address recipient, uint256 amount) internal {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");
        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[sender] = senderBalance - amount;
        }
        _balances[recipient] += amount;
        emit Transfer(sender, recipient, amount);
    }

    function _approve(address owner, address spender, uint256 amount) internal {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");
        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }
}
```


# ERC-721

## ERC-721: Non-Fungible Token (NFT) Standard 🖼️

ERC-721 defines the standard for non-fungible tokens, which are unique and indivisible. This standard has been crucial for the development of digital collectibles, art, and gaming assets.

Key functions of ERC-721:

* balanceOf(address owner): Returns the number of NFTs owned by an address
* ownerOf(uint256 tokenId): Returns the owner of a specific token
* transferFrom(address from, address to, uint256 tokenId): Transfers ownership of an NFT
* approve(address to, uint256 tokenId): Grants permission to transfer a specific NFT
* setApprovalForAll(address operator, bool approved): Enables or disables approval for a third party to manage all of the sender's assets

Example ERC-721 implementation:

```solidity
pragma solidity ^0.8.0;

contract ERC721Token {
    mapping(uint256 => address) private _owners;
    mapping(address => uint256) private _balances;
    mapping(uint256 => address) private _tokenApprovals;
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    function balanceOf(address owner) public view returns (uint256) {
        require(owner != address(0), "ERC721: balance query for the zero address");
        return _balances[owner];
    }

    function ownerOf(uint256 tokenId) public view returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC721: owner query for nonexistent token");
        return owner;
    }

    function approve(address to, uint256 tokenId) public {
        address owner = ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");
        require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
            "ERC721: approve caller is not owner nor approved for all"
        );
        _tokenApprovals[tokenId] = to;
        emit Approval(owner, to, tokenId);
    }

    function getApproved(uint256 tokenId) public view returns (address) {
        require(_exists(tokenId), "ERC721: approved query for nonexistent token");
        return _tokenApprovals[tokenId];
    }

    function setApprovalForAll(address operator, bool approved) public {
        require(operator != msg.sender, "ERC721: approve to caller");
        _operatorApprovals[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

    function isApprovedForAll(address owner, address operator) public view returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    function transferFrom(address from, address to, uint256 tokenId) public {
        require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
        _transfer(from, to, tokenId);
    }

    function _exists(uint256 tokenId) internal view returns (bool) {
        return _owners[tokenId] != address(0);
    }

    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
        require(_exists(tokenId), "ERC721: operator query for nonexistent token");
        address owner = ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
    }

    function _transfer(address from, address to, uint256 tokenId) internal {
        require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
        require(to != address(0), "ERC721: transfer to the zero address");
        _approve(address(0), tokenId);
        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;
        emit Transfer(from, to, tokenId);
    }

    function _approve(address to, uint256 tokenId) internal {
        _tokenApprovals[tokenId] = to;
        emit Approval(ownerOf(tokenId), to, tokenId);
    }
}
```


# ERC-1155

## ERC-1155: Multi-Token Standard 🎭

ERC-1155 allows for the creation of both fungible and non-fungible tokens within a single contract. This standard is particularly useful for gaming applications where various types of assets are needed.

Key functions of ERC-1155:

* balanceOf(address account, uint256 id): Returns the balance of a specific token for an account
* balanceOfBatch(address\[] accounts, uint256\[] ids): Returns the balance of multiple token types for multiple accounts
* safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data): Transfers a specific amount of tokens
* safeBatchTransferFrom(address from, address to, uint256\[] ids, uint256\[] amounts, bytes data): Batch transfers multiple token types

Example ERC-1155 implementation:

```solidity
pragma solidity ^0.8.0;

contract ERC1155Token {
    mapping(uint256 => mapping(address => uint256)) private _balances;
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
    event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    function balanceOf(address account, uint256 id) public view returns (uint256) {
        require(account != address(0), "ERC1155: balance query for the zero address");
        return _balances[id][account];
    }

    function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view returns (uint256[] memory) {
        require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
        uint256[] memory batchBalances = new uint256[](accounts.length);
        for (uint256 i = 0; i < accounts.length; ++i) {
            batchBalances[i] = balanceOf(accounts[i], ids[i]);
        }
        return batchBalances;
    }

    function setApprovalForAll(address operator, bool approved) public {
        require(msg.sender != operator, "ERC1155: setting approval status for self");
        _operatorApprovals[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

    function isApprovedForAll(address account, address operator) public view returns (bool) {
        return _operatorApprovals[account][operator];
    }

    function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) public {
        require(from == msg.sender || isApprovedForAll(from, msg.sender), "ERC1155: caller is not owner nor approved");
        require(to != address(0), "ERC1155: transfer to the zero address");
        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
        _balances[id][from] = fromBalance - amount;
        _balances[id][to] += amount;
        emit TransferSingle(msg.sender, from, to, id, amount);
    }

    function safeBatchTransferFrom(address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public {
        require(from == msg.sender || isApprovedForAll(from, msg.sender), "ERC1155: transfer caller is not owner nor approved");
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
        require(to != address(0), "ERC1155: transfer to the zero address");
        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];
            uint256 fromBalance = _balances[id][from];
            require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
            _balances[id][from] = fromBalance - amount;
            _balances[id][to] += amount;
        }
        emit TransferBatch(msg.sender, from, to, ids, amounts);
    }
}
```

####


# ERC-4337

## ERC-4337: Account Abstraction 🔐

ERC-4337 introduces account abstraction, allowing for smart contract wallets to be used as easily as regular externally owned accounts (EOAs). This standard enables advanced features like social recovery, multi-signature wallets, and sponsored transactions without changes to the Ethereum protocol.

Key features of ERC-4337:

* Introduces "UserOperations" as an alternative to traditional transactions
* Enables gasless transactions and batched transactions
* Allows for customizable account logic and recovery mechanisms

ERC-4337 was introduced to address several limitations of traditional Ethereum accounts and to enhance the user experience in blockchain interactions. Here's why it was introduced and how it's helpful in the blockchain ecosystem:

#### Why ERC-4337 was introduced:

* To overcome the limitations of Externally Owned Accounts (EOAs)
* To enable more flexible and programmable account behaviors
* To improve user onboarding and reduce complexity for new users
* To allow for more advanced security features at the account level

#### How ERC-4337 is helpful in blockchain:

* **Improved User Experience:** Simplifies onboarding by allowing users to interact with dApps without managing private keys or understanding gas fees
* **Enhanced Security:** Enables built-in multi-factor authentication and social recovery options
* **Flexible Account Logic:** Allows for programmable spending limits, automated actions, and other custom behaviors
* **Gas Abstraction:** Enables sponsored transactions, where dApps or third parties can pay for users' gas fees
* **Batched Transactions:** Improves efficiency by allowing multiple operations to be executed in a single transaction

By introducing these features, ERC-4337 aims to make blockchain interactions more user-friendly, secure, and flexible, potentially accelerating the adoption of blockchain technology and decentralized applications.

Example of a simplified UserOperation structure:

```jsx
const userOp = {
  sender: '0x...',  // Address of the smart contract account
  nonce: 1,
  initCode: '0x...',  // Code to deploy the account if it's not deployed yet
  callData: '0x...',  // The actual operation to perform
  callGasLimit: 200000,
  verificationGasLimit: 100000,
  preVerificationGas: 50000,
  maxFeePerGas: ethers.utils.parseUnits("20", "gwei"),
  maxPriorityFeePerGas: ethers.utils.parseUnits("5", "gwei"),
  paymasterAndData: '0x...',  // Optional, for sponsored transactions
  signature: '0x...'  // Signature authorizing the operation
};
```


# ERC-6551

## ERC-6551: Non-Fungible Token Bound Accounts 🔗

ERC-6551 proposes a standard for creating unique blockchain accounts for non-fungible tokens (NFTs). This allows each NFT to own assets and interact with applications, effectively turning them into smart contract wallets.

Key features of ERC-6551:

* Each NFT can have its own account to hold assets and execute transactions
* Enables NFTs to own other NFTs, creating complex ownership structures
* Allows for the creation of "nested NFTs" and more complex digital asset management

Example of creating an account for an NFT:

```solidity
interface IERC6551Registry {
    function createAccount(
        address implementation,
        uint256 chainId,
        address tokenContract,
        uint256 tokenId,
        uint256 salt,
        bytes calldata initData
    ) external returns (address);
}

contract NFTWallet {
    IERC6551Registry private registry;
    
    constructor(address _registry) {
        registry = IERC6551Registry(_registry);
    }
    
    function createAccountForNFT(
        address tokenContract,
        uint256 tokenId
    ) external returns (address) {
        return registry.createAccount(
            address(this),  // implementation
            block.chainid,  // chainId
            tokenContract,
            tokenId,
            0,  // salt
            ""  // initData
        );
    }
}
```

These ERCs represent significant advancements in Ethereum's capabilities, enabling more flexible and powerful smart contract interactions and asset management.


# ERC-777

## 📜 ERC-777: Advanced Token Standard

ERC-777 is an Ethereum token standard that improves upon ERC-20 by introducing new features and capabilities. This page provides a comprehensive overview of its architecture, core concepts, user flow, and implementation details.

### 🏗️ Architecture

ERC-777 builds on the foundation of ERC-20 while introducing new functionalities. Here's a high-level overview of the architecture:

<figure><img src="/files/9e8Sj08dBFpMOzDUMAPm" alt=""><figcaption></figcaption></figure>

### 🧠 Core Concepts

#### 1. Operators 👥

Operators are addresses authorized to send tokens on behalf of a token holder. This concept enhances flexibility in token management.

#### 2. Send Function 📤

The `send` function replaces the `transfer` function from ERC-20, providing more control and functionality.

#### 3. Hooks 🎣

ERC-777 introduces hooks that are called before sending and after receiving tokens, allowing for more complex interactions.

#### 4. Backwards Compatibility 🔄

ERC-777 tokens are backwards compatible with ERC-20, ensuring interoperability with existing systems.

### 🚶 User Flow

Here's a typical user flow for interacting with ERC-777 tokens:

<figure><img src="/files/gi6M3wVLmDojBJBfHTrX" alt=""><figcaption></figcaption></figure>

### 💻 Implementation Details

#### Core Interface (IERC777)

```solidity
interface IERC777 {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function granularity() external view returns (uint256);
    function totalSupply() external view returns (uint256);
    function balanceOf(address owner) external view returns (uint256);
    function send(address recipient, uint256 amount, bytes calldata data) external;
    function burn(uint256 amount, bytes calldata data) external;
    function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
    function authorizeOperator(address operator) external;
    function revokeOperator(address operator) external;
    function defaultOperators() external view returns (address[] memory);
    // ... events
}
```

#### Sender Hook Interface (IERC777Sender)

```solidity
interface IERC777Sender {
    function tokensToSend(
        address operator,
        address from,
        address to,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external;
}
```

#### Recipient Hook Interface (IERC777Recipient)

```solidity
interface IERC777Recipient {
    function tokensReceived(
        address operator,
        address from,
        address to,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external;
}
```

### 🚀 Example Implementation

Here's a basic implementation of the ERC-777 standard:

```solidity
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC777/ERC777.sol";

contract MyERC777Token is ERC777 {
    constructor(
        string memory name,
        string memory symbol,
        address[] memory defaultOperators
    )
        ERC777(name, symbol, defaultOperators)
    {
        // Mint initial supply to the contract deployer
        _mint(msg.sender, 1000000 * 10**18, "", "", true);
    }

    // Additional custom functions can be added here
}
```

This implementation uses OpenZeppelin's ERC777 contract as a base, which provides a robust and secure implementation of the standard. Developers can extend this base implementation to add custom functionality specific to their use case.

### 🔍 Key Differences from ERC-20

* 📤 `send` function replaces `transfer` and `transferFrom`
* 🎣 Hooks allow for more complex token interactions
* 👥 Operator concept for enhanced authorization
* 🔥 Built-in burning functionality
* 🔢 Granularity for fractional tokens

ERC-777 provides a more feature-rich and flexible token standard compared to ERC-20, while maintaining backwards compatibility. This makes it an attractive option for projects requiring advanced token functionality.


# ERC-3643

## 📜 ERC-3643: The Security Token Standard

ERC-3643 is a comprehensive standard for security tokens on the Ethereum blockchain. It provides a framework for issuing, managing, and trading compliant security tokens.

### 🏗️ Architecture

The ERC-3643 standard consists of several interconnected components:

<figure><img src="/files/ZGI2c1gbY44EDfLKwwlq" alt=""><figcaption></figcaption></figure>

### 🧠 Core Concepts

#### 1. Token 💰

The main ERC-3643 token contract that implements the standard's interfaces.

#### 2. Identity Registry 🆔

Manages the identities of token holders and their associated claims.

#### 3. Compliance 📋

Enforces transfer restrictions and other compliance rules.

#### 4. Trusted Issuers Registry 📚

Maintains a list of trusted claim issuers.

#### 5. Claim Topics Registry 📝

Defines the types of claims that can be associated with identities.

### 🚶 User Flow

Here's a typical user flow for interacting with ERC-3643 tokens:

<figure><img src="/files/y0K04f5zlxDrCG4LlQPc" alt=""><figcaption></figcaption></figure>

### 💻 Implementation Details

#### Token Interface

```solidity
interface IERC3643 is IERC20 {
    function setIdentityRegistry(address _identityRegistry) external;
    function setCompliance(address _compliance) external;
    function forcedTransfer(address _from, address _to, uint256 _amount) external returns (bool);
    function mint(address _to, uint256 _amount) external;
    function burn(address _from, uint256 _amount) external;
    // ... additional functions
}
```

#### Identity Registry Interface

```solidity
interface IIdentityRegistry {
    function registerIdentity(address _address, uint16 _country, bytes32 _hash) external;
    function updateIdentity(address _address, uint16 _country, bytes32 _hash) external;
    function deleteIdentity(address _address) external;
    function isVerified(address _address) external view returns (bool);
    // ... additional functions
}
```

#### Compliance Interface

```solidity
interface ICompliance {
    function canTransfer(address _from, address _to, uint256 _amount) external view returns (bool);
    function transferred(address _from, address _to, uint256 _amount) external;
    function created(address _to, uint256 _amount) external;
    function destroyed(address _from, uint256 _amount) external;
    // ... additional functions
}
```

### 🚀 Example Implementation

Here's a basic implementation of the ERC-3643 token:

```solidity
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./interfaces/IERC3643.sol";
import "./interfaces/IIdentityRegistry.sol";
import "./interfaces/ICompliance.sol";

contract ERC3643Token is ERC20, IERC3643 {
    IIdentityRegistry public identityRegistry;
    ICompliance public compliance;

    constructor(string memory name, string memory symbol) ERC20(name, symbol) {
        // Initialize with default identity registry and compliance
    }

    function setIdentityRegistry(address _identityRegistry) external override {
        // Implementation
    }

    function setCompliance(address _compliance) external override {
        // Implementation
    }

    function transfer(address recipient, uint256 amount) public virtual override(ERC20, IERC20) returns (bool) {
        require(compliance.canTransfer(msg.sender, recipient, amount), "Transfer not allowed");
        bool success = super.transfer(recipient, amount);
        if (success) {
            compliance.transferred(msg.sender, recipient, amount);
        }
        return success;
    }

    // Implement other required functions...
}
```

### 🔑 Key Features

* 🔒 Built-in compliance and regulatory features
* 🆔 Identity management for token holders
* 🔄 Flexible transfer restrictions
* 📊 Granular control over token issuance and management
* 🌐 Support for global regulatory requirements

ERC-3643 provides a comprehensive framework for security tokens, addressing the complex regulatory requirements of tokenized securities. Its modular design allows for flexibility in implementing various compliance rules and identity verification processes.


# EIP-7702

## 📜 EIP-7702: Soulbound Token Standard

EIP-7702 introduces a standard for Soulbound Tokens (SBTs) in the Ethereum ecosystem. This page will provide a comprehensive overview of its architecture, core concepts, user flow, and implementation details.

### 🏗️ Architecture

The EIP-7702 standard defines a set of interfaces and functionalities for Soulbound Tokens. Here's a high-level overview of the architecture:

<figure><img src="/files/MwtnckSWkgpdkjwp7v0Y" alt=""><figcaption></figcaption></figure>

### 🧠 Core Concepts

#### 1. Non-Transferability 🔒

SBTs are designed to be non-transferable, meaning once minted to an address, they cannot be moved to another address.

#### 2. Revocability 🔄

The issuer of an SBT has the ability to revoke (burn) the token if necessary.

#### 3. Metadata 📊

Each SBT can carry metadata, providing additional information about the token and its properties.

#### 4. Enumeration 🔢

The standard includes enumeration functions to easily query and iterate over tokens.

### 🚶 User Flow

Here's a typical user flow for interacting with Soulbound Tokens:

<figure><img src="/files/0rmRZmKJOccwKCoZAQK7" alt=""><figcaption></figcaption></figure>

### 💻 Implementation Details

#### Core Interface (IERC7702)

```solidity
interface IERC7702 {
    event Minted(address indexed to, uint256 indexed tokenId);
    event Burned(address indexed from, uint256 indexed tokenId);

    function mint(address to) external returns (uint256 tokenId);
    function burn(uint256 tokenId) external;
    function ownerOf(uint256 tokenId) external view returns (address owner);
}
```

#### Metadata Interface (IERC7702Metadata)

```solidity
interface IERC7702Metadata is IERC7702 {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function tokenURI(uint256 tokenId) external view returns (string memory);
}
```

#### Enumerable Interface (IERC7702Enumerable)

```solidity
interface IERC7702Enumerable is IERC7702 {
    function totalSupply() external view returns (uint256);
    function tokenByIndex(uint256 index) external view returns (uint256);
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
}
```

### 🚀 Example Implementation

Here's a basic implementation of the ERC7702 standard:

```solidity
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

contract ERC7702 is IERC7702, IERC7702Metadata, IERC7702Enumerable {
    using Counters for Counters.Counter;
    using Strings for uint256;

    string private _name;
    string private _symbol;
    Counters.Counter private _tokenIds;
    mapping(uint256 => address) private _owners;
    mapping(address => uint256[]) private _ownedTokens;

    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    function mint(address to) external override returns (uint256) {
        _tokenIds.increment();
        uint256 newTokenId = _tokenIds.current();
        _mint(to, newTokenId);
        return newTokenId;
    }

    function burn(uint256 tokenId) external override {
        require(msg.sender == ownerOf(tokenId), "ERC7702: caller is not the owner");
        _burn(tokenId);
    }

    function ownerOf(uint256 tokenId) public view override returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC7702: invalid token ID");
        return owner;
    }

    function name() public view override returns (string memory) {
        return _name;
    }

    function symbol() public view override returns (string memory) {
        return _symbol;
    }

    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        require(_exists(tokenId), "ERC7702: URI query for nonexistent token");
        return string(abi.encodePacked("<https://example.com/token/>", tokenId.toString()));
    }

    function totalSupply() public view override returns (uint256) {
        return _tokenIds.current();
    }

    function tokenByIndex(uint256 index) public view override returns (uint256) {
        require(index < totalSupply(), "ERC7702: global index out of bounds");
        return index + 1;
    }

    function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
        require(index < balanceOf(owner), "ERC7702: owner index out of bounds");
        return _ownedTokens[owner][index];
    }

    function balanceOf(address owner) public view returns (uint256) {
        return _ownedTokens[owner].length;
    }

    function _mint(address to, uint256 tokenId) internal {
        require(to != address(0), "ERC7702: mint to the zero address");
        require(!_exists(tokenId), "ERC7702: token already minted");

        _owners[tokenId] = to;
        _ownedTokens[to].push(tokenId);

        emit Minted(to, tokenId);
    }

    function _burn(uint256 tokenId) internal {
        address owner = ownerOf(tokenId);

        delete _owners[tokenId];
        _removeTokenFromOwnerEnumeration(owner, tokenId);

        emit Burned(owner, tokenId);
    }

    function _exists(uint256 tokenId) internal view returns (bool) {
        return _owners[tokenId] != address(0);
    }

    function _removeTokenFromOwnerEnumeration(address owner, uint256 tokenId) private {
        uint256 lastTokenIndex = _ownedTokens[owner].length - 1;
        uint256 tokenIndex;

        for (uint256 i = 0; i <= lastTokenIndex; i++) {
            if (_ownedTokens[owner][i] == tokenId) {
                tokenIndex = i;
                break;
            }
        }

        if (tokenIndex != lastTokenIndex) {
            _ownedTokens[owner][tokenIndex] = _ownedTokens[owner][lastTokenIndex];
        }
        _ownedTokens[owner].pop();
    }
}
```

This implementation provides a solid foundation for creating Soulbound Tokens following the EIP-7702 standard. Developers can extend and customize this base implementation to suit their specific use cases and requirements.


# ERC-7715

## 📜 ERC-7715: Modular Smart Contract Accounts

ERC-7715 introduces a standard for modular smart contract accounts, providing a flexible and extensible framework for account abstraction on the Ethereum blockchain.

### 🏗️ Architecture

The ERC-7715 standard defines a modular architecture for smart contract accounts, consisting of several key components:

<figure><img src="/files/f0cDr95H8N5qR4KDCOI9" alt=""><figcaption></figcaption></figure>

### 🧠 Core Concepts

#### 1. Account 👤

The main smart contract that represents the user's account. It manages modules and delegates calls to them.

#### 2. AccountRegistry 📚

A central registry that keeps track of all accounts and their associated modules.

#### 3. Modules 🧩

Interchangeable components that provide specific functionalities to the account:

* ExecutionModule: Handles the execution of transactions
* ValidationModule: Validates transactions before execution
* HookModule: Provides pre and post-execution hooks

#### 4. Fallback ↩️

A mechanism to handle calls to undefined functions, providing flexibility for future extensions.

### 🚶 User Flow

Here's a typical user flow for interacting with an ERC-7715 account:

<figure><img src="/files/bJdDqtGWHZDtMOkPUzfh" alt=""><figcaption></figcaption></figure>

### 💻 Implementation Details

#### Account Interface

```solidity
interface IERC7715Account {
    function execute(bytes calldata _data) external payable returns (bytes memory);
    function isValidSignature(bytes32 _hash, bytes memory _signature) external view returns (bytes4);
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
    // ... additional functions
}
```

#### Module Interface

```solidity
interface IERC7715Module {
    function isInitialized(address _account) external view returns (bool);
    function initialize(bytes calldata _data) external returns (bytes memory);
    // ... additional functions
}
```

#### AccountRegistry Interface

```solidity
interface IERC7715AccountRegistry {
    function registerAccount(address _account, address _owner) external;
    function isRegistered(address _account) external view returns (bool);
    function getAccountOwner(address _account) external view returns (address);
    // ... additional functions
}
```

### 🚀 Example Implementation

Here's a basic implementation of an ERC-7715 Account:

```solidity
pragma solidity ^0.8.0;

import "./IERC7715Account.sol";
import "./IERC7715Module.sol";

contract ERC7715Account is IERC7715Account {
    mapping(bytes4 => address) private modules;

    function execute(bytes calldata _data) external payable override returns (bytes memory) {
        address module = modules[bytes4(keccak256("execute(bytes)"))];
        require(module != address(0), "Execution module not set");
        return IERC7715Module(module).execute(_data);
    }

    function isValidSignature(bytes32 _hash, bytes memory _signature) external view override returns (bytes4) {
        address module = modules[bytes4(keccak256("isValidSignature(bytes32,bytes)"))];
        require(module != address(0), "Validation module not set");
        return IERC7715Module(module).isValidSignature(_hash, _signature);
    }

    function setModule(bytes4 _selector, address _module) external {
        // Add access control here
        modules[_selector] = _module;
    }

    function supportsInterface(bytes4 interfaceId) external view override returns (bool) {
        return interfaceId == type(IERC7715Account).interfaceId;
    }

    // Fallback function to handle undefined calls
    fallback() external payable {
        address fallbackModule = modules[bytes4(0)];
        if (fallbackModule != address(0)) {
            (bool success, ) = fallbackModule.delegatecall(msg.data);
            require(success, "Fallback call failed");
        }
    }
}
```

### 🔑 Key Features

* 🧩 Modular design for flexible functionality
* 🔄 Easy upgradeability of account features
* 🔒 Enhanced security through separate validation modules
* 🎣 Extensible with pre and post-execution hooks
* 🔌 Interoperability with existing Ethereum infrastructure

ERC-7715 provides a powerful framework for creating modular smart contract accounts, enabling developers to build sophisticated and adaptable account systems. This standard paves the way for more user-friendly and feature-rich blockchain applications while maintaining high levels of security and flexibility.


# ERC-7739

## 📜 ERC-7739: Modular Programmable Authorization

ERC-7739 introduces a standard for modular programmable authorization in smart contracts, providing a flexible and extensible framework for access control and permission management on the Ethereum blockchain.

### 🏗️ Architecture

The ERC-7739 standard defines a modular architecture for programmable authorization, consisting of several key components:

### 🧠 Core Concepts

#### 1. AuthorizationManager 🎛️

The main contract that manages authorization modules and policies. It acts as the central hub for all authorization-related operations.

#### 2. AuthorizationModule 🧩

Interchangeable components that implement specific authorization logic. Examples include:

* RoleBasedModule: Implements role-based access control
* TokenGatedModule: Implements token-gated access
* MultiSigModule: Implements multi-signature authorization

#### 3. PolicyEngine 🚦

Manages and evaluates authorization policies. It consists of:

* PolicyRegistry: Stores and manages authorization policies
* PolicyEvaluator: Evaluates policies against authorization requests

### 🚶 User Flow

Here's a typical user flow for interacting with an ERC-7739 system:

<figure><img src="/files/wkY7NKMDZuxV4mc79vNG" alt=""><figcaption></figcaption></figure>

### 💻 Implementation Details

#### AuthorizationManager Interface

```solidity
interface IAuthorizationManager {
    function isAuthorized(address user, bytes4 functionSelector, bytes calldata data) external view returns (bool);
    function addModule(address module) external;
    function removeModule(address module) external;
    function setPolicy(bytes32 policyId, bytes calldata policyData) external;
    // ... additional functions
}
```

#### AuthorizationModule Interface

```solidity
interface IAuthorizationModule {
    function checkAuthorization(address user, bytes4 functionSelector, bytes calldata data) external view returns (bool);
    function initialize(bytes calldata data) external;
    // ... additional functions
}
```

#### PolicyEngine Interface

```solidity
interface IPolicyEngine {
    function evaluatePolicy(bytes32 policyId, address user, bytes4 functionSelector, bytes calldata data) external view returns (bool);
    function setPolicy(bytes32 policyId, bytes calldata policyData) external;
    // ... additional functions
}
```

### 🚀 Example Implementation

Here's a basic implementation of an ERC-7739 AuthorizationManager:

```solidity
pragma solidity ^0.8.0;

import "./IAuthorizationManager.sol";
import "./IAuthorizationModule.sol";
import "./IPolicyEngine.sol";

contract AuthorizationManager is IAuthorizationManager {
    mapping(address => bool) private modules;
    IPolicyEngine public policyEngine;

    constructor(address _policyEngine) {
        policyEngine = IPolicyEngine(_policyEngine);
    }

    function isAuthorized(address user, bytes4 functionSelector, bytes calldata data) external view override returns (bool) {
        bool moduleAuthorized = false;
        for (address module in modules) {
            if (IAuthorizationModule(module).checkAuthorization(user, functionSelector, data)) {
                moduleAuthorized = true;
                break;
            }
        }
        
        if (!moduleAuthorized) {
            return false;
        }

        return policyEngine.evaluatePolicy(keccak256(abi.encodePacked(user, functionSelector)), user, functionSelector, data);
    }

    function addModule(address module) external override {
        // Add access control here
        modules[module] = true;
    }

    function removeModule(address module) external override {
        // Add access control here
        delete modules[module];
    }

    function setPolicy(bytes32 policyId, bytes calldata policyData) external override {
        // Add access control here
        policyEngine.setPolicy(policyId, policyData);
    }
}
```

### 🔑 Key Features

* 🧩 Modular design for flexible authorization logic
* 🔄 Easy upgradeability of authorization mechanisms
* 🔒 Enhanced security through separate authorization modules
* 📜 Programmable policies for fine-grained access control
* 🔌 Interoperability with existing Ethereum smart contracts

ERC-7739 provides a powerful framework for creating modular and programmable authorization systems, enabling developers to build sophisticated and adaptable access control mechanisms. This standard paves the way for more secure and flexible smart contract interactions while maintaining high levels of customizability and extensibility.


# EIP-6780

## EIP-6780: SELFDESTRUCT Only in CREATE 💥

EIP-6780 proposes to limit the use of the SELFDESTRUCT opcode, which has been a source of complexity and potential security issues in Ethereum smart contracts.

Key aspects of EIP-6780:

* Restricts the SELFDESTRUCT opcode to only be callable during contract creation
* Prevents the use of SELFDESTRUCT after a contract has been deployed
* Aims to simplify the Ethereum protocol and improve security

Rationale behind EIP-6780:

* Reduces potential attack vectors related to contract self-destruction
* Simplifies the reasoning about contract behavior and state
* Facilitates future optimizations in Ethereum clients

This EIP is part of the ongoing efforts to improve Ethereum's security and reduce complexity in smart contract development. By limiting SELFDESTRUCT, it helps prevent unexpected contract removals and simplifies the overall protocol.


# EIP-5792

## 📜 EIP-5792: Wallet Contract Interface

EIP-5792 introduces a standard interface for wallet contracts in the Ethereum ecosystem. This page provides a comprehensive overview of its architecture, core concepts, user flow, and implementation details.

### 🏗️ Architecture

The EIP-5792 standard defines a set of interfaces and functionalities for wallet contracts. Here's a high-level overview of the architecture:

<figure><img src="/files/VFwHOIvZFNRgeZ5b7DWA" alt=""><figcaption></figcaption></figure>

### 🧠 Core Concepts

#### 1. Wallet Contract 👛

A smart contract that implements the EIP-5792 interface, allowing it to act as a programmable wallet with advanced features.

#### 2. Signature Validation ✅

The ability to verify signatures, enabling secure transaction authorization.

#### 3. Transaction Execution 🚀

Methods for executing single and batch transactions, providing flexibility in wallet operations.

#### 4. Nonce Management 🔢

A mechanism to prevent replay attacks and ensure transaction uniqueness.

### 🚶 User Flow

Here's a typical user flow for interacting with an EIP-5792 wallet contract:

<figure><img src="/files/fZu09DtsSYOxI1HqEzU2" alt=""><figcaption></figcaption></figure>

### 💻 Implementation Details

#### Wallet Contract Interface

```solidity
interface IERC5792 {
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
    function executeCall(address to, uint256 value, bytes memory data) external payable returns (bytes memory);
    function executeBatch(address[] memory to, uint256[] memory value, bytes[] memory data) external payable returns (bytes[] memory);
    function nonce() external view returns (uint256);
}
```

#### Example Implementation

Here's a basic implementation of an ERC-5792 Wallet Contract:

```solidity
pragma solidity ^0.8.0;

import "./IERC5792.sol";

contract ERC5792Wallet is IERC5792 {
    address public owner;
    uint256 private _nonce;

    constructor(address _owner) {
        owner = _owner;
    }

    function isValidSignature(bytes32 hash, bytes memory signature) external view override returns (bytes4 magicValue) {
        if (recoverSigner(hash, signature) == owner) {
            return 0x1626ba7e; // EIP-1271 magic value
        }
        return 0xffffffff;
    }

    function executeCall(address to, uint256 value, bytes memory data) external payable override returns (bytes memory) {
        require(msg.sender == owner, "Not authorized");
        _nonce++;
        (bool success, bytes memory result) = to.call{value: value}(data);
        require(success, "Call failed");
        return result;
    }

    function executeBatch(address[] memory to, uint256[] memory value, bytes[] memory data) external payable override returns (bytes[] memory) {
        require(msg.sender == owner, "Not authorized");
        require(to.length == value.length && to.length == data.length, "Array length mismatch");
        _nonce++;
        bytes[] memory results = new bytes[](to.length);
        for (uint256 i = 0; i < to.length; i++) {
            (bool success, bytes memory result) = to[i].call{value: value[i]}(data[i]);
            require(success, "Call failed");
            results[i] = result;
        }
        return results;
    }

    function nonce() external view override returns (uint256) {
        return _nonce;
    }

    function recoverSigner(bytes32 hash, bytes memory signature) internal pure returns (address) {
        require(signature.length == 65, "Invalid signature length");
        bytes32 r;
        bytes32 s;
        uint8 v;
        assembly {
            r := mload(add(signature, 32))
            s := mload(add(signature, 64))
            v := byte(0, mload(add(signature, 96)))
        }
        if (v < 27) v += 27;
        require(v == 27 || v == 28, "Invalid signature 'v' value");
        return ecrecover(hash, v, r, s);
    }
}
```

### 🔑 Key Features

* 🔐 Secure signature validation for transaction authorization
* 🚀 Flexible execution of single and batch transactions
* 🔢 Nonce management to prevent replay attacks
* 🔌 Interoperability with existing Ethereum infrastructure
* 🧩 Extensibility for custom wallet implementations

EIP-5792 provides a robust framework for creating standardized wallet contracts, enabling developers to build sophisticated and secure wallet solutions. This standard paves the way for more user-friendly and feature-rich blockchain applications while maintaining high levels of security and flexibility.


# ERC-4626

## ERC-4626: Tokenized Vault Standard

Welcome to my comprehensive guide on **ERC-4626**, the Tokenized Vault Standard. This page demonstrates my deep understanding of ERC-4626 and provides insights into its implementation, benefits, and real-world applications.

***

### **Introduction to ERC-4626**

**ERC-4626** is a technical standard for tokenized vault implementations, designed to optimize and unify the technical parameters of yield-bearing vaults. It extends **ERC-20** to establish a standardized API for tokenized vaults that represent shares of a single underlying ERC-20 token.

***

### **Key Concepts**

1. **Standardized Vault Interface**: Unified structure for integrating with DeFi protocols.
2. **Share-Based Accounting**: Ownership represented via shares proportional to deposited assets.
3. **Underlying Token Integration**: Compatibility with ERC-20 tokens.
4. **Deposit/Withdrawal Mechanisms**: Simplified interaction for users.

<figure><img src="/files/YhZxY6p3BPVwxXDhDSgV" alt=""><figcaption></figcaption></figure>

***

### **Technical Implementation**

Below is a basic implementation of an ERC-4626-compliant vault:

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract ERC4626Vault is ERC20 {
    IERC20 public immutable asset;

    constructor(
        IERC20 _asset,
        string memory _name,
        string memory _symbol
    ) ERC20(_name, _symbol) {
        asset = _asset;
    }

    // Core Functions
    function deposit(uint256 assets, address receiver) public returns (uint256 shares) {
        // Implementation
    }

    function withdraw(uint256 assets, address receiver, address owner) public returns (uint256 shares) {
        // Implementation
    }

    // View Functions
    function totalAssets() public view returns (uint256) {
        // Implementation
    }

    function convertToShares(uint256 assets) public view returns (uint256) {
        // Implementation
    }

    function convertToAssets(uint256 shares) public view returns (uint256) {
        // Implementation
    }
}
```

***

#### **Core Functions**

**`deposit(uint256 assets, address receiver)`**

* Users deposit assets to receive shares based on the current exchange rate.

**`withdraw(uint256 assets, address receiver, address owner)`**

* Burns shares and transfers equivalent assets to the receiver.

**`redeem(uint256 shares, address receiver, address owner)`**

* Similar to withdraw but takes shares as input instead of assets.

#### **View Functions**

| Function            | Description                                           |
| ------------------- | ----------------------------------------------------- |
| `totalAssets()`     | Returns the total amount of underlying assets.        |
| `convertToShares()` | Calculates shares minted for a given asset amount.    |
| `convertToAssets()` | Calculates assets withdrawn for a given share amount. |

***

### **Benefits and Use Cases**

1. **Standardized Integration**: Simplifies adoption across DeFi protocols.
2. **Simplified Yield-Bearing Tokens**: Reduces development complexity.
3. **Composability**: Better interaction across different protocols.
4. **Efficient Audits**: Unified design lowers audit costs.

***

### **Implementation Considerations**

* **Rounding Mechanisms**: Ensure accurate share calculations.
* **Security Measures**: Address reentrancy and integer overflows.
* **Gas Optimization**: Optimize for lower transaction costs.
* **Integration**: Seamlessly integrate with existing protocols.

#### **Security Best Practices**

* Implement access controls.
* Use safe math operations.
* Add emergency pause mechanisms.
* Conduct thorough audits.

***

### **Common Integration Patterns**

```solidity
interface IERC4626 is IERC20 {
    function asset() external view returns (address assetTokenAddress);
    function totalAssets() external view returns (uint256 totalManagedAssets);
    function convertToShares(uint256 assets) external view returns (uint256 shares);
    function convertToAssets(uint256 shares) external view returns (uint256 assets);
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
```

***

### **Testing and Verification**

#### Sample Tests

```javascript
describe("ERC4626Vault", function() {
    it("should correctly deposit assets and mint shares", async function() {
        const depositAmount = ethers.utils.parseEther("100");
        await vault.deposit(depositAmount, user.address);

        const shares = await vault.balanceOf(user.address);
        expect(shares).to.be.gt(0);
    });

    it("should correctly withdraw assets and burn shares", async function() {
        const withdrawAmount = ethers.utils.parseEther("50");
        await vault.withdraw(withdrawAmount, user.address, user.address);

        const remainingAssets = await vault.totalAssets();
        expect(remainingAssets).to.be.lt(initialAssets);
    });
});
```

***

### **Future Developments**

ERC-4626 evolves alongside DeFi. Potential improvements include:

* Advanced yield strategies.
* Cross-chain compatibility.
* Enhanced security features.

Stay updated with developments via the [Ethereum Improvement Proposals (EIPs)](https://eips.ethereum.org/).

***

### **Simplified Guide to ERC-4626**

Think of ERC-4626 as a digital safe deposit box for your tokens.

#### **How It Works**

1. **Deposit Tokens**: Receive shares in return.
2. **Earn Yield**: Vault strategies grow your assets.
3. **Withdraw Tokens**: Return shares to retrieve assets + yield.

***

### **Why Choose ERC-4626?**

* **Easy to Use**: Unified interface for deposits and withdrawals.
* **Yield Opportunities**: Earn passive income on your tokens.
* **Interoperability**: Works seamlessly across protocols.


# EIP-1559

## **EIP-1559: Ethereum's Fee Market Revolution**

### Introduction

EIP-1559 (Ethereum Improvement Proposal 1559) is a significant upgrade to Ethereum's fee mechanism, implemented in August 2021 as part of the London Hard Fork. It fundamentally changed how transaction fees are calculated and processed on the Ethereum network.

### Key Concepts

* **Base Fee:** A dynamically adjusted fee that all users must pay for their transactions
* **Priority Fee (Tip):** An optional tip to incentivize miners/validators to process transactions faster
* **Fee Burning:** The base fee is burned (destroyed) rather than paid to miners
* **Block Size Flexibility:** Blocks can be up to 2x the target size to handle demand spikes

### How EIP-1559 Works

<figure><img src="/files/IGoqGfCpukNNbOsQpDTk" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/S4CyphEQMWaAEJM3ROPT" alt=""><figcaption></figcaption></figure>

### Technical Implementation

```solidity
// Example of sending a transaction with EIP-1559
const transaction = {
    to: receiverAddress,
    value: ethers.utils.parseEther("1.0"),
    maxFeePerGas: ethers.utils.parseUnits("50", "gwei"),     // Maximum fee willing to pay
    maxPriorityFeePerGas: ethers.utils.parseUnits("2", "gwei") // Tip for validators
};
```

### Benefits and Impact

* **Predictable Fees:** More reliable fee estimation and reduced price volatility
* **Improved User Experience:** Simpler fee market and reduced overpayment
* **Deflationary Mechanism:** Base fee burning reduces ETH supply over time
* **Network Security:** Better protection against spam attacks

### Before vs After EIP-1559

| **Aspect**         | **Before EIP-1559** | **After EIP-1559**                 |
| ------------------ | ------------------- | ---------------------------------- |
| Fee Structure      | Single gas price    | Base fee + priority fee            |
| Fee Recipient      | All to miners       | Base fee burned, tip to validators |
| Block Size         | Fixed               | Dynamic (up to 2x)                 |
| Fee Predictability | Highly volatile     | More predictable                   |

### Common Use Cases

* **DeFi Transactions:** More reliable fee estimation for DEX swaps and lending
* **NFT Minting:** Better handling of gas spikes during popular mints
* **Smart Contract Deployment:** More predictable deployment costs

### Best Practices

* Always set a reasonable maxFeePerGas to avoid excessive costs
* Monitor network conditions to optimize priority fees
* Implement proper error handling for fee-related issues
* Consider using EIP-1559-aware libraries and tools

### Challenges and Considerations

* **MEV Impact:** Relationship with Maximal Extractable Value
* **Network Congestion:** Handling of extreme network conditions
* **Validator Economics:** Changes to validator revenue model

This implementation has become a cornerstone of Ethereum's economic model, significantly improving the network's usability and efficiency while introducing a deflationary mechanism through fee burning.


# ERC-404

## Understanding ERC-404: A Hybrid Token Standard

ERC-404 is an experimental token standard that combines the features of both ERC-20 (fungible tokens) and ERC-721 (non-fungible tokens) into a single smart contract. It was introduced to solve specific challenges in the digital asset space and create more dynamic token interactions.

### Why ERC-404 Was Introduced

* To bridge the gap between fungible and non-fungible tokens
* To enable fractional ownership of NFTs in a more seamless way
* To reduce complexity in managing multiple token standards
* To create more liquid markets for NFT-like assets

<figure><img src="/files/DG8AvocpLs7nzfxO4Y2n" alt=""><figcaption></figcaption></figure>

### Key Concepts

The standard operates on these fundamental principles:

* **Automatic Minting/Burning:** NFTs are automatically minted or burned based on token balance thresholds
* **Fungible Division:** Allows for fractional ownership through ERC-20 mechanics
* **Atomic Operations:** Ensures consistency between ERC-20 balances and NFT ownership

### Technical Structure

```solidity
// Basic ERC-404 Contract Structure
contract ERC404 is ERC20, ERC721 {
    uint256 public constant TOKENS_PER_NFT = 1e18;  // 1 NFT = 1 whole token
    
    mapping(uint256 => address) private _owners;
    mapping(address => uint256) private _balances;
    
    function _mintNFT(address to) internal {
        // Mint NFT logic
    }
    
    function _burnNFT(uint256 tokenId) internal {
        // Burn NFT logic
    }
}
```

### Workflow Diagram

```mermaid
graph TD;
    A["User initiates token transfer"] --> B{"Balance >= 1 whole token?"};
    B -- Yes --> C["Mint NFT"];
    B -- No --> D["Burn NFT"];
    C --> E["Update token balances"];
    D --> E;
    E --> F["Transaction complete"];
```

### How It Works

Let's break down the process:

1. When a user acquires enough tokens (typically 1.0), an NFT is automatically minted to their address
2. If their balance falls below the threshold, the NFT is automatically burned
3. The system maintains constant synchronization between token balances and NFT ownership
4. All operations are atomic, meaning they either complete fully or revert entirely

### Example Implementation

```solidity
// Example transfer function
function transfer(address to, uint256 amount) public returns (bool) {
    address from = msg.sender;
    
    // Pre-transfer NFT check
    uint256 fromNFTBalance = balanceOf(from) / TOKENS_PER_NFT;
    uint256 toNFTBalance = balanceOf(to) / TOKENS_PER_NFT;
    
    // Perform ERC20 transfer
    _transfer(from, to, amount);
    
    // Post-transfer NFT adjustment
    uint256 newFromNFTBalance = balanceOf(from) / TOKENS_PER_NFT;
    uint256 newToNFTBalance = balanceOf(to) / TOKENS_PER_NFT;
    
    // Handle NFT minting/burning
    _adjustNFTBalances(from, fromNFTBalance, newFromNFTBalance);
    _adjustNFTBalances(to, toNFTBalance, newToNFTBalance);
    
    return true;
}
```

### Advantages of ERC-404

* **Simplified Management:** Single contract for both fungible and non-fungible functionality
* **Enhanced Liquidity:** Easier trading of fractional NFT ownership
* **Reduced Complexity:** No need for separate wrapper contracts
* **Gas Efficiency:** Optimized operations in a single contract

### Use Cases

* Fractional ownership of high-value NFTs
* Gaming assets with both fungible and non-fungible properties
* DeFi applications requiring hybrid token functionality
* Digital art platforms with fractional ownership models

### Limitations and Considerations

While ERC-404 offers unique advantages, it's important to consider:

* Experimental nature of the standard
* Potential gas costs for automatic minting/burning
* Complexity in implementing proper security measures
* Need for careful consideration of edge cases

### Best Practices

* Implement comprehensive testing for all possible scenarios
* Include proper access controls and security measures
* Document all functions and behaviors clearly
* Consider gas optimization in implementation

ERC-404 represents an innovative approach to token standards, offering new possibilities for digital asset management while requiring careful implementation and consideration of its experimental nature.

## Future Implications and Development

As ERC-404 continues to evolve, several key areas are emerging for future development:

* **Standardization Efforts:** Work towards official recognition and standardization within the Ethereum ecosystem
* **Enhanced Integration:** Development of improved tools and frameworks for easier implementation
* **Cross-chain Compatibility:** Exploration of cross-chain applications and interoperability solutions
* **Advanced Use Cases:** Development of more sophisticated applications leveraging the hybrid nature of the standard

### Conclusion

ERC-404 represents a significant innovation in blockchain token standards, offering a unique solution to the challenges of digital asset fractionalization and management. While still experimental, its potential impact on the future of digital assets and decentralized applications is substantial.

###


# ERC-3643

## ERC-3643: Ushering in a New Era of Real-World Asset Tokenization

The blockchain and decentralized finance landscape is rapidly evolving, introducing innovations that redefine asset ownership and investment. Among these advancements is ERC-3643, a standard poised to revolutionize the tokenization and trading of real-world assets (RWAs).

### **What is ERC-3643?**

ERC-3643, also known as the T-REX protocol (Token for Regulated Exchange), is a groundbreaking technical standard developed on the Ethereum blockchain. Designed for tokenizing RWAs, this open-source suite of smart contracts facilitates the issuance, management, and transfer of permissioned tokens, representing ownership or fractional ownership of tangible assets like real estate, art, and commodities.

ERC-3643 integrates blockchain's transparency with compliance mechanisms to ensure tokenized assets adhere to regulations and foster investor trust. Below, we explore its defining features and functionalities.

***

### **How ERC-3643 Works**

ERC-3643 employs permissioned tokens and digital identity verification to embed regulatory compliance directly into the protocol’s design. Transfers occur only when the investor’s digital identity (via ONCHAINID) and offering rules are validated, ensuring adherence to regulations.

***

### **Key Features**

#### **1. Regulatory Compliance**

ERC-3643 addresses the complexities of navigating regulatory frameworks by embedding compliance mechanisms directly within its standard. The protocol integrates Know Your Customer (KYC) and Anti-Money Laundering (AML) checks, streamlining processes and fostering trust among participants.

For example, an investor purchasing a tokenized fraction of a beachfront property undergoes automated KYC/AML checks before the transaction is processed, ensuring compliance from the outset.

#### **2. Enhanced Security and Transparency**

Leveraging Ethereum’s blockchain, ERC-3643 tokens offer immutability and transparency. Every transaction is publicly recorded, reducing fraud risk and ensuring token authenticity. This secure environment protects both investors and issuers.

#### **3. Streamlined Tokenization and Interoperability**

Built upon the widely adopted ERC-20 standard, ERC-3643 simplifies development and integration. This interoperability extends to Ethereum-based decentralized finance (DeFi) protocols, enabling innovative financial products and services for tokenized assets.

#### **4. Fractional Ownership and Liquidity**

ERC-3643 enables fractional ownership by dividing assets into smaller, tradable units. This feature democratizes access to markets previously restricted by high entry barriers. Additionally, ERC-3643 tokens can be traded on Ethereum’s secondary markets, enhancing liquidity and facilitating efficient asset allocation.

***

### **Technical Overview**

#### **Core Components**

<figure><img src="/files/rquV7CgPq29BhV0uacox" alt=""><figcaption></figcaption></figure>

* **Token Contract:** Implements the ERC-3643 standard
* **Identity Registry:** Manages user identities and verifies participants
* **Transfer Manager:** Enforces compliance rules during transactions
* **Compliance Service:** Ensures regulatory adherence

#### **Workflow**

<figure><img src="/files/hwnurylsW97kyb97CyW4" alt=""><figcaption></figcaption></figure>

***

### **Code Example**

```solidity
// ERC-3643 Token Implementation
contract TREXToken is ERC3643 {
    constructor(
        string memory _name,
        string memory _symbol,
        address _identityRegistry,
        address _compliance
    ) {
        name = _name;
        symbol = _symbol;
        identityRegistry = IIdentityRegistry(_identityRegistry);
        compliance = ICompliance(_compliance);
    }

    function transfer(address _to, uint256 _amount) public override returns (bool) {
        require(identityRegistry.isVerified(msg.sender), "Sender not verified");
        require(identityRegistry.isVerified(_to), "Receiver not verified");
        require(compliance.canTransfer(msg.sender, _to, _amount), "Transfer not compliant");

        _transfer(msg.sender, _to, _amount);
        return true;
    }
}
```

***

### **Advantages Over Traditional Standards**

| **Feature**         | **ERC-20** | **ERC-3643**  |
| ------------------- | ---------- | ------------- |
| Compliance Checks   | Manual     | Automated     |
| Identity Management | None       | Built-in      |
| Transfer Controls   | Basic      | Advanced      |
| Regulatory Support  | Limited    | Comprehensive |

***

### **Real-World Applications**

#### **1. Security Token Offerings (STOs)**

ERC-3643 streamlines the tokenization of regulated financial instruments, such as securities, enabling automated compliance.

#### **2. Fractional Ownership of Tangible Assets**

Platforms like RealT and Codex Protocol utilize ERC-3643 to tokenize real estate, artworks, and collectibles, democratizing access to high-value markets.

#### **3. Supply Chain and Loyalty Programs**

The protocol facilitates efficient tokenization of supply chain assets and loyalty programs, creating new use cases for blockchain technology.

***

### **Conclusion**

ERC-3643 is transforming the tokenization of regulated assets by integrating compliance mechanisms directly into blockchain protocols. It ensures transparency, enhances security, and democratizes access to traditionally exclusive markets. As regulatory frameworks evolve, ERC-3643 will play a pivotal role in shaping the future of real-world asset tokenization, bridging the gap between physical and digital realms.


# ERC-223

## ERC-223: An Enhanced Token Standard

### Introduction

ERC-223 is a token standard for Ethereum, proposed as an improvement to the widely used ERC-20 standard. It introduces mechanisms to address critical shortcomings of ERC-20, such as accidental token losses and inefficient gas usage. By defining a new communication model for token transfers, ERC-223 provides a more robust and user-friendly framework for token interactions.

***

### What is ERC-223?

ERC-223 is similar to ERC-20 but extends its functionality by:

* Handling token transfers on the recipient's side.
* Preventing the loss of tokens sent to incompatible contracts.
* Supporting metadata in token transfers for additional transaction context.

***

### Key Features and Differences

#### Improvements Over ERC-20

1. **Recipient Awareness**
   * ERC-223 tokens can only be transferred to contracts that implement the `tokenReceived` function.
   * Prevents tokens from being permanently lost if sent to non-compatible contracts.
2. **Efficient Transactions**
   * Uses a single `transfer` method instead of separate `approve` and `transferFrom`.
   * Reduces gas consumption by eliminating unnecessary calls.
3. **Metadata Support**
   * Allows metadata to be included with transfers, enabling context-specific actions.

***

### Workflow Diagram

<figure><img src="/files/n2gkjTOjmtdk0ZEs2H0I" alt=""><figcaption></figcaption></figure>

***

### ERC-223 Implementation

An ERC-223 token must define specific methods and events, as described in [EIP-223](https://eips.ethereum.org/EIPS/eip-223).

#### Required Methods

```solidity
function name() public view returns (string);
function symbol() public view returns (string);
function decimals() public view returns (uint8);
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transfer(address _to, uint256 _value, bytes calldata _data) public returns (bool success);
```

#### Events

```solidity
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes calldata _data);
```

#### Recipient Contract Requirements

Contracts receiving ERC-223 tokens must implement:

```solidity
function tokenReceived(address _from, uint _value, bytes calldata _data);
```

If the recipient contract does not implement this function, the transaction fails, and tokens remain with the sender.

***

### Example Implementation

#### ERC-223 Token Contract

```solidity
pragma solidity ^0.8.19;

abstract contract IERC223Recipient {
    function tokenReceived(address _from, uint _value, bytes memory _data) public virtual;
}

contract ERC223Token {
    event Transfer(address indexed from, address indexed to, uint value, bytes data);
    mapping(address => uint256) private balances;

    function transfer(address _to, uint _value, bytes calldata _data) public returns (bool success) {
        balances[msg.sender] -= _value;
        balances[_to] += _value;
        if (isContract(_to)) {
            IERC223Recipient(_to).tokenReceived(msg.sender, _value, _data);
        }
        emit Transfer(msg.sender, _to, _value, _data);
        return true;
    }

    function isContract(address account) internal view returns (bool) {
        uint256 size;
        assembly { size := extcodesize(account) }
        return size > 0;
    }
}
```

#### Recipient Contract

```solidity
pragma solidity ^0.8.19;

contract RecipientContract is IERC223Recipient {
    event Deposit(address indexed sender, uint value);
    uint256 public deposits;

    function tokenReceived(address _from, uint _value, bytes memory _data) public override {
        deposits += _value;
        emit Deposit(_from, _value);
    }
}
```

***

### Advantages of ERC-223

* **Safety**: Tokens cannot be accidentally lost by sending them to incompatible contracts.
* **Efficiency**: Reduces gas costs by requiring fewer transactions.
* **Extensibility**: Supports metadata for enhanced functionality.

***

### Limitations

* **Adoption**: ERC-223 is not yet widely adopted, limiting compatibility.
* **Backward Compatibility**: Existing ERC-20 tools and contracts require modifications to support ERC-223.
* **Gas Costs**: The additional recipient checks may increase transaction costs in some scenarios.


# Web3 Toolkits


# Foundry

### 1. Introduction to Foundry 🏗️

Foundry is a blazing fast, portable, and modular toolkit for Ethereum application development. It's designed to make smart contract development, testing, and deployment more efficient and developer-friendly.

### 2. Installation and Setup 🔧

To install Foundry, follow these steps:

```bash
# Install Foundry
curl -L <https://foundry.paradigm.xyz> | bash

# Update PATH and load env variables
source ~/.bashrc

# Install Foundry components
foundryup
```

After installation, verify the setup:

```bash
forge --version
cast --version
anvil --version
```

### 3. Core Concepts 🧠

Foundry consists of three main components:

* **Forge:** A testing framework for Ethereum smart contracts
* **Cast:** A command-line tool for interacting with Ethereum RPC nodes
* **Anvil:** A local Ethereum node for development purposes
* **Chisel**: An interactive Solidity REPL (Read-Eval-Print Loop) for quick experimentation and debugging

### 4. Key Features 🌟

* Fast compilation and testing
* Solidity-native testing
* Flexible debugging
* Fuzz testing
* Gas optimization
* Forking capabilities

### 5. Foundry Architecture 🏛️

<figure><img src="/files/MtLO9Kb4XOMj5GbVlZZM" alt=""><figcaption></figcaption></figure>

### 6. User Flow 🔄

<figure><img src="/files/6Sp3qaRsxHx60eKtkBF3" alt=""><figcaption></figcaption></figure>

### 7. Solidity Basics to Advanced Concepts 📚

#### 7.1 Basic Structure of a Solidity Contract

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MyContract {
    // State variables
    uint256 public myNumber;

    // Constructor
    constructor(uint256 _initialNumber) {
        myNumber = _initialNumber;
    }

    // Functions
    function setNumber(uint256 _newNumber) public {
        myNumber = _newNumber;
    }

    function getNumber() public view returns (uint256) {
        return myNumber;
    }
}
```

#### 7.2 Advanced Solidity Concepts

#### 7.2.1 Inheritance and Interfaces

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface ICounter {
    function increment() external;
    function getCount() external view returns (uint256);
}

contract Counter is ICounter {
    uint256 private count;

    function increment() external override {
        count++;
    }

    function getCount() external view override returns (uint256) {
        return count;
    }
}

contract AdvancedCounter is Counter {
    function incrementBy(uint256 _value) external {
        for (uint256 i = 0; i < _value; i++) {
            increment();
        }
    }
}
```

#### 7.2.2 Libraries and Using For

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

library MathLib {
    function square(uint256 _a) internal pure returns (uint256) {
        return _a * _a;
    }
}

contract MathContract {
    using MathLib for uint256;

    function calculateSquare(uint256 _number) public pure returns (uint256) {
        return _number.square();
    }
}
```

#### 7.2.3 Events and Indexed Parameters

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract EventExample {
    event Transfer(address indexed from, address indexed to, uint256 amount);

    function transfer(address _to, uint256 _amount) public {
        // Transfer logic here
        emit Transfer(msg.sender, _to, _amount);
    }
}
```

### 8. Foundry Commands and Usage 🖥️

#### 8.1 Forge Commands

* **forge build:** Compile all contracts in the project
* **forge test:** Run all tests in the project
* **forge create:** Deploy a contract
* **forge verify-contract:** Verify a deployed contract on Etherscan

#### 8.2 Cast Commands

* **cast call:** Perform a call to a contract without publishing a transaction
* **cast send:** Send a transaction to a contract
* **cast estimate:** Estimate the gas cost of a transaction

#### 8.3 Anvil Commands

* **anvil:** Start a local Ethereum node
* **anvil --fork-url:** Start a node that forks from a specified network

#### 8.4 Verbosity Levels in Foundry Commands

Foundry commands support different verbosity levels, which can be very useful for debugging and getting more detailed information about your operations. These levels are:

* **-v:** Displays basic logs and errors
* **-vv:** Shows more detailed logs, including emitted events
* **-vvv:** Provides even more information, including gas usage for each call
* **-vvvv:** Offers the most detailed output, including stack traces for errors

Example usage:

```bash
forge test -vv
forge create --rpc-url &lt;your_rpc_url&gt; -vvv
```

These verbosity levels can be applied to most Foundry commands, allowing you to tailor the output to your specific needs during development, testing, and deployment processes.

### 9. Real-world Examples 🌍

#### 9.1 DEX (Decentralized Exchange) Smart Contract

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract SimpleDEX {
    mapping(address => mapping(address => uint256)) public tokenBalances;

    event Deposit(address user, address token, uint256 amount);
    event Withdraw(address user, address token, uint256 amount);
    event Trade(address user, address tokenGive, uint256 amountGive, address tokenGet, uint256 amountGet);

    function deposit(address _token, uint256 _amount) external {
        require(IERC20(_token).transferFrom(msg.sender, address(this), _amount), "Transfer failed");
        tokenBalances[msg.sender][_token] += _amount;
        emit Deposit(msg.sender, _token, _amount);
    }

    function withdraw(address _token, uint256 _amount) external {
        require(tokenBalances[msg.sender][_token] >= _amount, "Insufficient balance");
        tokenBalances[msg.sender][_token] -= _amount;
        require(IERC20(_token).transfer(msg.sender, _amount), "Transfer failed");
        emit Withdraw(msg.sender, _token, _amount);
    }

    function trade(address _tokenGive, uint256 _amountGive, address _tokenGet, uint256 _amountGet) external {
        require(tokenBalances[msg.sender][_tokenGive] >= _amountGive, "Insufficient balance");
        require(tokenBalances[address(this)][_tokenGet] >= _amountGet, "Insufficient liquidity");

        tokenBalances[msg.sender][_tokenGive] -= _amountGive;
        tokenBalances[address(this)][_tokenGive] += _amountGive;
        tokenBalances[msg.sender][_tokenGet] += _amountGet;
        tokenBalances[address(this)][_tokenGet] -= _amountGet;

        emit Trade(msg.sender, _tokenGive, _amountGive, _tokenGet, _amountGet);
    }
}
```

### 10. Benefits of Using Foundry 🚀

* Faster development cycle
* Improved testing capabilities
* Better debugging tools
* Gas optimization features
* Seamless integration with existing Solidity projects

### 11. Core-level Engineering Concepts 🔬

#### 11.1 Gas Optimization

Gas optimization is crucial in Ethereum development. Here's an example of how to optimize gas usage:

```solidity
// Gas-inefficient
function sumArray(uint256[] memory numbers) public pure returns (uint256) {
    uint256 sum = 0;
    for (uint256 i = 0; i < numbers.length; i++) {
        sum += numbers[i];
    }
    return sum;
}

// Gas-optimized
function sumArrayOptimized(uint256[] memory numbers) public pure returns (uint256) {
    uint256 sum = 0;
    uint256 length = numbers.length;
    for (uint256 i = 0; i < length; i++) {
        sum += numbers[i];
    }
    return sum;
}
```

#### 11.2 Memory vs Storage

Understanding the difference between memory and storage is crucial for efficient smart contract development:

```solidity
contract MemoryVsStorage {
    uint256[] public myArray;

    // Uses storage - modifies the state
    function addToArray(uint256 _number) public {
        myArray.push(_number);
    }

    // Uses memory - doesn't modify the state
    function getArraySum() public view returns (uint256) {
        uint256[] memory tempArray = myArray;
        uint256 sum = 0;
        for (uint256 i = 0; i < tempArray.length; i++) {
            sum += tempArray[i];
        }
        return sum;
    }
}
```


# Hardhat

## Hardhat: A Comprehensive Guide for Solidity Development

Welcome to this detailed guide on Hardhat, an essential tool for Solidity and Ethereum development. This document will cover everything from basic concepts to advanced features, helping you become proficient in using Hardhat for your blockchain projects. 🚀

### 1. Introduction to Hardhat 🎩

Hardhat is a development environment designed for Ethereum software. It facilitates the process of compiling, deploying, testing, and debugging Ethereum applications. Hardhat is particularly well-suited for Solidity development, providing a robust set of tools and plugins to streamline the development workflow.

#### Key Benefits of Hardhat:

* 🔧 Flexible and extensible architecture
* 🚀 Fast compilation and testing
* 🐞 Advanced debugging capabilities
* 🔬 Built-in Solidity compiler
* 🌐 Easy integration with other tools and services

### 2. Installation and Setup 💻

#### Installing Hardhat

To install Hardhat, you need to have Node.js and npm (Node Package Manager) installed on your system. Once you have these prerequisites, you can install Hardhat using the following command:

```bash
npm install --save-dev hardhat
```

#### Creating a New Hardhat Project

To create a new Hardhat project, run the following command in your terminal:

```bash
npx hardhat
```

This will initiate the Hardhat setup wizard, which will guide you through the process of creating a new project.

#### Project Structure

A typical Hardhat project structure looks like this:

```
my-hardhat-project/
├── contracts/
│   └── MyContract.sol
├── scripts/
│   └── deploy.js
├── test/
│   └── MyContract.test.js
├── hardhat.config.js
└── package.json
```

### 3. Basic Concepts 🧠

#### Hardhat Runtime Environment (HRE)

The Hardhat Runtime Environment (HRE) is a key concept in Hardhat. It's an object containing all the functionality that Hardhat exposes when running a task, test, or script. The HRE is automatically created when Hardhat is run, and it's injected into the global scope.

#### Tasks

Tasks are the core building blocks of Hardhat. They are JavaScript async functions that can be run using the Hardhat CLI. Hardhat comes with built-in tasks, and you can also create your own custom tasks.

#### Plugins

Plugins are reusable pieces of configuration that can modify Hardhat's behavior and add new features. Many popular Ethereum tools are available as Hardhat plugins.

### 4. Core Features 🔑

#### Compilation

Hardhat includes a built-in Solidity compiler. You can compile your contracts using the following command:

```bash
npx hardhat compile
```

#### Testing

Hardhat provides a powerful testing framework. You can run your tests using:

```bash
npx hardhat test
```

#### Deployment

To deploy your contracts, you can use Hardhat scripts. Here's a basic example of a deployment script:

```jsx
const main = async () => {
  const [deployer] = await ethers.getSigners();
  console.log("Deploying contracts with the account:", deployer.address);

  const MyContract = await ethers.getContractFactory("MyContract");
  const myContract = await MyContract.deploy();

  console.log("MyContract address:", myContract.address);
};

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
```

Run the deployment script using:

```bash
npx hardhat run scripts/deploy.js --network <network-name>
```

#### Console

Hardhat provides an interactive JavaScript console for interacting with your contracts. Start it with:

```bash
npx hardhat console
```

### 5. Hardhat Architecture 🏗️

Here's a high-level overview of Hardhat's architecture:

### 6. User Flow 🔄

A typical user flow in a Hardhat project might look like this:

<figure><img src="/files/3T7wNs42t1rV4QaLZyrb" alt=""><figcaption></figcaption></figure>

### 7. Solidity Development with Hardhat 💻

#### Writing Solidity Contracts

Here's an example of a simple Solidity contract:

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private storedData;

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}
```

#### Testing Contracts

Here's an example of how to test the SimpleStorage contract using Hardhat and Chai:

```jsx
const { expect } = require("chai");

describe("SimpleStorage", function () {
  it("Should store and retrieve the value", async function () {
    const SimpleStorage = await ethers.getContractFactory("SimpleStorage");
    const simpleStorage = await SimpleStorage.deploy();
    await simpleStorage.deployed();

    await simpleStorage.set(42);
    expect(await simpleStorage.get()).to.equal(42);
  });
});
```

### 8. Advanced Concepts 🚀

#### Gas Optimization

Hardhat can help you optimize your contracts for gas usage. Here's an example of using the gas reporter:

```jsx
// In your hardhat.config.js
require("hardhat-gas-reporter");

module.exports = {
  gasReporter: {
    enabled: true,
    currency: 'USD',
    gasPrice: 21
  }
};
```

#### Forking Mainnet

Hardhat allows you to fork the Ethereum mainnet for testing purposes:

```jsx
// In your hardhat.config.js
module.exports = {
  networks: {
    hardhat: {
      forking: {
        url: "<https://eth-mainnet.alchemyapi.io/v2/YOUR-API-KEY>",
      }
    }
  }
};
```

### 9. Real-world Examples 🌍

#### DeFi Yield Farming Contract

Here's a simplified example of a yield farming contract:

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract YieldFarm is ReentrancyGuard {
    IERC20 public stakingToken;
    IERC20 public rewardToken;

    uint256 private constant REWARD_RATE = 1e18; // 1 token per second
    uint256 private lastUpdateTime;
    uint256 private rewardPerTokenStored;

    mapping(address => uint256) private userRewardPerTokenPaid;
    mapping(address => uint256) private rewards;
    mapping(address => uint256) private _balances;

    uint256 private _totalSupply;

    constructor(address _stakingToken, address _rewardToken) {
        stakingToken = IERC20(_stakingToken);
        rewardToken = IERC20(_rewardToken);
    }

    function stake(uint256 amount) external nonReentrant updateReward(msg.sender) {
        require(amount > 0, "Cannot stake 0");
        _totalSupply += amount;
        _balances[msg.sender] += amount;
        stakingToken.transferFrom(msg.sender, address(this), amount);
    }

    function withdraw(uint256 amount) external nonReentrant updateReward(msg.sender) {
        require(amount > 0, "Cannot withdraw 0");
        _totalSupply -= amount;
        _balances[msg.sender] -= amount;
        stakingToken.transfer(msg.sender, amount);
    }

    function getReward() external nonReentrant updateReward(msg.sender) {
        uint256 reward = rewards[msg.sender];
        if (reward > 0) {
            rewards[msg.sender] = 0;
            rewardToken.transfer(msg.sender, reward);
        }
    }

    function rewardPerToken() public view returns (uint256) {
        if (_totalSupply == 0) {
            return rewardPerTokenStored;
        }
        return
            rewardPerTokenStored +
            (((block.timestamp - lastUpdateTime) * REWARD_RATE * 1e18) / _totalSupply);
    }

    function earned(address account) public view returns (uint256) {
        return
            ((_balances[account] *
                (rewardPerToken() - userRewardPerTokenPaid[account])) / 1e18) +
            rewards[account];
    }

    modifier updateReward(address account) {
        rewardPerTokenStored = rewardPerToken();
        lastUpdateTime = block.timestamp;
        if (account != address(0)) {
            rewards[account] = earned(account);
            userRewardPerTokenPaid[account] = rewardPerTokenStored;
        }
        _;
    }
}
```

### 10. Best Practices and Tips 💡

* 🔒 Always use the latest version of Solidity and keep your dependencies up to date
* 🧪 Write comprehensive tests for your contracts
* 📊 Use gas reporting to optimize your contracts
* 🔍 Leverage Hardhat's debugging capabilities to troubleshoot issues
* 🔧 Make use of Hardhat's extensive plugin ecosystem
* 📚 Keep your project well-documented
* 🔁 Use version control (like Git) to manage your project


# RemixIDE

### 1. Introduction to RemixIDE 🌟

RemixIDE is a powerful, open-source tool for writing, testing, and deploying smart contracts in Solidity. It provides a user-friendly interface for developers to create, debug, and interact with Ethereum-based applications.

### 2. Installation and Setup 🛠️

#### 2.1 Browser-based Usage

The easiest way to use RemixIDE is through your web browser:

1. Open your preferred web browser
2. Navigate to <https://remix.ethereum.org>
3. Start coding immediately!

#### 2.2 Local Installation

For offline use or improved performance, you can install RemixIDE locally:

```shell
# Install RemixIDE globally using npm
npm install -g @remix-project/remix-ide

# Start RemixIDE
remix-ide
```

After running these commands, RemixIDE will be available at `http://localhost:8080`.

### 3. Basic Solidity Concepts 📚

#### 3.1 Contract Structure

A basic Solidity contract structure looks like this:

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MyContract {
    // State variables
    uint public myNumber;

    // Constructor
    constructor(uint _initialNumber) {
        myNumber = _initialNumber;
    }

    // Functions
    function setNumber(uint _newNumber) public {
        myNumber = _newNumber;
    }

    function getNumber() public view returns (uint) {
        return myNumber;
    }
}
```

#### 3.2 Data Types

Solidity supports various data types:

* Integers: `int`, `uint`
* Boolean: `bool`
* Address: `address`
* Bytes: `bytes1` to `bytes32`
* String: `string`
* Arrays: `uint[]`, `string[]`
* Mapping: `mapping(key => value)`

#### 3.3 Functions

Functions in Solidity can have different visibility and state mutability specifiers:

```solidity
contract FunctionExample {
    uint private data;

    // Public function that can modify state
    function setData(uint _value) public {
        data = _value;
    }

    // View function that doesn't modify state
    function getData() public view returns (uint) {
        return data;
    }

    // Pure function that doesn't access state
    function add(uint a, uint b) public pure returns (uint) {
        return a + b;
    }
}
```

### 4. Advanced Solidity Concepts 🚀

#### 4.1 Inheritance

Solidity supports multiple inheritance:

```solidity
contract Owned {
    address public owner;

    constructor() {
        owner = msg.sender;
    }

    modifier onlyOwner {
        require(msg.sender == owner, "Not the owner");
        _;
    }
}

contract Destructible is Owned {
    function destroy() public onlyOwner {
        selfdestruct(payable(owner));
    }
}

contract MyContract is Destructible {
    // MyContract now has access to Owned and Destructible functionalities
}
```

#### 4.2 Events

Events allow logging to the Ethereum blockchain:

```solidity
contract EventExample {
    event Transfer(address indexed from, address indexed to, uint256 value);

    function transfer(address to, uint256 value) public {
        // Perform transfer logic here
        emit Transfer(msg.sender, to, value);
    }
}
```

#### 4.3 Libraries

Libraries allow code reuse and gas optimization:

```solidity
library SafeMath {
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }
}

contract UsingLibrary {
    using SafeMath for uint256;

    function addSafely(uint256 a, uint256 b) public pure returns (uint256) {
        return a.add(b);
    }
}
```

### 5. RemixIDE Core Concepts 🧠

#### 5.1 Workspace

The workspace in RemixIDE is where you manage your files and folders. You can create, delete, and organize your Solidity contracts and other related files here.

#### 5.2 Editor

The editor is where you write and edit your Solidity code. It provides syntax highlighting, auto-completion, and real-time error checking.

#### 5.3 Compiler

The compiler panel allows you to compile your Solidity contracts. You can select the compiler version, enable optimization, and view compilation results.

#### 5.4 Deploy & Run Transactions

This panel lets you deploy your contracts to various environments (JavaScript VM, Injected Web3, etc.) and interact with deployed contracts.

### 6. Key Features of RemixIDE 🔑

* Integrated development environment for Solidity
* Real-time compilation and error checking
* Built-in debugger
* Gas estimation
* Static analysis
* Plugin system for extensibility
* Integration with popular wallets like MetaMask

### 7. RemixIDE Usage: Terminal and Command Palette ⌨️

#### 7.1 Terminal Usage

RemixIDE provides a built-in terminal for executing commands:

```bash
# Compile all contracts in the current workspace
remix compile

# Deploy a contract
remix deploy MyContract

# Run tests
remix test
```

#### 7.2 Command Palette

Access the command palette using `Ctrl+Shift+P` (Windows/Linux) or `Cmd+Shift+P` (Mac). Some useful commands include:

* `Compile current file`: Compiles the active Solidity file
* `Deploy & Run Transactions`: Opens the deployment panel
* `Run script`: Executes a selected script

### 8. Benefits of Using RemixIDE 🌈

* **Comprehensive**: Includes all tools needed for Solidity development
* **Debugging:** Built-in debugger for efficient troubleshooting
* **Testing**: Integrated testing framework
* **Flexibility**: Can be used online or installed locally
* **Community support:** Large user base and active development
* **Accessibility:** Remix is a web-based tool, making it accessible from any device with a web browser. &#x20;
* **Ease of Use:** Its user-friendly interface makes it suitable for both beginners and experienced developers. &#x20;
* **Open Source:** Being open-source, it allows for community contributions and improvements. &#x20;

### 9. Limitations of Using RemixIDE 🌈

While Remix is a powerful tool, it has some limitations:

* **Online Dependency:** As a web-based tool, it relies on an internet connection.
* **Limited Local Development:** It's primarily designed for online development, and local development might require additional setup.
* **Performance:** Complex projects might experience performance issues due to browser limitations.

### 10. RemixIDE Commands: Why and When to Use 🛠️

#### 10.1 Compile

**Command:** `Ctrl+S` or click the "Compile" button

**Why:** To check for syntax errors and prepare the contract for deployment

**When:** After making changes to your Solidity code

#### 10.2 Deploy

**Command:** Click "Deploy" in the "Deploy & Run Transactions" panel

**Why:** To deploy your contract to the selected environment

**When:** After successful compilation and when you're ready to test your contract

#### 10.3 Debug

**Command:** Click the bug icon next to a transaction

**Why:** To step through the execution of a transaction and inspect the contract state

**When:** When you encounter unexpected behavior or errors in your contract

### 11. Architecture and User Flow Diagrams 📊

#### 11.1 RemixIDE Architecture

<figure><img src="/files/tOaznvf6JWX1rIkthxXD" alt=""><figcaption></figcaption></figure>

Remix IDE is a valuable tool for anyone starting their journey into Ethereum development. Its user-friendly interface, combined with its powerful features, makes it a popular choice for both beginners and experienced developers. However, for larger and more complex projects, developers might consider using more advanced development environments like Hardhat or Truffle. &#x20;


# Messaging/Caching

Messaging and caching systems are fundamental components in modern software architectures, each serving distinct yet complementary roles in enhancing application performance, scalability, and reliability.

### Messaging Systems in Detail

Messaging systems facilitate communication between different components or services in a distributed system. They enable asynchronous data transfer, which is crucial for building loosely coupled, scalable applications.

#### Key Components of Messaging Systems:

* Message Producer: The component that creates and sends messages
* Message Consumer: The component that receives and processes messages
* Message Broker: The intermediary that manages message queues and routes messages
* Message Queue: A buffer that temporarily stores messages

#### Common Messaging Patterns:

* Point-to-Point: Messages are sent from one producer to one consumer
* Publish-Subscribe: Messages are broadcast to multiple consumers
* Request-Reply: A two-way communication where the producer expects a response

### Caching Systems in Detail

Caching systems store frequently accessed data in memory, reducing the load on databases and improving application response times. They play a crucial role in optimizing data retrieval operations.

#### Key Concepts in Caching:

* Cache Hit: When requested data is found in the cache
* Cache Miss: When requested data is not in the cache and must be fetched from the primary data store
* Cache Eviction: The process of removing data from the cache to make room for new data
* Cache Consistency: Ensuring that cached data remains in sync with the primary data store

#### Caching Strategies:

* Read-Through: Cache fetches data from the database when it's not in the cache
* Write-Through: Data is written to both the cache and the database simultaneously
* Write-Behind: Data is written to the cache and later asynchronously updated in the database
* Cache-Aside: Application code manages when to read from/write to the cache

### Integration of Messaging and Caching in Modern Architectures

Messaging and caching systems often work together in modern architectures to create highly performant and scalable applications. Here's a diagram illustrating their integration:

<figure><img src="/files/NYfA9ti6MTIa4oNfTtpP" alt=""><figcaption></figcaption></figure>

In this architecture:

* The API Gateway serves as the entry point for client requests
* The Cache (e.g., Redis) stores frequently accessed data to reduce database load
* The Message Broker (e.g., Kafka) facilitates communication between services
* Multiple services process requests and interact with their respective databases
* Services can both publish and consume messages, enabling event-driven architectures
* The cache can be updated by services and queried to reduce load on databases

#### Benefits of This Integrated Approach

* Improved Scalability: Services can scale independently based on message queue load
* Enhanced Performance: Caching reduces database queries and improves response times
* Better Fault Tolerance: Message queues can buffer requests during service outages
* Decoupled Architecture: Services can evolve independently, communicating via messages

#### Challenges and Considerations

* Eventual Consistency: Caching and messaging can introduce data consistency challenges
* Increased Complexity: Managing distributed systems requires additional operational overhead
* Data Synchronization: Keeping caches and databases in sync can be challenging
* Message Ordering: Ensuring correct message order in distributed systems can be complex

By leveraging both messaging and caching systems, modern applications can achieve high levels of performance, scalability, and reliability. However, careful design and implementation are crucial to navigate the inherent complexities of distributed systems.


# Kafka

## What is kafka?

<https://kafka.apache.org/>

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fdd2015a1-5c5c-4ef3-91ad-2c6a8c92600c%2FScreenshot_2024-07-10_at_2.40.11_PM.png?table=block&#x26;id=ed871567-37d8-44cf-9634-1858ab454b54&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## **What is distributed**

You can scale kafka horizontally by adding more nodes that run your kafka `brokers`

**Event streaming**

If you want to build a system where one process `produces` events that can be consumed by multiple `consumers`

**Examples of apps**

Payment notifications

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Feadf2285-35e0-4b6e-bdc6-6459d7ad2223%2FScreenshot_2024-07-10_at_2.47.40_PM.png?table=block&#x26;id=93fb3e9a-3e77-4670-a7d8-1762154c2f57&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

**Cluster and broker**

A group of machines running kafka are known as a kafka clusterEach individual machine is called a broker

**Producers**

As the name suggests, producers are used to `publish` data to a topic

**Consumers**

As the name suggests, consumers consume from a topic

**Topics**

A topic is a logical channel to which producers send messages and from which consumers read messages.

**Offsets**

Consumers keep track of their position in the topic by maintaining offsets, which represent the position of the last consumed message. Kafka can manage offsets automatically or allow consumers to manage them manually.

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fa98a741c-5ae0-41dc-b5cb-d8246ad491fb%2FScreenshot_2024-07-10_at_3.30.42_PM.png?table=block&#x26;id=ffeb8e21-320d-4b3c-b159-4a7bf83a35ed&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

**Retention**

Kafka topics have configurable retention policies, determining how long data is stored before being deleted. This allows for both real-time processing and historical data replay.

## Start kafka locally

Ref - [https://kafka.apache.org/quickstart](https://kafka.apache.org/quickstart#quickstart_createtopic)

**Using docker**

```javascript
docker run -p 9092:9092 apache/kafka:3.7.1
```

**Get shell access to container**

```javascript
docker ps
docker exec -it container_id /bin/bash
cd /opt/kafka/bin
```

**Create a topic**

```javascript
./kafka-topics.sh --create --topic quickstart-events --bootstrap-server localhost:9092
```

**Publish to the topic**

```javascript
./kafka-console-producer.sh --topic quickstart-events --bootstrap-server localhost:9092
```

**Consuming from the topic**

```javascript
./kafka-console-consumer.sh --topic quickstart-events --from-beginning --bootstrap-serve
```

## Kafka in a Node.js process

Ref <https://www.npmjs.com/package/kafkajs>&#x20;

* Initialise project

```javascript
npm init -y
npx tsc --init
```

* Update package.json

```javascript
"rootDir": "./src",
"outDir": "./dist"
```

* Add `src/index.ts`

```javascript
import { Kafka } from "kafkajs";

const kafka = new Kafka({
  clientId: "my-app",
  brokers: ["localhost:9092"]
})

const producer = kafka.producer();

const consumer = kafka.consumer({groupId: "my-app3"});


async function main() {
  await producer.connect();
  await producer.send({
    topic: "quickstart-events",
    messages: [{
      value: "hi there"
    }]
  })

  await consumer.connect();
  await consumer.subscribe({
    topic: "quickstart-events", fromBeginning: true
  })

  await consumer.run({
    eachMessage: async ({ topic, partition, message }) => {
      console.log({
        offset: message.offset,
        value: message?.value?.toString(),
      })
    },
  })
}


main();
```

* Update package.json

```javascript
"scripts": {
    "start": "tsc -b && node dist/index.js"
},
```

* Start the process

```javascript
npm run start
```

&#x20;

## Breaking into prodcuer and consumer scripts

* producer.ts

```javascript
import { Kafka } from "kafkajs";

const kafka = new Kafka({
  clientId: "my-app",
  brokers: ["localhost:9092"]
})

const producer = kafka.producer();

async function main() {
  await producer.connect();
  await producer.send({
    topic: "quickstart-events",
    messages: [{
      value: "hi there"
    }]
  });
}


main();
```

* consumer.ts

```javascript
import { Kafka } from "kafkajs";

const kafka = new Kafka({
  clientId: "my-app",
  brokers: ["localhost:9092"]
})

const consumer = kafka.consumer({ groupId: "my-app3" });


async function main() {
  await consumer.connect();
  await consumer.subscribe({
    topic: "quickstart-events", fromBeginning: true
  })

  await consumer.run({
    eachMessage: async ({ topic, partition, message }) => {
      console.log({
        offset: message.offset,
        value: message?.value?.toString(),
      })
    },
  })
}


main();
```

* Update package.json

```javascript

  "scripts": {
    "start": "tsc -b && node dist/index.js",
    "produce": "tsc -b && node dist/producer.js",
    "consume": "tsc -b && node dist/consumer.js"    
  },
```

* Try starting multiple consumers, and see if each gets back a message for the messages produced

Notice we specified a `consumer group` (my-app3)

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fc0f866ab-9544-4ec7-bce6-c8818af57fed%2FScreenshot_2024-07-10_at_5.25.39_PM.png?table=block&#x26;id=6ddd921a-7a16-4347-9686-432df1b22f6c&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## Consumer groups and partitions

**Consumer group**

A consumer group is a group of consumers that coordinate to consume messages from a Kafka topic.

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F2551afde-b3b2-4499-8c0c-5ac5db8a65a5%2FScreenshot_2024-07-10_at_5.28.10_PM.png?table=block&#x26;id=f6a77bd2-5944-4d95-976c-8c1d2bb8f719&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

Purpose:

* Load Balancing: Distribute the processing load among multiple consumers.
* Fault Tolerance: If one consumer fails, Kafka automatically redistributes the partitions that the failed consumer was handling to the remaining consumers in the group.
* Parallel Processing: Consumers in a group can process different partitions in parallel, improving throughput and scalability.

**Partitions**

Partitions are subdivisions of a Kafka topic. Each partition is an ordered, immutable sequence of messages that is appended to by producers. Partitions enable Kafka to scale horizontally and allow for parallel processing of messages.

**How is a partition decided?**

When a message is produced to a Kafka topic, it is assigned to a specific partition. This can be done using a round-robin method, a hash of the message key, or a custom partitioning strategy.Usually you’ll take things like `user id` as the `message key` so all messages from the same user go to the same consumer (so a single user doesnt starve everyone lets say)&#x20;

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F7fc0019b-0671-4b74-87b7-7c5e02f527dc%2FScreenshot_2024-07-10_at_5.34.47_PM.png?table=block&#x26;id=83a339f3-8a03-4162-943a-641838776f51&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

**Multiple consumer groups**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fd55d31bc-6733-4b44-b29f-c068def20edc%2FScreenshot_2024-07-10_at_5.36.09_PM.png?table=block&#x26;id=31961a0e-a0f8-4aef-b8e2-a146990ff7c6&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## Partitions in kafka

In this slide, we’ll talk about what are partitions in Kafka

* Create a new topic with 3 partitions

```javascript
./kafka-topics.sh --create --topic payment-done --partitions 3 --bootstrap-server localhost:9092
```

* Ensure it has 3 partitions

```javascript
./kafka-topics.sh --describe --topic payment-done --bootstrap-server localhost:9092
```

* Update the topic in the node.js script to use `payment-done`

```javascript
async function main() {
  await producer.connect();
  await producer.send({
    topic: "payment-done",
    messages: [{
      value: "hi there",
      key: "user1"
    }]
  });
}
///
await consumer.subscribe({
  topic: "payment-done", fromBeginning: true
})
```

* Consume messages in 3 terminals

```javascript
npm run consume
```

* produce messages

```javascript
npm run produce
```

* Notice the messages get consumed by all 3 consumers

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F72dd30f7-5de2-4283-8669-f19b1fbc10ab%2FScreenshot_2024-07-10_at_5.46.52_PM.png?table=block&#x26;id=724bfc27-1728-4f88-9892-95daa7e4e4ae&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## &#x20;**Current architecture**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Fbf85b3a4-8d68-4cff-a14d-fc032f456af1%2FScreenshot_2024-07-10_at_5.47.41_PM.png?table=block&#x26;id=7f40219e-7b79-4b84-b591-7345136a6105&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## Three cases to discuss

## **Equal number of partitions and consumers**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F75478041-1808-4a32-b5b1-6468d3c5cd6e%2FScreenshot_2024-07-10_at_5.58.22_PM.png?table=block&#x26;id=e21e3f03-27d8-424e-9e5c-92d79ff92f29&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## **More partitions**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F34cf697b-1d69-4106-897b-125a9939d7c7%2FScreenshot_2024-07-10_at_5.58.51_PM.png?table=block&#x26;id=63bb2037-c8bd-4825-a16f-7287673bf35c&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## **More consumers**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Ff2060b34-80ea-41d5-9617-df65d189c86f%2FScreenshot_2024-07-10_at_5.59.05_PM.png?table=block&#x26;id=371bde0a-fac2-4618-beb5-371df0145ed7&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

## Partitioning strategy

When producing messages, you can assign a key that uniquely identifies the event.Kafka will hash this key and use the hash to determine the partition. This ensures that all messages with the same key (lets say for the same user) are sent to the same partition.💡Why would you want messages from the same user to go to the same partition? Lets say a single user has too many notifications, this way you can make sure they only choke a single partition and not all the partitions

* Create a new `producer-user.ts` file, pass in a `key` when producing the message

```javascript
import { Kafka } from "kafkajs";

const kafka = new Kafka({
  clientId: "my-app",
  brokers: ["localhost:9092"]
})

const producer = kafka.producer();

async function main() {
  await producer.connect();
  await producer.send({
    topic: "payment-done",
    messages: [{
      value: "hi there",
      key: "user1"
    }]
  });
}

main();
```

* Add `produce:user` script

```javascript
"produce:user": "tsc -b && node dist/producer-user.js",
```

* Start 3 consumers and one producer. Notice all messages reach the same consumer

```javascript
npm run produce:user
```


# Redis

## Redis: In-Memory Data Structure Store 🚀

Redis (Remote Dictionary Server) is an open-source, in-memory data structure store that can be used as a database, cache, message broker, and queue. It's known for its high performance and versatility.

### Architecture 🏗️

Redis follows a client-server architecture:

<figure><img src="/files/jlinZufWqfUrQ9HCduZW" alt=""><figcaption></figcaption></figure>

### Key Concepts 🗝️

* In-memory data storage
* Key-value data model
* Data structures: Strings, Lists, Sets, Hashes, Sorted Sets
* Pub/Sub messaging
* Transactions
* Lua scripting

### Installation and Setup 🛠️

To install Redis on Ubuntu:

```bash
sudo apt update
sudo apt install redis-server
```

To start Redis server:

```bash
sudo systemctl start redis-server
```

### Basic Redis Commands 💻

Here are some basic Redis commands:

```bash
SET key value
GET key
DEL key
EXISTS key
INCR key
EXPIRE key seconds
```

### Using Redis with Node.js 🟢

First, install the Redis client for Node.js:

```bash
npm install redis
```

Here's a simple example of using Redis with Node.js:

```jsx
const redis = require('redis');
const client = redis.createClient();

client.on('error', (err) => console.log('Redis Client Error', err));

async function main() {
    await client.connect();

    // Set a key
    await client.set('user:1', 'John Doe');

    // Get a key
    const value = await client.get('user:1');
    console.log(value); // Output: John Doe

    // Close the connection
    await client.quit();
}

main();
```

### Redis Data Structures 📊

#### 1. Strings

```jsx
await client.set('mykey', 'Hello, Redis!');
const value = await client.get('mykey');
console.log(value); // Output: Hello, Redis!
```

#### 2. Lists

```jsx
await client.lPush('mylist', 'world');
await client.lPush('mylist', 'hello');
const list = await client.lRange('mylist', 0, -1);
console.log(list); // Output: [ 'hello', 'world' ]
```

#### 3. Sets

```jsx
await client.sAdd('myset', 'member1');
await client.sAdd('myset', 'member2');
const members = await client.sMembers('myset');
console.log(members); // Output: [ 'member1', 'member2' ]
```

#### 4. Hashes

```jsx
await client.hSet('user:1000', 'name', 'John Doe');
await client.hSet('user:1000', 'email', 'john@example.com');
const user = await client.hGetAll('user:1000');
console.log(user); // Output: { name: 'John Doe', email: 'john@example.com' }
```

### Redis Pub/Sub 📡

Redis Pub/Sub implementation:

```jsx
const publisher = redis.createClient();
const subscriber = publisher.duplicate();

await Promise.all([publisher.connect(), subscriber.connect()]);

await subscriber.subscribe('news', (message) => {
    console.log(message); // 'Hello world!'
});

await publisher.publish('news', 'Hello world!');
```

### Redis Transactions 🔒

Example of a Redis transaction:

```jsx
const multi = client.multi();
multi.set('key1', 'value1');
multi.set('key2', 'value2');
const results = await multi.exec();
console.log(results); // Output: ['OK', 'OK']
```

### Deployment 🚀

For production deployment, consider using Redis Cloud or setting up a Redis cluster for high availability and scalability. Always ensure proper security measures are in place, such as authentication and encryption.

&#x20;Remember to configure Redis for persistence if you need data to survive server restarts. You can use RDB snapshots or AOF (Append Only File) for this purpose.

With its speed, versatility, and rich feature set, Redis is an excellent choice for various use cases in modern application development, from caching to real-time analytics and more.


# Sendgrid

## SendGrid: Email Delivery Service 📧

SendGrid is a cloud-based email delivery platform that enables businesses to send transactional and marketing emails. It provides robust APIs and tools for managing email campaigns, tracking analytics, and ensuring high deliverability rates.

### Architecture 🏗️

SendGrid's architecture is designed for scalability and reliability:

### Key Concepts 🗝️

* Transactional and Marketing Email Delivery
* Email Authentication (SPF, DKIM, DMARC)
* Email Templates and Dynamic Content
* Advanced Analytics and Reporting
* Webhook Event Handling
* API and SMTP Integration

### Installation and Setup 🛠️

To use SendGrid with Node.js, first install the SendGrid package:

```bash
npm install @sendgrid/mail
```

### Basic Usage with Node.js 💻

Here's a simple example of sending an email using SendGrid:

```jsx
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey('YOUR_SENDGRID_API_KEY');

const msg = {
  to: 'recipient@example.com',
  from: 'sender@example.com',
  subject: 'Sending with SendGrid is Fun',
  text: 'and easy to do anywhere, even with Node.js',
  html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};

sgMail
  .send(msg)
  .then(() => {
    console.log('Email sent successfully');
  })
  .catch((error) => {
    console.error(error);
  });
```

Output:

```bash
Email sent successfully
```

### Advanced Features 🚀

#### 1. Using Templates

```jsx
const msg = {
  to: 'recipient@example.com',
  from: 'sender@example.com',
  templateId: 'd-f43daeeaef504760851f727007e0b5d6',
  dynamicTemplateData: {
    name: 'John Doe',
    company: 'Acme Inc.'
  },
};

sgMail.send(msg);
```

#### 2. Handling Webhooks

```jsx
const express = require('express');
const app = express();

app.post('/webhook', express.json(), (req, res) => {
  const events = req.body;
  events.forEach(event => {
    console.log('Event:', event.event);
    console.log('Email:', event.email);
  });
  res.sendStatus(200);
});

app.listen(3000, () => console.log('Webhook server running on port 3000'));
```

#### 3. Batch Sending

```jsx
const messages = [
  {
    to: 'recipient1@example.com',
    from: 'sender@example.com',
    subject: 'Hello, Recipient 1',
    text: 'This is a test email for Recipient 1',
  },
  {
    to: 'recipient2@example.com',
    from: 'sender@example.com',
    subject: 'Hello, Recipient 2',
    text: 'This is a test email for Recipient 2',
  },
];

sgMail
  .send(messages)
  .then(() => console.log('Emails sent successfully'))
  .catch((error) => console.error(error));
```

### Deployment 🚀

When deploying an application using SendGrid:

* Securely store your SendGrid API key as an environment variable
* Set up domain authentication for better deliverability
* Configure IP warmup if sending large volumes of emails
* Implement proper error handling and logging

Example of setting API key in different environments:

```bash
# Development
export SENDGRID_API_KEY='YOUR_API_KEY'

# Production (e.g., Heroku)
heroku config:set SENDGRID_API_KEY='YOUR_API_KEY'
```

&#x20;Remember to monitor your SendGrid dashboard for analytics, bounces, and spam reports. Regularly clean your email lists and follow best practices to maintain a good sender reputation.

With its powerful features and scalable infrastructure, SendGrid is an excellent choice for businesses of all sizes looking to implement robust email delivery solutions in their applications.vv


# Blockchain

### How Banks Do Authentication:

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2Fb6b653be-a925-4fed-bba5-9764dfbd5a32%2Fimage.png?table=block&#x26;id=730f3055-75f4-4045-b1a4-88ce68610b09&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

* Username and Password:
* * Traditional banks rely on a username and password for authentication.
  * These credentials allow you to:
  * * View your funds.
    * Transfer funds.
    * Review your transaction history.

### How Blockchains Do Authentication:

#### Public-Private Keypair:

Blockchain accounts are secured through a public-private keypair.

* A public-private keypair consists of two keys used in asymmetric cryptography.

**Public Key:**

* The public key is a string that can be shared openly with anyone.
* It acts like your "account number" on the blockchain.
* Example: [Ethereum Address on Etherscan](https://etherscan.io/address/0xD9a657ACB3960DB92AaaA32942019bD3c473FCCB)

**Private Key:**

* The private key is a secret string that must be kept confidential.
* It is used to sign transactions and prove ownership of the associated public key.
* Never share your private key with anyone.

***

### Bits and Bytes

<details>

<summary>Why Learning this?</summary>

</details>

#### What is a Bit?

* A bit is the smallest unit of data in a computer.
* It can have one of two values: `0` or `1`.
* All programs and code you write are eventually converted to `0's` and `1's`.
* Analogy:
* * Think of a bit like a light switch that can either be off (`0`) or on (`1`).
* Bit Representation in JavaScript:
* * ```javascript
    const x = 0;
    console.log(x); // Outputs: 0
    ```
  * Here, `x` represents a single bit with a value of `0`.

#### What is a Byte?

* A byte is a group of 8 bits.
* It’s the standard unit of data used to represent a single character in memory.
* Possible Values:
* * Since each bit can be either `0` or `1`, a byte can have 2^8 (256) possible values, ranging from `0` to `255`.
  * Example: The binary sequence `11001010` represents a specific value in decimal (we'll cover this in the assignment below).
* Byte Representation:
* * ```javascript
    const x = 202;
    console.log(x); // Outputs: 202
    ```
  * Here, `x` is a byte, representing the decimal value `202`, which is equivalent to `11001010` in binary.
* Array of Bytes:
* * ```javascript
    const bytes = [202, 244, 1, 23];
    console.log(bytes); // Outputs: [202, 244, 1, 23]
    ```
  * This is an array containing multiple bytes.

**Using `UInt8Array` in JavaScript:**

* Definition:
* * `UInt8Array` is a typed array in JavaScript that represents an array of 8-bit unsigned integers (bytes).
* Advantages:
* * Memory Efficiency: Uses less space; each value takes only 1 byte.
  * Constraints: Ensures that values don’t exceed `255`, which is the maximum value a byte can hold.
* Example:
* * ```javascript
    let bytes = new Uint8Array([0, 255, 127, 128]);
    console.log(bytes); // Outputs: Uint8Array(4) [ 0, 255, 127, 128 ]
    ```
  * This code creates a `UInt8Array` with four bytes, ensuring that each value stays within the valid byte range.
* Example:
* * ```javascript
    const binaryRepresentation = new TextEncoder().encode("h");
    console.log(binaryRepresentation); // Uint8Array(1)[104]
    ```

***

**Why Use `UInt8Array` Over Native Arrays?**

* Memory Efficiency:
* * Native arrays in JavaScript store numbers using 64 bits (8 bytes) per number, regardless of the actual size of the number.
  * `UInt8Array` stores each number using only 1 byte, which is sufficient for values between `0` and `255`.
* Constraints:
* * `UInt8Array` enforces that each element doesn’t exceed `255`, preventing potential overflow errors.

***

<details>

<summary>Assignment:</summary>

* Question: What do you think happens to the first element here? Does it throw an error?
* * ```javascript
    let uint8Arr = new Uint8Array([0, 255, 127, 128]);
    uint8Arr[1] = 300;
    ```

</details>

***

<details>

<summary>Assignment:</summary>

* Question: What is `11001010` converted to in decimal?
* Answer: `202`

💡[Binary to Decimal Converter (rapidtables.com)](https://www.rapidtables.com/convert/number/binary-to-decimal.html)

</details>

***

### Encodings

* When working with computers, data is often represented in a format that is not human-readable, such as binary or bytes.
* Encoding is the process of converting this data into a more readable format.
* Some common encodings include ASCII, Hex, Base64, and Base58.
* These encodings help us represent binary data in a more understandable way.

#### 1. ASCII (American Standard Code for Information Interchange)

* 1 character = 7 bits
* ASCII is one of the oldest encodings used to represent text in computers. Each character in ASCII corresponds to a specific number (ranging from 0 to 127), which is represented in binary.
* For example, the letter 'A' is represented by the number 65 in ASCII, which is `01000001` in binary.

<details>

<summary>Converting Bytes to ASCII</summary>

```javascript
function bytesToAscii(byteArray) {
  return byteArray.map(byte => String.fromCharCode(byte)).join('');
}

// Example usage:
const bytes = [72, 101, 108, 108, 111]; // Corresponds to "Hello"
const asciiString = bytesToAscii(bytes);
console.log(asciiString); // Output: "Hello"
```

</details>

<details>

<summary>Converting ASCII to Bytes</summary>

```javascript
function asciiToBytes(asciiString) {
  const byteArray = [];
  for (let i = 0; i < asciiString.length; i++) {
    byteArray.push(asciiString.charCodeAt(i));
  }
  return byteArray;
}

// Example usage:
const ascii = "Hello";
const byteArray = asciiToBytes(ascii);
console.log(byteArray); // Output: [72, 101, 108, 108, 111]
```

</details>

<details>

<summary>Using <code>UInt8Array</code> for ASCII</summary>

```javascript
function bytesToAscii(byteArray) {
  return new TextDecoder().decode(byteArray);
}

// Example usage:
const bytes = new Uint8Array([72, 101, 108, 108, 111]); // Corresponds to "Hello"
const asciiString = bytesToAscii(bytes);
console.log(asciiString); // Output: "Hello"
```

</details>

<details>

<summary>ASCII to <code>UInt8Array</code></summary>

```javascript
function asciiToBytes(asciiString) {
  return new Uint8Array([...asciiString].map(char => char.charCodeAt(0)));
}

// Example usage:
const ascii = "Hello";
const byteArray = asciiToBytes(ascii);
console.log(byteArray); // Output: Uint8Array(5) [72, 101, 108, 108, 111]
```

</details>

💡[ASCII table - Table of ASCII codes, characters and symbols (ascii-code.com)](https://www.ascii-code.com/) [HTML ASCII Reference (w3schools.com)](https://www.w3schools.com/charsets/ref_html_ascii.asp#:~:text=The%20ASCII%20Character%20Set\&text=ASCII%20is%20a%207-bit,are%20all%20based%20on%20ASCII)

#### 2. Hexadecimal (Hex)

* 1 character = 4 bits
* Hexadecimal is a base-16 encoding system that uses 16 characters: `0-9` and `A-F`. It is commonly used in programming and digital systems to represent binary data in a more compact and readable format.
* Each hex digit represents four bits (a nibble), and two hex digits represent one byte.

<details>

<summary>Converting Array to Hex</summary>

```javascript
function arrayToHex(byteArray) {
  let hexString = '';
  for (let i = 0; i < byteArray.length; i++) {
    hexString += byteArray[i].toString(16).padStart(2, '0');
  }
  return hexString;
}

// Example usage:
const byteArray = new Uint8Array([72, 101, 108, 108, 111]); // Corresponds to "Hello"
const hexString = arrayToHex(byteArray);
console.log(hexString); // Output: "48656c6c6f"
```

</details>

<details>

<summary>Converting Hex to Array</summary>

```javascript
function hexToArray(hexString) {
  const byteArray = new Uint8Array(hexString.length / 2);
  for (let i = 0; i < byteArray.length; i++) {
    byteArray[i] = parseInt(hexString.substr(i * 2, 2), 16);
  }
  return byteArray;
}

// Example usage:
const hex = "48656c6c6f";
const byteArrayFromHex = hexToArray(hex);
console.log(byteArrayFromHex); // Output: Uint8Array(5) [72, 101, 108, 108, 111]
```

</details>

💡[Hex (Base16) encoder & decoder, a simple online tool 🧰 (hexator.com)](https://www.hexator.com/)

#### 3. Base64

* 1 character = 6 bits
* Base64 is an encoding scheme that represents binary data in an ASCII string format. It uses 64 different characters (`A-Z`, `a-z`, `0-9`, `+`, `/`). It is commonly used in data transfer, encoding images, and storing complex data as text.

<details>

<summary>Encoding to Base64</summary>

```javascript
const uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
const base64Encoded = Buffer.from(uint8Array).toString("base64");
console.log(base64Encoded);
```

</details>

💡[Base64 Encode/Decode](https://www.base64encode.org/)[Base64 Decode/Encode](https://www.base64decode.org/)

#### 4. Base58

* Base58 is similar to Base64 but uses a different set of characters to avoid visually similar characters (e.g., `0` and `O`, `l` and `1`) and to make the encoded output more user-friendly.
* It is often used in Bitcoin and other cryptocurrencies for encoding addresses and other data.

<details>

<summary>Encoding to Base58</summary>

```javascript
const bs58 = require('bs58');

function uint8ArrayToBase58(uint8Array) {
  return bs58.encode(uint8Array);
}

// Example usage:
const byteArray = new Uint8Array([72, 101, 108, 108, 111]); // Corresponds to "Hello"
const base58String = uint8ArrayToBase58(byteArray);
console.log(base58String); // Output: Base58 encoded string
```

</details>

<details>

<summary>Decoding from Base58</summary>

```javascript
const bs58 = require('bs58');

function base58ToUint8Array(base58String) {
  return bs58.decode(base58String);
}

// Example usage:
const base58 = base58String; // Use the previously encoded Base58 string
const byteArrayFromBase58 = base58ToUint8Array(base58);
console.log(byteArrayFromBase58); // Output: Uint8Array(5) [72, 101, 108, 108, 111]
```

</details>

***

### Hashing vs Encryption

#### Hashing

* Hashing converts data into a fixed-size string of characters, known as a hash.
* Key points:
* * Deterministic: The same input will always produce the same hash.
  * Fixed Size: Regardless of the input size, the output hash will always be the same length.
  * One-Way Function: Hashes cannot be reversed to retrieve the original input data.
  * Collision Resistance: It is computationally difficult to find two different inputs that produce the same hash.
* Common Hashing Algorithms:
* * SHA-256: Widely used in blockchain technology, ensuring data integrity.
  * MD5: Once popular for checksums, now considered insecure due to vulnerabilities.

#### Encryption

* Encryption converts plaintext into ciphertext using an algorithm and a key.
* Key points:
* * Reversible: With the correct key, the ciphertext can be decrypted back to plaintext.
  * Key-Dependent: The security of encryption relies on the secrecy of the key.

#### Types of Encryptions:

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F26ebabfb-089c-4f13-b19d-99686fd5df72%2Fimage.png?table=block&#x26;id=2c00cfca-559c-4555-be70-a68b3a480387&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

**1. Symmetric Encryption:**

* Definition: The same key is used for both encryption and decryption.
* Common Algorithms:
* * AES (Advanced Encryption Standard)
  * DES (Data Encryption Standard)

<details>

<summary>Example:</summary>

```javascript
const crypto = require('crypto');

// Generate a random encryption key
const key = crypto.randomBytes(32); // 32 bytes = 256 bits
const iv = crypto.randomBytes(16); // Initialization vector (IV)

// Function to encrypt text
function encrypt(text) {
    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;
}

// Function to decrypt text
function decrypt(encryptedText) {
    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

// Example usage
const textToEncrypt = 'Hello, World!';
const encryptedText = encrypt(textToEncrypt);
const decryptedText = decrypt(encryptedText);

console.log('Original Text:', textToEncrypt);
console.log('Encrypted Text:', encryptedText);
console.log('Decrypted Text:', decryptedText);
```

</details>

💡[AES Encryption and Decryption Online (devglan.com)](https://www.devglan.com/online-tools/aes-encryption-decryption)

**2. Asymmetric Encryption:**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F30661723-ba5b-4ed4-b8d4-9063293a757f%2Fimage.png?table=block&#x26;id=ef5bf570-ff4b-42b2-b7e0-37377ac33c4e&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

Uses a pair of keys – a public key and a private key – for encryption and decryption.

* Key Pair:
* * Public Key: Can be shared openly and is used to encrypt data.
  * Private Key: Must be kept confidential and is used to decrypt data encrypted with the corresponding public key.
* Common Algorithms:
* * RSA (Rivest–Shamir–Adleman)
  * ECC (Elliptic Curve Cryptography) - Used by ETH and BTC
  * EdDSA (Edwards-curve Digital Signature Algorithm) - Used by SOL
* Common Elliptic Curves:
* * secp256k1: Used in Bitcoin (BTC) and Ethereum (ETH).
  * ed25519: Used in Solana (SOL).
  *

  ```
  <figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F772683dc-8f61-4b26-a473-235bcec85a58%2Fimage.png?table=block&#x26;id=42c90f7f-a789-47ee-9af4-2b0f679ce092&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>
  ```

💡[How Elliptic Curves Work](https://www.youtube.com/watch?v=NF1pwjL9-DE&)

* Use Cases of Public-Key Cryptography:
* * SSL/TLS Certificates: Ensuring secure communication over the internet.
  * SSH Keys: For secure server access or pushing code to GitHub.
  * Blockchains and Cryptocurrencies: Ensuring secure and verifiable transactions.

***

💡- A message on the blockchain is signed using private key. - A miner verifies the transaction using the signature and public key. - Public/PrivateKeys & Signing - [Blockchain Demo: Public / Private Keys & Signing (andersbrownworth.com)](https://andersbrownworth.com/blockchain/public-private-keys/signatures)

### Creating a public/private keypair

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F4f59888c-376b-4f8f-944d-b5e37c0aaf92%2Fimage.png?table=block&#x26;id=8853405f-e465-445c-bef1-4db0c8e1dc38&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

**EdDSA - Edwards-curve Digital Signature Algorithm  - ED25519**

<details>

<summary>Using <code>@noble/ed25519</code></summary>

```javascript
import * as ed from "@noble/ed25519";

async function main() {
  // Generate a secure random private key
  const privKey = ed.utils.randomPrivateKey();

  // Convert the message "hello world" to a Uint8Array
  const message = new TextEncoder().encode("hello world");

  // Generate the public key from the private key
  const pubKey = await ed.getPublicKeyAsync(privKey);

  // Sign the message
  const signature = await ed.signAsync(message, privKey);

  // Verify the signature
  const isValid = await ed.verifyAsync(signature, message, pubKey);

  // Output the result
  console.log(isValid); // Should print `true` if the signature is valid
}

main();
```

</details>

<details>

<summary>Using <code>@solanaweb3.js</code></summary>

```javascript
import { Keypair } from "@solana/web3.js";
import nacl from "tweetnacl";

// Generate a new keypair
const keypair = Keypair.generate();

// Extract the public and private keys
const publicKey = keypair.publicKey.toString();
const secretKey = keypair.secretKey;

// Display the keys
console.log("Public Key:", publicKey);
console.log("Private Key (Secret Key):", secretKey);

// Convert the message "hello world" to a Uint8Array
const message = new TextEncoder().encode("hello world");

const signature = nacl.sign.detached(message, secretKey);
const result = nacl.sign.detached.verify(
  message,
  signature,
  keypair.publicKey.toBytes(),
);

console.log(result);
```

</details>

**ECDSA (Elliptic Curve Digital Signature Algorithm) - secp256k1**

<details>

<summary>Using <code>@noble/secp256k1</code></summary>

```javascript
import * as secp from "@noble/secp256k1";

async function main() {
  const privKey = secp.utils.randomPrivateKey(); // Secure random private key
  // sha256 of 'hello world'
  const msgHash =
    "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9";
  const pubKey = secp.getPublicKey(privKey);
  const signature = await secp.signAsync(msgHash, privKey); // Sync methods below
  const isValid = secp.verify(signature, msgHash, pubKey);
  console.log(isValid);
}

main();
```

</details>

<details>

<summary>Using <code>ethers</code></summary>

```javascript
import { ethers } from "ethers";

// Generate a random wallet
const wallet = ethers.Wallet.createRandom();

// Extract the public and private keys
const publicKey = wallet.address;
const privateKey = wallet.privateKey;

console.log("Public Key (Address):", publicKey);
console.log("Private Key:", privateKey);

// Message to sign
const message = "hello world";

// Sign the message using the wallet's private key
const signature = await wallet.signMessage(message);
console.log("Signature:", signature);

// Verify the signature
const recoveredAddress = ethers.verifyMessage(message, signature);

console.log("Recovered Address:", recoveredAddress);
console.log("Signature is valid:", recoveredAddress === publicKey);
```

</details>

### Hierarchical Deterministic (HD) Wallet

HD wallets generate a tree of key pairs from a single seed, allowing users to manage multiple addresses from one root seed.Problem:

* Traditionally, maintaining multiple wallets required storing multiple public-private key pairs.
* This is cumbersome and risky, as losing any one of these keys can result in the loss of associated funds.

Solution - BIP-32:

* Bitcoin Improvement Proposal 32 (BIP-32), introduced by Bitcoin Core developer Pieter Wuille in 2012, addresses this problem by standardizing the derivation of private and public keys from a single master seed.
* BIP-32 introduced the concept of hierarchical deterministic (HD) wallets, which use a tree-like structure to manage multiple accounts easily.

#### How to Create an HD Wallet

**Mnemonics**

* A mnemonic phrase, or seed phrase, is a human-readable sequence of words used to generate a cryptographic seed.
* BIP-39(Improvement to BIP-32) defines how mnemonic phrases are generated and converted into a seed.

Example Code to Generate a Mnemonic:

```javascript
import { generateMnemonic } from 'bip39';

// Generate a 12-word mnemonic
const mnemonic = generateMnemonic();
console.log('Generated Mnemonic:', mnemonic);
```

💡Reference:

* [BIP-39](https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt)
* Example in where it is done in Backpack: [GitHub Link](https://github.com/coral-xyz/backpack/blob/master/packages/app-extension/src/components/common/Account/MnemonicInput.tsx#L143)
* [YouTube Reference](https://www.youtube.com/shorts/ojBIcnPOk6k)

**Seed Phrase**

* The seed is a binary number derived from the mnemonic phrase. This seed is used to generate the master private key.

Example Code to Generate a Seed from a Mnemonic:

```javascript
import { generateMnemonic, mnemonicToSeedSync } from "bip39";

const mnemonic = generateMnemonic();
console.log("Generated Mnemonic:", mnemonic);
const seed = mnemonicToSeedSync(mnemonic);
```

Reference:

* Example in Backpack: [GitHub Link](https://github.com/coral-xyz/backpack/blob/master/packages/secure-background/src/services/svm/keyring.ts#L131)

**Derivation Paths**

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F89f74c2f-2eb0-43d8-803f-97efb36f1d47%2Fimage.png?table=block&#x26;id=128bf35b-bbd7-40e6-8349-29d5e1ced334&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

* Derivation paths specify a systematic way to derive various keys from the master seed.
* They allow users to recreate the same set of addresses and private keys from the seed across different wallets, ensuring interoperability and consistency.

&#x20;

* A derivation path is typically expressed in a format like `m / purpose' / coin_type' / account' / change / address_index`.
* * `m`: Refers to the master node, or the root of the HD wallet.
  * `purpose`: A constant that defines the purpose of the wallet (e.g., `44'` for BIP44, which is a standard for HD wallets).
  * `coin_type`: Indicates the type of cryptocurrency (e.g., `0'` for Bitcoin, `60'` for Ethereum, `501'` for solana).
  * `account`: Specifies the account number (e.g., `0'` for the first account).
  * `change`: This is either `0` or `1`, where `0` typically represents external addresses (receiving addresses), and `1` represents internal addresses (change addresses).
  * `address_index`: A sequential index to generate multiple addresses under the same account and change path.

Example Code for Deriving Paths and Generating Keys:

```javascript
import nacl from "tweetnacl";
import { generateMnemonic, mnemonicToSeedSync } from "bip39";
import { derivePath } from "ed25519-hd-key";
import { Keypair } from "@solana/web3.js";

const mnemonic = generateMnemonic();
const seed = mnemonicToSeedSync(mnemonic);
for (let i = 0; i < 4; i++) {
  const path = `m/44'/501'/${i}'/0'`; // Derivation path for Solana
  const derivedSeed = derivePath(path, seed.toString("hex")).key;
  const secret = nacl.sign.keyPair.fromSeed(derivedSeed).secretKey;
  console.log(Keypair.fromSecretKey(secret).publicKey.toBase58());
}
```

Reference:

* Solana-specific Implementation:
* * [GitHub Link 1](https://github.com/coral-xyz/backpack/blob/master/packages/secure-background/src/blockchain-configs/solana/config.ts#L38)
  * [GitHub Link 2](https://github.com/coral-xyz/backpack/blob/master/packages/secure-background/src/services/svm/util.ts#L22)

***

### Additional

💡 Can you guess the 12-word recovery phrase \[Explanation with Calculations] 💡

**Understanding the 12-Word Recovery Phrase**

1. Mnemonic Phrases (BIP39 Standard):
2. 1. * The 12-word recovery phrase is based on the BIP39 standard, which is commonly used to generate and restore wallets.
      * These phrases are used to generate the wallet's private key. The words are chosen from a specific list of 2,048 words (known as the BIP39 wordlist).
3. Combinatorial Explosion:
4. 1. * A 12-word recovery phrase can be any combination of 12 words from this list.
      * The number of possible combinations of 12 words from a list of 2,048 words is astronomical.

**Computation of Combinations**

To compute the total number of possible 12-word combinations:Total Combinations =204812=204812Let's calculate that:204812≈2132≈5.444517870735016×1039204812≈2132≈5.444517870735016×1039This is approximately 5.4×10395.4×1039 possible combinations.

**Probability of Guessing Correctly**

The probability of correctly guessing a 12-word recovery phrase is the inverse of the number of combinations:Probability=1204812≈1.8×10−40Probability=2048121​≈1.8×10−40This probability is incredibly small, making it nearly impossible to guess the correct recovery phrase by chance.

**Computational Effort and Time**

Let’s assume you could check a huge number of phrases per second:

* Hypothetical Scenario:
* * Suppose you could check 1 billion (109)(109) Phrases per second. This is an unrealistically high number but will help illustrate the difficulty.
  * Number of seconds in a year: 31,536,000seconds/year31,536,000seconds/year
  * Number of checks per year: 109×31,536,000≈3.1536×1016109×31,536,000≈3.1536×1016

Even at this rate, it would take:5.4×10393.1536×1016≈1.71×1023 years3.1536×10165.4×1039​≈1.71×1023 yearsThis is longer than the current age of the universe by many orders of magnitude.

**Practical Considerations**

* Random Generation Is Impractical: Generating a random 12-word phrase and finding a matching wallet by brute force is practically impossible due to the enormous number of possible combinations.
* Cryptographic Security: Modern cryptocurrencies are designed with security in mind, making brute force attacks infeasible.

**Conclusion**

It is theoretically possible to find a 12-word recovery phrase by luck or by generating random phrases, but the probability of success is so low that it is effectively impossible.Even with the most powerful computational resources, the time required would exceed the age of the universe by an unimaginable factor.Cryptocurrencies rely on this extremely low probability to ensure the security of wallet keys, making it virtually impossible to guess or brute-force someone's private key or recovery phrase.&#x20;


# Solana

### 1. Introduction to Solana 🌟

**Solana** is a high-performance blockchain platform designed to facilitate the development and execution of decentralized applications (dApps). It aims to address the scalability limitations of other blockchains, such as Ethereum, by introducing innovative technologies. &#x20;

#### Key Characteristics:

* ⚡ High throughput: Up to 65,000 transactions per second
* ⏱️ Low latency: Block times of 400 milliseconds
* 💰 Low transaction costs: Average cost per transaction is $0.00025
* 🌿 Energy efficient: Uses Proof of Stake (PoS) consensus mechanism

#### Key Features

* **High Speed:** Solana is renowned for its ability to process a large number of transactions per second (TPS), significantly outperforming other blockchains. &#x20;
* **Low Fees:** Due to its high throughput, transaction fees on Solana are typically lower than on other platforms. &#x20;
* **Proof of History (PoH):** Solana uses a unique consensus mechanism called Proof of History (PoH) to achieve high speeds and scalability. It involves creating a verifiable record of events before they are added to the blockchain. &#x20;
* **Smart Contracts:** Solana supports smart contracts, allowing developers to create decentralized applications. &#x20;
* **Scalability:** The platform is designed to handle a growing number of users and transactions without compromising performance. &#x20;

### 2. Installation and Setup 🛠️

#### Install Solana CLI

#### MacOS & Linux

The below commands run for WSL as well.💡[Install the Solana CLI | Solana Validator (solanalabs.com)](https://docs.solanalabs.com/cli/install)

#### Windows

Download the highlighted folder from - <https://github.com/solana-labs/solana/releases>

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2Fcbf55025-5652-458e-b720-968b478699d5%2Fimage.png?table=block&#x26;id=e6c91833-5ad8-4532-9e04-801721de7f50&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

Unzip and you should see all the .exe files

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2Ffbe643cb-2b8d-455a-8fed-3ec7946781f1%2Fimage.png?table=block&#x26;id=7c601b09-1415-4032-ab87-89c8457013d8&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

#### Confirm by running commands

#### &#x20;RPC URL, Testnet, Devnet, and Mainnet

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F19894833-1316-456d-8e79-9a24584edd67%2Fimage.png?table=block&#x26;id=b512ca6c-ff5b-4a45-bc95-5948662d5607&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

#### What is an RPC URL?

* RPC (Remote Procedure Call) URLs allow applications like browsers, wallets, and users to interact with the Solana blockchain.
* By sending requests to an RPC URL, you can query the blockchain and perform various operations.
* How to Use RPC URLs:

&#x20;        Mainnet: `https://api.mainnet-beta.solana.com`

&#x20;        Devnet: `https://api.devnet.solana.com`

&#x20;        Testnet: `https://api.testnet.solana.com`

💡[Clusters and Public RPC Endpoints | Solana](https://solana.com/docs/core/clusters)

#### Changing RPC URLs

Use the following commands to set the appropriate RPC URL for your environment:

```shell
# Set RPC URL for Mainnet
solana config set --url https://api.mainnet-beta.solana.com

# Set RPC URL for Devnet
solana config set --url https://api.devnet.solana.com

# Set RPC URL for Testnet
solana config set --url https://api.testnet.solana.com
```

#### Solana Networks

* Mainnet: The live Solana blockchain where real transactions occur. It’s secure and used for deploying production applications.
* Testnet: A testing environment that mimics the mainnet but is used for testing applications before deploying them to the mainnet. It does not use real SOL.
* Devnet: A development environment similar to the testnet but specifically for developers to experiment and test applications. You can freely request SOL from the [Solana Devnet Faucet](https://faucet.solana.com/) for testing purposes.

**Using Devnet and Testnet**

* Airdrop SOL: On Devnet, you can use the faucet to receive free SOL for testing.
* Local Testing: Use the Solana Test Validator to start a local validator for testing applications without relying on external networks.

```javascript
solana-test-validator
```

**Solana Explorer**

* Explorer Tool: You can view transactions, account balances, and more on the Solana blockchain using the [Solana Explorer](https://explorer.solana.com/), which supports Devnet, Testnet, Mainnet, and custom RPC URLs.

<figure><img src="/files/lPenNxCCtDrnBWc7BSf6" alt=""><figcaption></figcaption></figure>

### 3. Core Concepts 🧠

#### 3.1 Accounts

In Solana, an account is a fundamental data structure that can hold data and SOL tokens. There are two types of accounts:

* Data Accounts: Store program-specific data
* SOL Accounts: Hold SOL tokens

#### 3.2 Programs

Programs in Solana are similar to smart contracts in other blockchains. They are stateless and can be called to operate on accounts.

#### 3.3 Transactions

Transactions in Solana are atomic, meaning they either complete entirely or fail entirely. A transaction consists of one or more instructions.

#### 3.4 Instructions

Instructions are the basic unit of execution in Solana. Each instruction specifies a program to call, accounts to pass to the program, and data that serves as input to the program.

### 4. Key Features 🔑

#### 4.1 Proof of History (PoH)

Proof of History is a novel timekeeping method for distributed systems. It creates a historical record that proves that an event has occurred at a specific moment in time.

#### 4.2 Tower BFT

Tower BFT is Solana's implementation of Practical Byzantine Fault Tolerance (PBFT). It leverages the PoH as a reliable source of time before consensus to reduce messaging overhead and latency.

#### 4.3 Gulf Stream

Gulf Stream is Solana's mempool-less transaction forwarding protocol. It allows for transaction caching and forwarding at the edge of the network, reducing confirmation times and the memory pressure on validators.

#### 4.4 Sealevel

Sealevel is Solana's parallel smart contracts runtime. It allows for horizontal scaling of transaction processing across GPUs and SSDs.

### 5. Solana CLI Commands 🖥️

Here are some essential Solana CLI commands:

```bash
# Check your balance
solana balance

# Transfer SOL
solana transfer <RECIPIENT_ADDRESS> <AMOUNT> --allow-unfunded-recipient

# Deploy a program
solana program deploy <PROGRAM_FILEPATH>

# Get account info
solana account <ACCOUNT_ADDRESS>

# Get cluster info
solana cluster-version
```

These commands are crucial for interacting with the Solana blockchain, managing accounts, and deploying programs.

### 6. Benefits of Solana 🌈

* 🚀 High Performance: Solana's architecture allows for incredibly high transaction throughput.
* 💰 Low Costs: Transaction fees on Solana are very low, making it suitable for micro-transactions.
* ⚡ Fast Finality: Transactions are confirmed quickly, providing a smooth user experience.
* 🌿 Eco-Friendly: Solana's Proof of Stake consensus mechanism is more energy-efficient than Proof of Work.
* 🔧 Developer-Friendly: With a growing ecosystem and developer tools, Solana is becoming increasingly accessible for builders.

This comprehensive guide should give you a solid foundation in Solana development. Remember, the best way to learn is by doing, so don't hesitate to start building your own Solana projects! Happy coding! 🚀👨‍💻👩‍💻

### 7. Accounts in Solana

#### What is an Account?

* In Solana, an account is a data structure that includes a public-private key pair (using the `ed25519` elliptic curve).
* Types of Accounts:
* Wallet Accounts: These accounts represent user wallets that can hold lamports (Solana’s native currency).
* Data Accounts: These accounts store data on the blockchain and can be used for various decentralized applications.
* Program Accounts: These are special accounts that store executable code, allowing smart contracts (known as "programs" in Solana) to run on the blockchain.

#### Rent on Solana

* Purpose of Rent: To prevent the blockchain from being clogged with inactive or unnecessary data, Solana charges rent for storing data.
* Rent Calculation: Rent is based on the storage size and the duration the account remains on the blockchain.
* Rent Exemption: If an account maintains a balance above a certain threshold, it becomes "rent-exempt," meaning it does not incur further rent charges. The rent paid is refundable when the account is closed.

💡[What is Rent on Solana and How to Calculate it | QuickNode](https://www.quicknode.com/guides/solana-development/getting-started/understanding-rent-on-solana)

#### Efficient Storage Management

* Incentivizing Minimal Storage: The rent model encourages users to store only the necessary data, reducing blockchain bloat.
* Removing Inactive Accounts: Accounts that fail to pay the required rent are eventually removed from the ledger, ensuring efficient use of blockchain resources.

#### Calculating Rent-Exempt Threshold

* Methods to Calculate:

1. Solana CLI: Command-line interface tools.
2. Solana Web3.js Library: JavaScript library for interacting with the Solana blockchain.
3. Anchor's Space Constraint: A framework-specific approach for calculating space requirements for accounts.

### 8. Web2 Data Model vs. Solana Data Model

#### Web2 Data Model

* Applications are typically deployed on cloud providers with backend code and data storage separated.
* Databases: Use SQL or NoSQL databases to store user data.
* Data Management: Adding or deleting a user involves simply adding or removing a row in the database.

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2Fc15c982b-5c55-4944-a00b-d83858a8d019%2Fimage.png?table=block&#x26;id=21632abc-e9e8-43bb-b6f9-56d318f798d0&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

#### Solana Data Model

* **Smart Contracts:** In Web3, smart contracts are equivalent to backend applications in Web2. These are deployed on the blockchain.
* **Program Storage**: On Solana, smart contracts (called "programs") are stored in executable accounts.
* **Data Storage**: Unlike Ethereum, where data and smart contract code are stored together, Solana separates them:
* **Data Accounts:** Store data independently from programs.
* **Executable Accounts:** Store the smart contract code (programs).

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F7e490be3-ab63-49ee-aa64-8bb464877adf%2Fimage.png?table=block&#x26;id=080dd7c6-7d54-4ae9-9d6f-03ba21016cec&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

#### Key Differences and Implications

* User Account Management:
* In Solana, each user requires a separate account, which adds complexity compared to simply adding a row in a Web2 database.
* **User-Paid Fees:** The responsibility for creating and funding these accounts, including paying for data rent, is delegated to the user.
* **Decentralized Fees:** Users pay the fees for their individual accounts, not the program itself. If an account is closed, any remaining rent is refunded to the user.

### 9. Token Program on Solana

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F4c72686b-9143-4b7b-9c57-ff138d9abbbf%2Fimage.png?table=block&#x26;id=fbec9f64-e09e-4a83-9577-d469cf550f86&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

#### Creating Tokens: Ethereum vs. Solana

* **Ethereum:**
* To create a token, you must deploy your own smart contract.
* Ethereum provides a standard template (ERC-20), but each token requires its own contract to be deployed on the blockchain.
* **Solana:**
* Solana simplifies this process with a single, pre-deployed Token Program.
* Instead of deploying a new contract, you only need to create a token account under this program.
* This significantly reduces complexity and deployment costs.

#### Understanding Tokens

* Tokens represent one of the primary use cases of blockchain technology, acting as digital assets or currencies that can be transferred or traded on the blockchain.
* Examples: USDC and USDT are popular stablecoins that have found significant market adoption. These tokens do not have their own blockchain; instead, they operate as smart contracts on existing blockchains like Ethereum and Solana.
* Why Use Existing Blockchains?
* Tokens like USDC and USDT leverage the security and infrastructure of established blockchains such as Solana and Ethereum. This allows them to function without maintaining their own blockchain or miners.
* The Token Program is essentially a mapping from an account to a number, representing the balance of tokens held by an account.

💡Explore various tokens and their market data on [CoinMarketCap](https://coinmarketcap.com/).

#### Solana's Token Program

* Centralized Token Program:
* Solana engineers recognized the importance of tokens and created a dedicated Token Program.
* This program is pre-deployed on the Solana blockchain, simplifying token creation.
* Mint Accounts:
* When creating a token on Solana, you establish a mint account under the Token Program.
* A mint account functions like a bank for your token, overseeing its supply but without executing any code. It does not run transactions or logic on its own; instead, it is responsible for managing the minting and overall supply of tokens.
* Associated token account:
* Associated Token Account is a token account whose address is deterministically derived using the owner's address and the mint account's address.

💡Solana program library: [solana-labs/solana-program-library: A collection of Solana programs maintained by Solana Labs (github.com)](https://github.com/solana-labs/solana-program-library)

#### Creating a Token using CLI

#### Creating a Token using JavaScript

* Check your balance in the explorer
* Import the token in Phantom and see the balances

#### Equivalent code in rust/python/go

Solana has libraries similar to `@solana/web3.js` in Rust, Python that would let you do the same thing.In the end, they all are sending requests to an RPC server.

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F3ebb35b1-78ca-47ba-9869-456f9e574ca9%2Fimage.png?table=block&#x26;id=c5b86b13-eab1-44ea-81bd-802f8e0e2416&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

### 10. Token 22 program

* A token program on the Solana blockchain, defining a common implementation for fungible and non-fungible tokens.
* The Token-2022 Program, also known as Token Extensions, is a superset of the functionality provided by the [Token Program](https://spl.solana.com/token).

💡<https://spl.solana.com/token-2022>

<details>

<summary>Create token mint</summary>

```shell
 spl-token create-token  --program-id TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb
```

</details>

<details>

<summary>Create an <code>associated token account</code></summary>

```shell
spl-token create-account 8fTM5XYRaoTJU9PLUuyakF3EypQ4RXL5HxKtiw2z9pQQ
```

</details>

<details>

<summary>Mint the tokens</summary>

```shell
spl-token mint 8fTM5XYRaoTJU9PLUuyakF3EypQ4RXL5HxKtiw2z9pQQ  100
```

</details>

#### Token 22 with metadata

<details>

<summary>Create a token with metadata enabled</summary>

```shell
spl-token --program-id TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb create-token --enable-metadata
```

</details>

<details>

<summary>Create metadata</summary>

```shell
spl-token initialize-metadata pXfZ6Hg2s78m1iSRVsdzos9TmfkqkQdv5MmQrr77ZQK 100xx 100xxx https://cdn.100xdevs.com/metadata.json
```

</details>

<details>

<summary>Create <code>associated token account</code></summary>

```shell
 spl-token create-account pXfZ6Hg2s78m1iSRVsdzos9TmfkqkQdv5MmQrr77ZQK
```

</details>

<details>

<summary>Mint</summary>

```shell
 spl-token mint 1000
```

</details>

<details>

<summary>Check out the token in your wallet</summary>

![](/files/0xtJdjOFhRgJk2GHGPIM)

</details>

## 11. Accounts

Ref - <https://solana.com/docs/core/accounts>

On Solana, all data is stored in what are referred to as "accounts”. The way data is organized on Solana resembles a [key-value store](https://en.wikipedia.org/wiki/Key%E2%80%93value_database), where each entry in the database is called an "account".

<figure><img src="/files/cwVdKVfaVHAnbYvIcSRl" alt=""><figcaption></figcaption></figure>

**Key points**

* Accounts can store up to 10MB of data, which can consist of either executable program code or program state.
  * Programs (smart contracts) are stateless accounts that store executable code.
  * Data accounts are created by programs to store and manage program state.
* Accounts require a rent deposit in SOL, proportional to the amount of data stored, which is fully refundable when the account is closed.
* Every account has a program `owner`. Only the program that owns an account can modify its data or deduct its lamport balance. However, anyone can increase the balance.
* Native programs are built-in programs included with the Solana runtime.

**Account**

Each account is identifiable by its unique address, represented as 32 bytes in the format of an [Ed25519](https://ed25519.cr.yp.to/) `PublicKey`. You can think of the address as the unique identifier for the account.

**AccountInfo**

Accounts have a [max size of 10MB](https://github.com/solana-labs/solana/blob/27eff8408b7223bb3c4ab70523f8a8dca3ca6645/sdk/program/src/system_instruction.rs#L85) (10 Mega Bytes) and the data stored on every account on Solana has the following structure known as the [AccountInfo](https://github.com/solana-labs/solana/blob/27eff8408b7223bb3c4ab70523f8a8dca3ca6645/sdk/program/src/account_info.rs#L19).

<figure><img src="/files/Q7dFHBrFr08Z5D2RWqRI" alt=""><figcaption></figcaption></figure>

Even if you store not data, you have to store fields like executable and owner which is why you still have to have a minimum amount of SOL as rent solana rent 0

**Example accounts**

* Account with no data (Owner - SystemProgram)

  <https://explorer.solana.com/address/5gjLjKtBhDxWL4nwGKprThQwyzzNZ7XNAVFcEtw3rD4i>

<figure><img src="/files/11S7MPDjBEX2fHnnQ0ZR" alt=""><figcaption></figcaption></figure>

* Account with some data (Owner - TokenProgram)

  <https://explorer.solana.com/address/8FQvjBxFdR51wbZfQVaWbkjR2sNNxDLyabNePPmsyou9>
*

```
<figure><img src="/files/uVOCm0BtUHf1Hmk32EZW" alt=""><figcaption></figcaption></figure>
```

<figure><img src="/files/hHwyignVbJgIHeIzBg5d" alt=""><figcaption></figcaption></figure>

Program account (Owner - BPF Loader)

[https://explorer.solana.com/address/TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5D](https://explorer.solana.com/address/TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA)

<figure><img src="/files/tT82WZ5heyceE0hiN0V8" alt=""><figcaption></figcaption></figure>

## 12. System program

Solana contains a small handful of native programs that are part of the validator implementation and provide various core functionalities for the network.

When developing custom programs on Solana, you will commonly interact with two native programs, the `System Program` and the `BPF Loader`.

By default, all new accounts are owned by the [System Program](https://github.com/solana-labs/solana/tree/27eff8408b7223bb3c4ab70523f8a8dca3ca6645/programs/system/src). The System Program performs several key tasks such as:

* [New Account Creation](https://github.com/solana-labs/solana/blob/27eff8408b7223bb3c4ab70523f8a8dca3ca6645/programs/system/src/system_processor.rs#L145): Only the System Program can create new accounts.
* [Space Allocation](https://github.com/solana-labs/solana/blob/27eff8408b7223bb3c4ab70523f8a8dca3ca6645/programs/system/src/system_processor.rs#L70): Sets the byte capacity for the data field of each account.
* [Assign Program Ownership](https://github.com/solana-labs/solana/blob/27eff8408b7223bb3c4ab70523f8a8dca3ca6645/programs/system/src/system_processor.rs#L112): Once the System Program creates an account, it can reassign the designated program owner to a different program account. This is how custom programs take ownership of new accounts created by the System Program.

On Solana, a `wallet` is simply an account owned by the System Program. The lamport balance of the wallet is the amount of SOL owned by the account.

<figure><img src="/files/OkQucHmHxxhvzqkjURDD" alt=""><figcaption></figcaption></figure>

**Using `@solana/web3.js` to interact with the System program**

* Create a new account with data and rent

  ```jsx
  const { Keypair, Connection, SystemProgram, Transaction } = require('@solana/web3.js');

  const payer = Keypair.fromSecretKey(Uint8Array.from([222,61,190,103,38,70,4,221,24,242,44,86,66,111,102,52,87,41,83,45,166,179,184,79,208,91,20,66,142,36,147,236,30,84,33,77,227,36,159,27,27,53,27,249,230,207,30,83,42,51,3,225,70,41,44,85,54,31,198,80,45,49,208,39]));

  const mintAthority = payer;

  const connection = new Connection("<https://api.devnet.solana.com>");
  async function main() {
      const newAccount = Keypair.generate();
      const TOTAL_BYTES = 165;
      const lamports = await connection.getMinimumBalanceForRentExemption(TOTAL_BYTES);
      const transaction = new Transaction();
      transaction.add(
          SystemProgram.createAccount({
              fromPubkey: payer.publicKey,
              newAccountPubkey: newAccount.publicKey,
              lamports: lamports,
              space: TOTAL_BYTES,
              programId: SystemProgram.programId,
          }),
      );

      await connection.sendTransaction(transaction, [payer, newAccount]);
      console.log(`New account created at ${newAccount.publicKey.toBase58()}`);
  }

  main();
  ```

  <figure><img src="/files/uSBfqrZfQnWts5ouapk0" alt=""><figcaption></figcaption></figure>
* Transfer lamports from your account to another account

  ```jsx
  const { createMint } = require('@solana/spl-token');
  const { Keypair, Connection, SystemProgram, Transaction } = require('@solana/web3.js');

  const payer = Keypair.fromSecretKey(Uint8Array.from([222,61,190,103,38,70,4,221,24,242,44,86,66,111,102,52,87,41,83,45,166,179,184,79,208,91,20,66,142,36,147,236,30,84,33,77,227,36,159,27,27,53,27,249,230,207,30,83,42,51,3,225,70,41,44,85,54,31,198,80,45,49,208,39]));

  const mintAthority = payer;

  const connection = new Connection("<https://api.devnet.solana.com>");
  async function main() {
      const newAccount = Keypair.generate();
      const TOTAL_BYTES = 165;
      const lamports = await connection.getMinimumBalanceForRentExemption(TOTAL_BYTES);
      const transaction = new Transaction();
      transaction.add(
          SystemProgram.transfer({
              fromPubkey: payer.publicKey,
              toPubkey: newAccount.publicKey,
              lamports,
          }),
      );

      await connection.sendTransaction(transaction, [payer, newAccount]);
      console.log(`Transferred to  ${newAccount.publicKey.toBase58()}`);
  }

  main();
  ```

<figure><img src="/files/ePaXXLjEhIJpSiV95Ov8" alt=""><figcaption></figcaption></figure>

* Change the owner of an account

  ```jsx
  const { createMint } = require('@solana/spl-token');
  const { Keypair, Connection, SystemProgram, Transaction } = require('@solana/web3.js');

  const payer = Keypair.fromSecretKey(Uint8Array.from([222,61,190,103,38,70,4,221,24,242,44,86,66,111,102,52,87,41,83,45,166,179,184,79,208,91,20,66,142,36,147,236,30,84,33,77,227,36,159,27,27,53,27,249,230,207,30,83,42,51,3,225,70,41,44,85,54,31,198,80,45,49,208,39]));

  const connection = new Connection("<https://api.devnet.solana.com>");
  async function main() {
      const newAccount = Keypair.generate();
      const owner = Keypair.generate();
      const TOTAL_BYTES = 165;
      const lamports = await connection.getMinimumBalanceForRentExemption(TOTAL_BYTES);
      const transaction = new Transaction();
      transaction.add(
          SystemProgram.createAccount({
              fromPubkey: payer.publicKey,
              newAccountPubkey: newAccount.publicKey,
              lamports: lamports,
              space: TOTAL_BYTES,
              programId: owner.publicKey,
          }),
      );

      await connection.sendTransaction(transaction, [payer, newAccount]);
      console.log(`New account created at ${newAccount.publicKey.toBase58()}`);
  }

  main();

  ```

## 13. BPF Loader Program

The [BPF Loader](https://github.com/solana-labs/solana/tree/27eff8408b7223bb3c4ab70523f8a8dca3ca6645/programs/bpf_loader/src) is the program designated as the "owner" of all other programs on the network, excluding Native Programs. It is responsible for deploying, upgrading, and executing custom programs.

A program I deployed just before todays class - <https://explorer.solana.com/address/8rpHNPsyEJQEJjC2waWvUXyvCkYghCZndACoXs9sNKZg?cluster=devnet>

<figure><img src="/files/1HOjiMM62EqYQc5BGXKX" alt=""><figcaption></figcaption></figure>

## 14. Authority in solana programs

In Solana programs, `authorities` are entities or accounts that have the right to perform certain actions or make changes within the program.

For example

* Token mint authority - Can mint new tokens
  1. Token with mint auth - <https://explorer.solana.com/address/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v>
  2. Token with No mint auth - <https://explorer.solana.com/address/8FQvjBxFdR51wbZfQVaWbkjR2sNNxDLyabNePPmsyou9>
* Token freeze authority - Can freeze tokens in an account

  Token with a freeze auth - <https://explorer.solana.com/address/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v>
* Upgrade authority - Can `upgrade` the code of a program.

  <https://explorer.solana.com/address/8rpHNPsyEJQEJjC2waWvUXyvCkYghCZndACoXs9sNKZg?cluster=devnet>

<figure><img src="/files/aR1kG5rWnJU95Ia2aghH" alt=""><figcaption></figcaption></figure>

### Creating and revoking mint authority

* Create a new token

```jsx
spl-token create-token
```

* Create an ata

```jsx
spl-token create-account <token_mint_address> 
```

* Try minting some tokens

```jsx
spl-token mint <token_mint_address> 10000000000
```

* Check if `mint authority` exists on explorer

<figure><img src="/files/NbbpTTzowa1U81GN90oi" alt=""><figcaption></figcaption></figure>

* Revoke `mint authority`

```jsx
spl-token authorize  <token_id>  mint --disable
```

* Try to mint again/check the explorer

```
spl-token mint <token_mint_address> 10000000000
```

<figure><img src="/files/M315STodq4aPwKW5RsGb" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/NG7hs0MI7ZXqplUBlqtj" alt=""><figcaption></figcaption></figure>

## Program derived addresses

![](https://petal-estimate-4e9.notion.site/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2Ffc9ec62d-8dd7-4d60-a246-ea6bb546408e%2FScreenshot_2024-09-13_at_7.12.22_PM.png?table=block\&id=2ed38db8-b55e-438b-a2f2-5c9d2f7b0bc6\&spaceId=085e8ad8-528e-47d7-8922-a23dc4016453\&width=1420\&userId=\&cache=v2)

Ref - <https://solana.com/docs/core/pda>

Video - <https://www.youtube.com/watch?v=p0eD29d8JCM>

Program Derived Addresses (PDAs) provide developers on Solana with two main use cases:

* **Deterministic Account Addresses**: PDAs provide a mechanism to deterministically derive an address using a combination of optional "seeds" (predefined inputs) and a specific program ID.
* **Enable Program Signing**: The Solana runtime enables programs to "sign" for PDAs which are derived from its program ID.

### Properties

* PDAs are addresses derived deterministically using
  * a combination of user-defined seeds
  * a bump seed
  * and a program's ID.
* PDAs are addresses that fall off the Ed25519 curve and have no corresponding private key.
* Solana programs can programmatically "sign" for PDAs that are derived using its program ID.
* Deriving a PDA does not automatically create an on-chain account.
* An account using a PDA as its address must be explicitly created through a dedicated instruction within a Solana program.

#### Find the associated token account for a user and a mint

```
const { PublicKey } = require('@solana/web3.js');
const { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID } = require('@solana/spl-token');

// Replace these with your actual values
const userAddress = new PublicKey('5gjLjKtBhDxWL4nwGKprThQwyzzNZ7XNAVFcEtw3rD4i');
const tokenMintAddress = new PublicKey('6NeR2StEEb6CP75Gsd7ydbiAkabdriMdixPmC2U9hcJs');

// Derive the associated token address
const getAssociatedTokenAddress = (mintAddress, ownerAddress) => {
    return PublicKey.findProgramAddressSync(
        [
            ownerAddress.toBuffer(),
            TOKEN_PROGRAM_ID.toBuffer(),
            mintAddress.toBuffer(),
        ],
        ASSOCIATED_TOKEN_PROGRAM_ID
    );
};

const [associatedTokenAddress, bump] = getAssociatedTokenAddress(tokenMintAddress, userAddress);
console.log(`Associated Token Address: ${associatedTokenAddress.toBase58()}, bump: ${bump}`);


```


# Ethereum

### 1. Introduction to Ethereum 🌐

Ethereum is a decentralized, open-source blockchain platform that enables the creation and deployment of smart contracts and decentralized applications (DApps). It was proposed in 2013 by Vitalik Buterin and went live in 2015.

#### Key Features of Ethereum:

* **Smart Contracts:** Self-executing contracts with the terms directly written into code
* **Decentralized Applications (DApps)**: Applications that run on a P2P network of computers
* **Ethereum Virtual Machine (EVM):** Turing-complete software that runs on the Ethereum network
* **Ether (ETH):** The native cryptocurrency of the Ethereum platform

### 2. Core Concepts of Ethereum 🧠

#### 2.1 Accounts

Ethereum has two types of accounts:

* Externally Owned Accounts (EOAs): Controlled by private keys
* Contract Accounts: Controlled by their contract code

#### 2.2 Transactions

Transactions are signed data packages that store a message to be sent from an EOA to another account on the blockchain.

#### 2.3 Gas

Gas is the unit that measures the amount of computational effort required to execute operations on the Ethereum network.

#### 2.4 Blocks

Blocks are batches of transactions with a hash of the previous block in the chain.

### 3. Smart Contracts 📜

Smart contracts are self-executing contracts with the terms directly written into code. Here's a simple example:

```solidity
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private storedData;

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}
```

### 4. Benefits of Ethereum 🌟

* Decentralization: No central point of failure
* Transparency: All transactions are public
* Immutability: Once data is written, it cannot be changed
* Programmable: Allows creation of complex decentralized applications

### 5. When to Use Ethereum 🤔

Ethereum is ideal for:

* Creating decentralized finance (DeFi) applications
* Implementing transparent and immutable record-keeping systems
* Developing decentralized autonomous organizations (DAOs)
* Creating non-fungible tokens (NFTs)

While Ethereum has achieved significant milestones, it has also faced challenges, including scalability and transaction fees. To address these, Ethereum is undergoing a major upgrade called Ethereum 2.0, which aims to improve scalability, security, and efficiency. &#x20;

**In essence, Ethereum is more than just a cryptocurrency; it's a platform that empowers developers to build and deploy decentralized applications with a wide range of potential use cases.** &#x20;


# Polygon & Zero knowldge Proof

## 1. Introduction to Polygon 🌐

Polygon (formerly known as Matic Network) is a Layer 2 scaling solution for Ethereum that aims to provide faster and cheaper transactions on the blockchain. It's designed to solve some of Ethereum's major limitations, such as low throughput and high gas fees.

#### Key Features of Polygon:

* Scalability: Handles a high number of transactions per second
* Low fees: Significantly reduces transaction costs
* Interoperability: Seamlessly connects with Ethereum and other blockchains
* Developer-friendly: Supports Ethereum tools and languages

#### Architecture of Polygon:

<figure><img src="/files/SrqhIKm7v5asjLwaNz4W" alt=""><figcaption></figcaption></figure>

### 2. Setting Up Polygon Development Environment 🛠️

#### Prerequisites:

* Node.js and npm installed
* MetaMask browser extension
* Truffle framework (optional, for smart contract development)

#### Installation Steps:

1. Install Truffle (if not already installed):

```bash
npm install -g truffle
```

1. Create a new Truffle project:

```bash
mkdir polygon-project
cd polygon-project
truffle init
```

1. Install Polygon-specific dependencies:

```bash
npm install @maticnetwork/maticjs @maticnetwork/maticjs-web3
```

**How Polygon works:**

* **Sidechains:** Polygon creates parallel blockchains (sidechains) that run independently of the main Ethereum chain. Transactions are processed on these sidechains, and then a summary of these transactions is posted on the main Ethereum chain for security. &#x20;
* **Plasma:** Similar to sidechains, Plasma allows for faster transactions off-chain. However, it requires a longer dispute period in case of fraudulent activity. &#x20;
* **PoS Chains:** Polygon also offers Proof-of-Stake (PoS) sidechains, which are more secure and energy-efficient than traditional Proof-of-Work (PoW) chains. &#x20;

**Benefits of Polygon:**

* **Scalability:** Handles a higher volume of transactions than Ethereum. &#x20;
* **Speed:** Faster transaction confirmation times.
* **Lower fees:** Significantly reduced transaction costs compared to Ethereum. &#x20;
* **Compatibility:** Built on Ethereum, allowing for interoperability with the Ethereum ecosystem. &#x20;

### 3. Introduction to Zero Knowledge Proofs (ZKPs) 🔐

**Zero-Knowledge Proofs**  are cryptographic methods that allow one party (the prover) to prove to another party (the verifier) that a statement is true, without revealing any information beyond the validity of the statement itself.

#### Key Concepts of ZKPs:

* Completeness: If the statement is true, an honest verifier will be convinced by an honest prover
* Soundness: If the statement is false, no cheating prover can convince an honest verifier that it's true
* Zero-knowledge: The verifier learns nothing other than the fact that the statement is true

#### Types of ZKPs:

* Interactive ZKPs: Require back-and-forth communication between prover and verifier
* Non-interactive ZKPs (NIZKs): Proof can be verified without interaction

### 4. Implementing ZKPs in Blockchain 🔗

ZKPs have several applications in blockchain technology, particularly for enhancing privacy and scalability. Here's a simple example of how you might implement a basic ZKP system using zk-SNARKs (Zero-Knowledge Succinct Non-Interactive Argument of Knowledge) with the circom library and snarkjs.

#### Installation:

```bash
npm install -g circom snarkjs
```

#### Creating a Simple ZKP Circuit:

1. Create a file named `circuit.circom`:

```
pragma circom 2.0.0;

template Multiplier() {
    signal input a;
    signal input b;
    signal output c;
    
    c <== a * b;
}

component main = Multiplier();
```

1. Compile the circuit:

```bash
circom circuit.circom --r1cs --wasm --sym
```

1. Generate a trusted setup:

```bash
snarkjs powersoftau new bn128 12 pot12_0000.ptau -v
snarkjs powersoftau contribute pot12_0000.ptau pot12_0001.ptau --name="First contribution" -v
snarkjs powersoftau prepare phase2 pot12_0001.ptau pot12_final.ptau -v
snarkjs groth16 setup circuit.r1cs pot12_final.ptau circuit_0000.zkey
snarkjs zkey contribute circuit_0000.zkey circuit_0001.zkey --name="1st Contributor Name" -v
snarkjs zkey export verificationkey circuit_0001.zkey verification_key.json
```

1. Generate a proof:

```bash
echo '{"a": 3, "b": 4}' > input.json
snarkjs groth16 prove circuit_0001.zkey witness.wtns proof.json public.json
```

1. Verify the proof:

```bash
snarkjs groth16 verify verification_key.json public.json proof.json
```

### 5. Integrating ZKPs with Polygon 🔗🌐

Polygon has its own ZK rollup solution called Polygon zkEVM, which uses ZK proofs to validate transactions off-chain and then posts the proof on-chain. Here's a high-level overview of how you might integrate ZKPs with a Polygon smart contract:

```solidity
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

contract ZKProofVerifier {
    using ECDSA for bytes32;

    function verifyProof(bytes32 messageHash, bytes memory signature) public pure returns (address) {
        return messageHash.recover(signature);
    }

    function hashMessage(string memory message) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(message));
    }
}
```

This contract provides a basic framework for verifying signatures, which could be extended to work with more complex ZK proof systems.

### 6. Benefits and Use Cases 🌟

**Benefits of ZKPs:**

* **Privacy:** Protects sensitive information by revealing only the necessary data. &#x20;
* **Scalability:** Can be used to create more efficient and scalable blockchain systems. &#x20;
* **Security:** Provides a high level of security by verifying information without revealing it.&#x20;

**How ZKPs work:**

* **The prover generates a proof:** The prover creates a mathematical proof that demonstrates knowledge of the information without revealing it. &#x20;
* **The verifier verifies the proof:** The verifier can check the validity of the proof without learning any details about the information. &#x20;

#### Use Cases:

* DeFi applications requiring high transaction throughput
* Privacy-preserving payment systems
* Scalable NFT marketplaces
* Secure and private identity verification systems

### 7. Conclusion 🎓

Polygon and Zero Knowledge Proofs represent cutting-edge technologies in the blockchain space. Polygon offers a scalable and efficient platform for building decentralized applications, while ZKPs provide powerful tools for enhancing privacy and security. As these technologies continue to evolve, they promise to play a crucial role in the future of blockchain and cryptography.

**In summary,** Polygon is a powerful scaling solution for Ethereum, and Zero-Knowledge Proofs are a cutting-edge cryptographic technology that can further enhance its capabilities. Together, they have the potential to revolutionize the blockchain industry.


# Bitcoin

## Bitcoin: The Revolutionary Cryptocurrency 💰

Bitcoin is a decentralized digital currency that has revolutionized the financial world since its introduction in 2009. This comprehensive guide will explore Bitcoin's inner workings, key features, advantages, disadvantages, and the reasons behind its creation.

### 1. Bitcoin's Origin and Purpose 🎯

Bitcoin was introduced in 2008 by an anonymous person or group using the pseudonym Satoshi Nakamoto. The primary purpose was to create a decentralized digital currency that could operate without the need for intermediaries like banks or governments.

> We have proposed a system for electronic transactions without relying on trust. - Satoshi Nakamoto, Bitcoin Whitepaper

The 2008 financial crisis highlighted the vulnerabilities of traditional financial systems, inspiring the creation of Bitcoin as an alternative.

### 2. How Bitcoin Works 🔍

* **Blockchain:** Bitcoin uses a technology called blockchain, which is a distributed ledger that records transactions across many computers. This ensures transparency and security.
* **Decentralization:** Bitcoin operates on a decentralized network, meaning no single entity controls it. This makes it resistant to censorship and downtime.
* **Mining:** New Bitcoins are created through a process called mining. Miners use powerful computers to solve complex mathematical problems. The first miner to solve the problem is rewarded with Bitcoins. This process also verifies and records transactions on the blockchain. &#x20;
* **Transactions:** Bitcoin transactions are peer-to-peer, meaning they occur directly between users without intermediaries like banks. These transactions are verified by the network and recorded on the blockchain.

### 3. Bitcoin's Impact

Bitcoin has revolutionized the financial world by introducing the concept of digital currencies and blockchain technology. It has sparked a wave of innovation and led to the creation of countless other cryptocurrencies and blockchain-based applications.

**However, Bitcoin also faces challenges:**

* **Volatility:** Bitcoin's price is highly volatile, making it a risky investment for some.
* **Energy Consumption:** Bitcoin mining consumes significant amounts of electricity, raising environmental concerns.
* **Scalability:** Bitcoin's network can handle a limited number of transactions per second.

Despite these challenges, Bitcoin continues to be a subject of fascination and debate, and its impact on the global financial landscape is undeniable.

#### Bitcoin's Impact

Bitcoin has revolutionized the financial world by introducing the concept of digital currencies and blockchain technology. It has sparked a wave of innovation and led to the creation of countless other cryptocurrencies and blockchain-based applications.

**However, Bitcoin also faces challenges:**

* **Volatility:** Bitcoin's price is highly volatile, making it a risky investment for some.
* **Energy Consumption:** Bitcoin mining consumes significant amounts of electricity, raising environmental concerns.
* **Scalability:** Bitcoin's network can handle a limited number of transactions per second.

Despite these challenges, Bitcoin continues to be a subject of fascination and debate, and its impact on the global financial landscape is undeniable.

### 4. Key Features of Bitcoin 🔑

* **Decentralization:** No central authority controls Bitcoin.
* **Transparency:** All transactions are publicly visible on the blockchain.
* **Limited Supply:** Only 21 million Bitcoins will ever exist.
* **Pseudonymity:** Users can transact without revealing their real-world identity.
* **Irreversibility:** Once confirmed, transactions cannot be reversed.

### 5. Advantages of Bitcoin 👍

* **Financial Freedom:** Users have full control over their funds.
* **Low Transaction Fees:** Especially for international transfers.
* **Fast Transactions:** Payments can be sent and received quickly.
* **Inflation Resistance:** Due to its limited supply, Bitcoin is often seen as a hedge against inflation.
* **Accessibility:** Anyone with internet access can use Bitcoin.

### 6. Disadvantages of Bitcoin 👎

* **Volatility:** Bitcoin's value can fluctuate dramatically.
* **Scalability Issues:** The network can become congested, leading to slower transaction times.
* **Energy Consumption:** Bitcoin mining requires significant computational power and electricity.
* **Regulatory Uncertainty:** Many countries are still developing laws around cryptocurrencies.
* **Security Risks:** If private keys are lost or stolen, funds can be irretrievably lost.

### 7. User Flow in Bitcoin Transactions 🔄

Here's a simplified user flow for a Bitcoin transaction:

<figure><img src="/files/43GqKSTBnLrmGhn3M91K" alt=""><figcaption></figcaption></figure>

### 8. Core Engineering Concepts 🛠️

#### 8.1 Merkle Trees

Bitcoin uses Merkle trees to efficiently verify transactions within blocks.

```python
import hashlib

def hash_pair(a, b):
    return hashlib.sha256(a.encode() + b.encode()).hexdigest()

def build_merkle_tree(transactions):
    if len(transactions) == 1:
        return transactions[0]
    
    new_level = []
    for i in range(0, len(transactions), 2):
        if i + 1 < len(transactions):
            new_level.append(hash_pair(transactions[i], transactions[i+1]))
        else:
            new_level.append(transactions[i])
    
    return build_merkle_tree(new_level)

# Example usage
transactions = ["tx1", "tx2", "tx3", "tx4"]
merkle_root = build_merkle_tree(transactions)
print(f"Merkle Root: {merkle_root}")
```

#### 8.2 Proof of Work

Bitcoin uses a Proof of Work (PoW) consensus mechanism to secure the network and validate transactions.

```python
import hashlib
import time

def proof_of_work(block_data, difficulty):
    target = "0" * difficulty
    nonce = 0
    start_time = time.time()
    
    while True:
        hash_attempt = hashlib.sha256(f"{block_data}{nonce}".encode()).hexdigest()
        if hash_attempt.startswith(target):
            end_time = time.time()
            print(f"Found solution in {end_time - start_time:.2f} seconds")
            return nonce, hash_attempt
        nonce += 1

# Example usage
block_data = "test_block_data"
difficulty = 4
nonce, block_hash = proof_of_work(block_data, difficulty)
print(f"Nonce: {nonce}")
print(f"Block Hash: {block_hash}")
```

### 9. Defining Electronic Coins in Bitcoin

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F4cb423d8-db8c-4e12-995f-c2993ab99466%2Fimage.png?table=block&#x26;id=8136969c-ff4b-4b94-94f5-0455f9a987bc&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

**Concept of an Electronic Coin**

* **Definition:** An electronic coin in Bitcoin is defined as a chain of digital signatures. This chain represents the ownership history of the coin, tracking each time it changes hands.

**How Ownership is Transferred**

* **Transaction Structure:**
* Each time a coin is transferred, the current owner signs a digital hash of the previous transaction.
* **The hash includes:**
* The Previous Transaction: Proof of how the current owner acquired the coin.
* The Public Key of the Next Owner: Designates the new owner of the coin.
* **Digital Signatures:**
* The current owner uses their private key to create a digital signature, adding it to the end of the coin’s chain and effectively transferring ownership.
* **Hash of the Transaction**: A unique string generated from the transaction data, ensuring even a small change produces a completely different hash.
* **Public Key of the Next Owner:** Serves as the address to which the coin is sent; only the holder of the corresponding private key can access and spend the coin.

**Verification of Ownership**

* **Verification Process:**
* The payee can verify the transaction’s authenticity by checking the chain of digital signatures.
* **This involves:**
* Verifying the Signatures: Ensuring each signature in the chain is legitimate by checking against the corresponding public key.
* Verifying the Chain of Ownership: Tracing back the chain of transactions to confirm that the coin’s ownership has been validly transferred.

**Chain of Ownership**

* **Purpose**: The chain of digital signatures serves as a record of ownership, proving that the current owner has legitimately acquired the coin.
* **Security:** Ensures that the ownership of the coin is secure and can be verified without relying on a central authority.

### 10. Digital Signatures

* **Partial Solution:** Digital signatures ensure the authenticity and integrity of a transaction. While crucial for securing transactions, they do not fully solve the double-spending problem.
* **Double-Spending Problem**: Refers to the risk of a single digital token being spent more than once, an issue arising from the ease of copying digital information.
* Transactions are secured with digital signatures.
* Each Bitcoin user has a pair of cryptographic keys: a public key and a private key.
* The private key signs transactions, ensuring only the owner can spend their Bitcoins.

### 11. Peer-to-Peer Network and Proof-of-Work (PoW)

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F7d5f1c85-5d40-4a40-9b5b-aa0216190a98%2Fimage.png?table=block&#x26;id=be7d24f8-dcba-477f-8ae2-f4e6b4fe3d47&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

* **Proposed Solution**: Solving the double-spending problem using a peer-to-peer (P2P) network. The network’s key innovation is the proof-of-work mechanism.
* **Network Operation**: Nodes in the network validate and relay transactions.
* Timestamps and Hashing:
* Each transaction is timestamped and hashed into a chain (the blockchain).
* The chain is secured through proof-of-work, where nodes (miners) expend computational power to solve cryptographic puzzles.

<figure><img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2Feb4566ea-3499-40d2-868e-56036b453147%2F2b4534cf-668b-4d29-992f-4cc18a1dca3d%2Fimage.png?table=block&#x26;id=7db1b1ef-2d0d-4fdc-9994-c7c96472c3ac&#x26;cache=v2" alt="notion image"><figcaption></figcaption></figure>

* **Immutable Record:**
* The blockchain forms an ongoing, immutable record of transactions.
* Once a block is added to the chain, it cannot be altered without redoing the proof-of-work for that block and all subsequent blocks.
* **Mining Process:** Nodes (miners) solve complex mathematical problems to validate transactions and add them to the blockchain.
* **Rewards**: The first miner to solve the problem gets to add a new block and is rewarded with newly minted Bitcoins.

#### What is Proof-of-Work?

* Concept: Proof-of-work is a cryptographic mechanism where participants (miners) must perform computational work to solve a problem. In Bitcoin, this problem involves finding a value that, when hashed using a cryptographic hash function like SHA-256, produces a hash with a certain number of leading zero bits.
* Origin: The PoW system used in Bitcoin is similar to the one proposed by Adam Back in [Hashcash](https://en.wikipedia.org/wiki/Hashcash), originally designed to combat email spam by requiring senders to perform a small amount of computational work.

#### How Proof-of-Work Works

* Hash Function: Bitcoin uses the SHA-256 hash function, which takes an input and produces a fixed-size output (the hash). The goal is to find an input (a block of transactions) that produces a hash beginning with a specific number of zero bits.
* Difficulty: The number of leading zero bits required in the hash determines the difficulty of the proof-of-work. The more zero bits required, the harder it is to find such a hash. The difficulty is set to maintain a consistent average time to find a solution across the network.

### 12. Longest Chain Rule

* **Chain Validity:**
* The longest chain in the blockchain is considered valid because it represents the most computational work (CPU power) invested.
* This chain serves as proof of the sequence of events (transactions) and indicates that it was generated by the majority of the network’s computing power.
* **Security Assumption:**
* The network's security relies on the assumption that a majority of CPU power is controlled by honest nodes.
* As long as this is true, the honest nodes will always generate the longest chain, outpacing any attackers.
* Once a transaction is confirmed and added to the blockchain, it cannot be altered.

### 13. Network Structure and Operation

1. Minimal Structure:

* The network is designed to operate with minimal structure.
* Nodes do not need to follow strict protocols or maintain constant connectivity.

2. Broadcasting and Rejoining:

* Transactions and blocks are broadcasted to the network on a best-effort basis.
* Nodes can leave and rejoin the network at will. When they rejoin, they accept the longest proof-of-work chain as the authoritative record of transactions.
* Resilience and Flexibility: This decentralized approach ensures the network’s resilience and flexibility, allowing it to continue operating even if some nodes go offline or the network is under attack.

3. Incentives and Mining:

* Miners are incentivized to secure the network through block rewards and transaction fees.
* As more miners join, the difficulty of the mathematical problems increases, maintaining a steady block generation rate.

4. Limited Supply:

* Bitcoin has a fixed supply of 21 million coins, designed to create scarcity and mimic precious metals like gold.
* The block reward halves approximately every four years in an event known as "halving."

5. Decentralized Ledger (Blockchain):

* Transactions are grouped into blocks and linked together to form a blockchain.
* The blockchain is a public ledger, visible to all participants in the network.
* Each block contains a list of validated transactions and a reference (hash) to the previous block, ensuring immutability.

6. Security and Attacks:

* The network is secure as long as honest nodes control more CPU power than any attacking group.
* Discusses the "51% attack" scenario, where a malicious actor with more than 50% of the network's hashing power could potentially alter the blockchain.


# Solidity

### Solidity: The Language of Smart Contracts

**Solidity** is a high-level object-oriented programming language for implementing smart contracts. It was influenced by JavaScript and C++, making it relatively easy to learn for developers with a background in these languages. &#x20;

#### Core Concepts

* **Smart Contracts:** These are self-executing contracts with the terms of the agreement directly written into code. They are deployed on a blockchain and cannot be changed once deployed. &#x20;
* **Accounts:** Accounts in Ethereum are identified by their public key hash. They can be either externally owned accounts (EOAs) controlled by individuals or contract accounts representing smart contracts. &#x20;
* **Transactions:** Transactions are used to interact with the Ethereum network. They transfer value (Ether) between accounts and execute code within smart contracts. &#x20;
* **State:** Smart contracts maintain persistent storage called state. It's data that exists between function calls. &#x20;
* **Ether:** The native cryptocurrency of the Ethereum blockchain. &#x20;

#### Solidity Syntax

Solidity's syntax is similar to JavaScript, with some key differences:

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MyContract {
    uint public myNumber;

    constructor() public {
        myNumber = 42;
    }

    function increment() public {
        myNumber++;
    }

    function getNumber() public view returns (uint) {
        return myNumber;
    }
}
```

* **// SPDX-License-Identifier: MIT** : provides clear and essential licensing information
* **`pragma solidity ^0.8.0;`**: Specifies the Solidity compiler version.
* **`contract`**: Defines a smart contract. &#x20;
* **`uint`**: Unsigned integer data type.
* **`public`**: Access modifier, making the variable or function accessible from outside the contract.
* **`constructor`**: A special function that runs only once when the contract is deployed. &#x20;
* **`function`**: Defines a function within the contract. &#x20;
* **`view`**: Indicates that the function does not modify the contract's state. &#x20;
* **`returns`**: Specifies the function's return type.

#### Data Types

Solidity supports various data types, including:

* **Value types:** `uint`, `int`, `bool`, `address`, `bytes`, `string`, `enum`, `struct`
* **Reference types:** `array`, `mapping`, `contract`

**Example of using different data types:**

```solidity
pragma solidity ^0.8.0;

contract DataTypesExample {
    bool public isActive = true;
    int256 public signedInteger = -10;
    uint256 public unsignedInteger = 100;
    address public owner = msg.sender;
    bytes32 public data = "Hello, Solidity!";
    
    enum Status { Pending, Approved, Rejected }
    Status public currentStatus = Status.Pending;
    
    uint256[] public numbers = [1, 2, 3, 4, 5];
    mapping(address => uint256) public balances;
    
    struct User {
        string name;
        uint256 age;
    }
    User public user = User("Alice", 30);
}
```

#### 1.2 Functions

* **Pure functions:** Do not read from or modify state. &#x20;
* **View functions:** Read from state but do not modify it. &#x20;
* **Non-pure functions:** Can read and modify state.

Functions are the building blocks of Solidity contracts. Here's an overview of function syntax and types:

```solidity
contract FunctionExample {
    // Public function
    function add(uint256 a, uint256 b) public pure returns (uint256) {
        return a + b;
    }
    
    // Private function
    function _multiply(uint256 x, uint256 y) private pure returns (uint256) {
        return x * y;
    }
    
    // View function (reads state but doesn't modify)
    function getBalance() public view returns (uint256) {
        return address(this).balance;
    }
    
    // Pure function (doesn't read or modify state)
    function square(uint256 n) public pure returns (uint256) {
        return n * n;
    }
    
    // Payable function (can receive Ether)
    function deposit() public payable {
        // Function logic
    }
}
```

#### 1.3 Modifiers

Modifiers are used to add behavior to functions:

* `public`: Function can be called by anyone.
* `private`: Function can only be called from within the contract.
* `external`: Function can only be called from outside the contract.
* `internal`: Function can be called from within the contract and from contracts that inherit from it.

Modifiers are used to change the behavior of functions. They're commonly used for access control and input validation.

```solidity
contract ModifierExample {
    address public owner;
    uint256 public minimumBid;
    
    constructor(uint256 _minimumBid) {
        owner = msg.sender;
        minimumBid = _minimumBid;
    }
    
    modifier onlyOwner() {
        require(msg.sender == owner, "Only owner can call this function");
        _;
    }
    
    modifier validBid(uint256 _bid) {
        require(_bid >= minimumBid, "Bid too low");
        _;
    }
    
    function placeBid(uint256 _bid) public payable validBid(_bid) {
        // Bid logic here
    }
    
    function changeMinimumBid(uint256 _newMinimum) public onlyOwner {
        minimumBid = _newMinimum;
    }
}
```

#### 1.4 Events

Events allow contracts to emit information to the outside world. &#x20;

```solidity
event Transfer(address indexed from, address indexed to, uint value);
```

Events in Solidity are used to log activities within the contract. They're essential for frontend applications to listen for specific occurrences on the blockchain.

```solidity
contract EventExample {
    event Transfer(address indexed from, address indexed to, uint256 amount);
    event NewUser(address user, string name);
    
    function transfer(address _to, uint256 _amount) public {
        // Transfer logic here
        emit Transfer(msg.sender, _to, _amount);
    }
    
    function registerUser(string memory _name) public {
        // Registration logic here
        emit NewUser(msg.sender, _name);
    }
}
```

### 2. Advanced Solidity Concepts 🧠

#### 2.1 Inheritance

Solidity supports inheritance, allowing contracts to inherit properties and functions from parent contracts. &#x20;

```solidity
contract Ownable {
    address public owner;
    
    constructor() {
        owner = msg.sender;
    }
    
    modifier onlyOwner() {
        require(msg.sender == owner, "Not the owner");
        _;
    }
}

contract Pausable is Ownable {
    bool public paused;
    
    function pause() public onlyOwner {
        paused = true;
    }
    
    function unpause() public onlyOwner {
        paused = false;
    }
    
    modifier whenNotPaused() {
        require(!paused, "Contract is paused");
        _;
    }
}

contract MyToken is Ownable, Pausable {
    string public name;
    uint256 public totalSupply;
    
    constructor(string memory _name, uint256 _totalSupply) {
        name = _name;
        totalSupply = _totalSupply;
    }
    
    function mint(uint256 _amount) public onlyOwner whenNotPaused {
        // Minting logic here
    }
}
```

#### 2.2 Libraries

Libraries in Solidity are reusable pieces of code that can be called from other contracts. They're useful for implementing common functionalities.

```solidity
library SafeMath {
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }
    
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }
}

contract UsingLibrary {
    using SafeMath for uint256;
    
    function doMath(uint256 _a, uint256 _b) public pure returns (uint256, uint256) {
        uint256 sum = _a.add(_b);
        uint256 difference = _a.sub(_b);
        return (sum, difference);
    }
}
```

### 3. Design Patterns in Solidity 🏗️

Understanding and implementing design patterns is crucial for writing efficient and secure smart contracts. Here are some common patterns:

#### 3.1 Factory Pattern

The factory pattern allows for the creation of contract instances from within another contract.

```solidity
contract Token {
    string public name;
    uint256 public totalSupply;
    
    constructor(string memory _name, uint256 _totalSupply) {
        name = _name;
        totalSupply = _totalSupply;
    }
}

contract TokenFactory {
    mapping(address => address[]) public createdTokens;
    
    function createToken(string memory _name, uint256 _totalSupply) public returns (address) {
        Token newToken = new Token(_name, _totalSupply);
        createdTokens[msg.sender].push(address(newToken));
        return address(newToken);
    }
}
```

#### 3.2 Proxy Pattern

The proxy pattern enables upgradeable contracts by separating the contract logic from its storage.

```solidity
contract Proxy {
    address public implementation;
    address public admin;
    
    constructor(address _implementation) {
        implementation = _implementation;
        admin = msg.sender;
    }
    
    function upgrade(address _newImplementation) external {
        require(msg.sender == admin, "Only admin can upgrade");
        implementation = _newImplementation;
    }
    
    fallback() external payable {
        address _impl = implementation;
        assembly {
            calldatacopy(0, 0, calldatasize())
            let result := delegatecall(gas(), _impl, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch result
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }
}
```

### 4. Gas Optimization Techniques ⛽

Optimizing gas usage is crucial for efficient smart contract execution. Here are some techniques:

* Use `uint256` instead of smaller uints when possible
* Pack variables to use fewer storage slots
* Use `memory` instead of `storage` for function parameters
* Avoid unnecessary storage reads/writes
* Use events instead of storing large amounts of data

Example of variable packing:

```solidity
contract Optimized {
    // Packed: uses only one storage slot
    uint128 a;
    uint128 b;
    
    // Not packed: uses two storage slots
    uint256 c;
    uint256 d;
}
```

### 5. Security Considerations 🔒

Security is paramount in smart contract development. Here are key areas to focus on:

* Reentrancy protection
* Access control
* Integer overflow/underflow (use SafeMath for versions < 0.8.0)
* Proper use of `transfer()` vs `send()` vs `call()`
* Avoiding timestamp dependence

Example of reentrancy protection:

```solidity
contract ReentrancyGuard {
    bool private locked = false;

    modifier noReentrant() {
        require(!locked, "Reentrant call");
        locked = true;
        _;
        locked = false;
    }

    function vulnerableFunction() public noReentrant {
        // Function logic here
    }
}
```

### 6. Solidity Ecosystem Diagram 🌐

Here's a visual representation of the Solidity ecosystem and its interaction with various components:

<figure><img src="/files/6Ur2nimUk8jzNUAZ0QN3" alt=""><figcaption></figcaption></figure>

#### Tools and Frameworks

* **Solidity Compiler:** Compiles Solidity code into bytecode. &#x20;
* **Remix:** An online IDE for Solidity development. &#x20;
* **Truffle:** A development framework for Ethereum. &#x20;
* **Hardhat:** A development environment for Ethereum. &#x20;
* **OpenZeppelin Contracts:** A library of audited smart contract code. &#x20;

### 7. Smart Contract Architecture 🏗️

Designing efficient and secure smart contract architecture is crucial. Here's a diagram illustrating a typical DeFi protocol architecture:

<figure><img src="/files/DHX3I5Vae0Ik1yFU3Eib" alt=""><figcaption></figcaption></figure>

This architecture showcases the interaction between various components in a DeFi ecosystem, including smart contracts, oracles, and liquidity pools.

### Conclusion 🎓

This comprehensive guide demonstrates my deep understanding of Solidity and smart contract development. From basic syntax to advanced concepts and best practices, I've covered the essential skills needed to create secure, efficient, and innovative blockchain applications. As the blockchain landscape continues to evolve, I remain committed to staying at the forefront of Solidity development and contributing to the decentralized future. 🚀


# Deployment  Platforms

Deployment is a crucial phase in the software development lifecycle where applications are released into production environments for end-user access. It involves a series of steps to ensure that the software runs smoothly and efficiently in its intended environment.

### 🔑 Key Aspects of Deployment

#### 1. Preparation 🧪

Before deployment, thorough testing and quality assurance are essential. This includes unit testing, integration testing, and user acceptance testing.

#### 2. Environment Setup 🏗️

Ensuring the production environment is properly configured, including server setup, database configurations, and network settings.

#### 3. Version Control 🕰️

Using version control systems like Git to manage different versions of the software and facilitate rollbacks if needed.

#### 4. Deployment Strategies 🎭

* Blue-Green Deployment: Maintaining two identical production environments for seamless updates.
* Canary Releases: Gradually rolling out changes to a small subset of users before full deployment.
* Rolling Updates: Updating instances one at a time to minimize downtime.

#### 5. Automation 🤖

Implementing Continuous Integration/Continuous Deployment (CI/CD) pipelines to automate the deployment process, reducing human error and increasing efficiency.

#### 6. Monitoring and Logging 🔍

Setting up robust monitoring and logging systems to track application performance and quickly identify and resolve issues post-deployment.

### 👍 Best Practices for Deployment

* Always have a rollback plan in case of unexpected issues.
* Use configuration management tools to maintain consistency across environments.
* Implement security measures like encryption and access controls.
* Regularly update and patch systems to address vulnerabilities.
* Document the deployment process thoroughly for future reference and team knowledge sharing.

Effective deployment is critical for the success of any software project. By following best practices and leveraging modern tools and strategies, organizations can ensure smooth, reliable, and efficient software releases.

### Popular Deployment Platforms

Here are some widely used deployment platforms:

#### 1. ☁️ Amazon Web Services (AWS)

AWS offers a comprehensive suite of cloud services for deploying and scaling applications. Key services include:

* EC2 for virtual servers
* S3 for storage
* Lambda for serverless computing
* Elastic Beanstalk for easy application deployment

#### 2.⚡ Vercel

Vercel is a cloud platform for static and serverless deployment, particularly popular for front-end frameworks like Next.js, React, and Vue.js.

#### 3. 🎈 Heroku

Heroku is a platform-as-a-service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.

#### 4. 🖼️ Render

Render is a unified cloud to build and run all your apps and websites with free SSL, a global CDN, private networks, and auto-deploy from Git.

## 🌐 Domain Setup

* 🛒 **Domain Registration:** Shop for the perfect domain name.
* 🧭 **DNS Configuration:** Guide users to your app's new home.
* 🔐 **SSL/TLS Certificate:** Secure your site with HTTPS goodness.
* 🔗 **Platform-specific Setup:** Connect the dots between your domain and deployment platform.

Remember to allow time for DNS propagation after making changes. It can take up to 48 hours for changes to fully propagate, though it's often much quicker.

### Deployment Architecture Diagram

Here's a high-level diagram of a typical deployment architecture:

<figure><img src="/files/yyJXgLZIzbHmRyokCLeI" alt=""><figcaption></figcaption></figure>

This diagram illustrates the flow from code push to production deployment, including key components like CI/CD pipelines, testing, and monitoring.

### Core Concepts of Deployment

Here's a diagram highlighting the core concepts of deployment:

<figure><img src="/files/COtB8uniu599zLxTnex1" alt=""><figcaption></figcaption></figure>

This diagram outlines the key components and considerations in the deployment process, showcasing how various elements interact and contribute to successful software deployment.


# AWS

## 🌐 AWS Server Setup & Website Deployment

### 1. AWS Login 🚪

#### Account Types

* **Root User**: Main account holder, manages everything (email & password).
* **IAM User**: Limited permissions for security (can only perform specific tasks).

### 2. Log in to AWS Console 💻

* Log in to [AWS Management Console](https://aws.amazon.com/console/).
* **Region Selection**: Set to **London** (or choose your preferred region).

### 3. Launch an EC2 Instance 🚀

#### Steps:

1. **Navigate to EC2 Service**:
   * Console > **EC2** > **Instances** > **Launch Instance**.
2. **Instance Name and Tags**:
   * Provide a name for the server, e.g., "Frontend Server", "Backend Server".
3. **Application and OS Images** (Choose the OS for your server):
   * Options:
     * **Ubuntu** (Recommended) 🐧.
     * Amazon Linux.
     * macOS.

#### Example:

* Select **Ubuntu Server 22.04 LTS (HVM)**, SSD Volume Type.

### 4. Instance Details ⚙️

**AWS Architecture Overview:**

<figure><img src="/files/2qYCKit3fWCECqShBveM" alt=""><figcaption></figcaption></figure>

The architecture comprises:

* **Virtual Private Cloud (VPC)** to isolate resources.
* **EC2 Instances** to host the server.
* **S3** for object storage.
* **Security Groups** for managing inbound/outbound traffic.
* Select **64-bit (x86)** for compatibility.

#### Instance Type

* **t2.micro**: Suitable for small web apps, **Free Tier** (React Apps).
* **t2.small**: Suitable for backend services (**Paid**).

#### Key Pair (Login) 🔑

1. Click on **Create new key pair**.
2. Provide a name for the project.
3. Select **File Type: .pem** and **Download**.
   * Save it securely to access the server later.

#### Network Settings 🌐

* Allow SSH Traffic from **anywhere** (tick).
* Allow HTTPS and HTTP Traffic from the **internet** (tick).

#### Configure Storage 💾

* Allocate **30 GB** (default, gp2 SSD).

#### Advanced Details (Optional) ⚙️

* No changes required here.

#### Summary 📝

* Review all settings:
  * **Number of instances**: 1 or more based on requirements.
  * **AMI**: Ubuntu 22.04 LTS.
  * **Instance Type**: t2.micro or t2.small.

### 5. Create and Connect to EC2 Instance 🔌

#### Create the EC2 Instance 🖥️

* Click **Launch**.

#### Connect to the Instance 📡

1. **Create IAM Role**: Attach `AmazonSSMFullAccess` for secure access.
2. Enable **Fleet Manager** host.

#### Connect Using SSH 🔐

```sh
chmod 400 project-key.pem
ssh -i "project-key.pem" ubuntu@<public-ip-address>
```

### 6. Install Dependencies for Web Application ⚙️

#### Become Super User

```sh
sudo su
```

#### Install Node.js & NPM 🌐

1. Follow the guide [here](https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-20-04).
2. Use the first option command.
3. After installing Node.js:

```sh
npm install -g n
n lts
```

* If you encounter errors, refer to the [Node.js Package Manager Guide](https://nodejs.org/en/download/package-manager#n).

#### Install MongoDB 💾

Follow [this tutorial](https://www.digitalocean.com/community/tutorials/how-to-install-mongodb-on-ubuntu-18-04-source).

If there are issues:

1. Download `libssl1.1`:

```sh
wget http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb
sudo dpkg -i libssl1.1_1.1.1f-1ubuntu2_amd64.deb
sudo apt-get install -y mongodb-org
```

#### Install Nginx 🌐

1. Follow [this tutorial](https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-20-04).
   * Use `"Nginx Full"` for firewall settings:

```sh
shCopy codesudo ufw allow 'Nginx FULL'
sudo ufw enable
sudo ufw status
sudo ufw reload
```

#### Install PM2 🔄

```sh
sudo npm install pm2 -g
```

### 7. Upload Application Code 📁

#### Upload Frontend & Backend Code

```sh
cd /var/www/html/
```

#### Install NVM (Node Version Manager) 🌐

```sh
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
source ~/.bashrc
nvm install --lts
npm install -g npm
npm install
```

#### Site Configuration for Nginx ⚙️

**Unlink Default Config File**

```sh
cd /etc/nginx/sites-available/
sudo unlink /etc/nginx/sites-available/default
```

**Create New Config File for Frontend & Backend 🖊️**

1. **Frontend Configuration Example**:

```nginx
server {
    root /var/www/html/frontend-build/;
    index index.html;
    server_name yourdomain.com;
    location / {
        try_files $uri /index.html;
    }
}
```

2. **Backend Configuration Example**:

```nginx
server {
    listen 80;
    server_name backend.yourdomain.com;
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
```

**Enable Configuration**

```sh
sudo ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled
```

**Test and Restart Nginx ⚙️**

```sh
sudo nginx -t
sudo systemctl restart nginx
```

### 8. Set Up SSL 🔒

1. **Install Certbot**:

```sh
shCopy codesudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt install certbot python3-certbot-nginx
```

2. **Generate SSL Certificate**:

```sh
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
```

3. **Renew Certificate**:

```sh
sudo certbot renew --dry-run
```

### 9. Additional Configurations 🛠️

#### Start Services

```sh
sudo systemctl start nginx
sudo systemctl start mongod
```

#### Check Service Status

```sh
sudo systemctl status nginx
sudo systemctl status mongod
```

#### Add IAM Role for SSM 📊

* Assign **SSM Administrator** access to connect easily via AWS Systems Manager.

### 10. DNS Setup 🌍

#### A Records and CNAME

* **Main Website**: Use **A Record** pointing to instance IP.
* **Subdomain** (same instance IP): Use **CNAME Record**.
* **Different IP**: Use **A Record**.

### 11. Extra Commands & Tips 💡

* List PM2 processes:

```sh
pm2 list
```

* Check Certbot Certificates:

```sh
certbot certificates
```

* If stopping and restarting the instance, update **DNS** with the new IP address.

#### **Conclusion** 🎉

AWS provides powerful and flexible tools to build scalable and secure infrastructure for your website. With these steps, you're on your way to mastering AWS deployments!


# Vercel

Deploying both frontend and backend to Vercel involves deploying the projects separately as they are usually distinct applications with different requirements.

### 1. Setting Up Vercel

* **Sign Up/Login to Vercel:**
  * Visit <https://vercel.com> and sign up using your GitHub, GitLab, or Bitbucket account.
* **Create a New Project:**
  * After logging in, click on the "Add New\..." button and select "Project" to start a new deployment.

### 2. Preparing Your Frontend and Backend Projects

Make sure your projects are set up correctly:

* **Frontend (e.g., React, Next.js) Project:**
  * Should have a `package.json` file with a build script (`"build": "next build"` for Next.js).
  * Make sure your frontend is ready for production (environment variables, API URLs, etc.).
* **Backend (e.g., Node.js/Express) Project:**
  * Should also have a `package.json` file with a start script (`"start": "node index.js"`).
  * Add a Vercel configuration (`vercel.json`) to specify the serverless functions.

### 3. Deploying the Frontend on Vercel

**Step-by-Step Deployment:**

1. **Connect to Git Repository:**
   * Connect your frontend repository to Vercel.
   * Select your Git provider (GitHub, GitLab, Bitbucket) and pick the repository for the frontend.
2. **Configure Project Settings:**
   * Set the **framework preset** to your frontend framework (e.g., Next.js).
   * Configure the **Environment Variables** if needed, such as API URLs.
3. **Deploy Frontend:**
   * Click "Deploy" and wait for Vercel to build and deploy the frontend.
   * Once deployed, Vercel will provide you with a URL (e.g., `your-project.vercel.app`).

### 4.  Deploy Backend on Vercel 🌐

Vercel treats backend projects as serverless functions.

**Step-by-Step Deployment:**

1. **Connect to Git Repository:**
   * Connect your backend repository to Vercel.
   * Select your Git provider and pick the repository for the backend.
2. **Add `vercel.json` Configuration:**
   * Create a `vercel.json` file in the root of your backend project to specify the serverless functions configuration:

     ```json
     {
       "version": 2,
       "builds": [
         { "src": "api/**/*.js", "use": "@vercel/node" }
       ],
       "routes": [
         { "src": "/api/(.*)", "dest": "/api/$1" }
       ]
     }
     ```
   * Place your backend code in the `/api` directory (e.g., `/api/index.js`). Vercel will treat these files as serverless functions.
3. **Configure Environment Variables:**
   * Set environment variables like database URLs, API keys, etc., in the **Environment Variables** section.
4. **Deploy Backend:**
   * Click "Deploy" and wait for Vercel to build and deploy the backend.
   * Once deployed, Vercel will provide a URL for your backend endpoints (e.g., `your-backend.vercel.app/api`).

### 5. Setting Up Environment Variables

* **Frontend Environment Variables:**
  * In Vercel, go to your frontend project settings.
  * Under "Environment Variables", add variables like `NEXT_PUBLIC_API_URL` to point to the backend deployment URL.
* **Backend Environment Variables:**
  * In Vercel, go to your backend project settings.
  * Add variables for database connection strings, secret keys, etc.

### 6. Setting Up a Custom Domain in Vercel🌍

You can set up a custom domain to make your frontend and backend accessible through your own domain name.

**Step-by-Step Process:**

1. **Add Domain to Vercel:**
   * In the Vercel dashboard, go to your frontend or backend project.
   * Click on "Settings" and then "Domains".
   * Click on "Add Domain" and enter your custom domain (e.g., `www.example.com`).
2. **Verify Domain Ownership:**

   * Vercel will provide you with DNS records that you need to add to your domain registrar.
   * Typically, you need to add an `A` record or `CNAME` record pointing to Vercel's servers.

   **For Main Website:**

   * Add an `A` record pointing to the IP address given by Vercel.

   **For Subdomain:**

   * Create a `CNAME` record pointing to your Vercel project URL (e.g., `your-project.vercel.app`).
3. **Wait for Propagation:**
   * DNS changes can take some time (up to 24-48 hours) to propagate, though it's usually much faster.
4. **Configure HTTPS:**
   * Vercel automatically provides an SSL certificate for your domain. You don’t need to configure SSL manually.
   * Once the domain is verified, Vercel will enable HTTPS by default.

### 7. Connecting Frontend to Backend

* Update the API URLs in your frontend code to point to the backend endpoint deployed on Vercel.
  * For example, set `NEXT_PUBLIC_API_URL=https://your-backend.vercel.app/api` in your environment variables.

#### Example Command Summary 📝

* **Install Vercel CLI (Optional but Recommended for Local Testing):**

  ```sh
  shCopy codenpm install -g vercel
  ```
* **Deploy Frontend Locally:**

  ```sh
  shCopy codevercel --prod
  ```
* **Deploy Backend Locally:**

  ```sh
  shCopy codecd backend
  vercel --prod
  ```

### 8. Summary 🚀

* **Frontend Deployment:**
  * Connect to Vercel -> Configure -> Deploy -> Get URL.
* **Backend Deployment:**
  * Connect to Vercel -> Add `vercel.json` -> Configure -> Deploy -> Get URL.
* **Domain Setup:**
  * Add domain -> Verify with DNS -> Wait for propagation -> HTTPS enabled by Vercel.

This setup ensures that your frontend and backend are deployed separately on Vercel but can work together seamlessly through the use of environment variables and domain configuration.


# Heroku, Render


# Domain setup


# SDKs


# Google Cloud SDK

## ☁️ Advanced Guide to Google Cloud SDK, AWS SDK, and Firebase SDK for Cloud Development

This comprehensive guide is designed for developers building a professional portfolio on **GitBook**. It covers the **Google Cloud SDK**, **AWS SDK**, and **Firebase SDK**, detailing their purposes, advanced use cases, integration with **JavaScript** and **Next.js**, key management, and practical examples. Whether you’re building a startup MVP, an enterprise-grade application, or automating DevOps pipelines, this guide will help you choose the right SDK and implement it effectively.

***

### 1. **Google Cloud SDK**

#### 📌 What is the Google Cloud SDK?

The **Google Cloud SDK** is a powerful suite of command-line tools and libraries for managing **Google Cloud Platform (GCP)** services, including **Compute Engine**, **Cloud Storage**, **BigQuery**, **Cloud Functions**, **Kubernetes Engine (GKE)**, and more. The primary tool, `gcloud`, simplifies resource management, while client libraries (e.g., `@google-cloud/*`) enable programmatic access in languages like JavaScript.

#### ✅ Why Use It?

* **Unified Management**: Control all GCP services via a single CLI or API.
* **Automation**: Script infrastructure provisioning and deployments for CI/CD pipelines.
* **Scalability**: Supports enterprise-grade applications with global infrastructure.
* **Specialized Services**: Access advanced tools like **Vertex AI** for machine learning and **BigQuery** for analytics.

#### 📅 When to Use It?

* **Infrastructure Management**: Deploying VMs, Kubernetes clusters, or serverless functions.
* **Data Analytics**: Processing large datasets with BigQuery or Dataflow.
* **Machine Learning**: Training and deploying models with Vertex AI.
* **DevOps Automation**: Integrating with Cloud Build for CI/CD.

#### ⚙️ Project Types and Use Cases

| **Project Type**             | **Why Use Google Cloud SDK?**                                                   | **Example Services**                  |
| ---------------------------- | ------------------------------------------------------------------------------- | ------------------------------------- |
| **Enterprise Applications**  | Scalable infrastructure for high-traffic apps with global load balancing.       | Compute Engine, Cloud Run, GKE        |
| **Data Analytics Platforms** | Process and analyze petabytes of data with low latency.                         | BigQuery, Dataflow, Dataproc          |
| **ML/AI Solutions**          | Build and deploy custom ML models or use pre-trained APIs (e.g., Vision AI).    | Vertex AI, AutoML                     |
| **Serverless Microservices** | Run event-driven functions or lightweight containers without server management. | Cloud Functions, Cloud Run            |
| **CI/CD Pipelines**          | Automate deployments and infrastructure as code (IaC).                          | Cloud Build, Cloud Deployment Manager |

#### 🛠️ How to Use It?

**Installation**

1. **MacOS/Linux**:

   ```bash
   curl https://sdk.cloud.google.com | bash
   exec -l $SHELL
   gcloud init
   ```

   * `gcloud init` guides you through authentication and project selection.
2. **Windows**:
   * Download the installer from the [Google Cloud SDK Installation Page](https://cloud.google.com/sdk/docs/install).
   * Run the installer and follow the prompts to authenticate.
3. **Verify Installation**:

   ```bash
   gcloud --version
   ```

**Key Management**

* **Service Account Key**:
  1. In the [Google Cloud Console](https://console.cloud.google.com/iam-admin/serviceaccounts), create a service account:
     * Navigate to **IAM & Admin** > **Service Accounts** > **Create Service Account**.
     * Assign roles (e.g., `Storage Admin` for Cloud Storage).
     * Generate and download a JSON key file.
  2. Set the environment variable:

     ```bash
     export GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"
     ```
  3. For Next.js, store the key securely and reference it in `.env.local`:

     ```
     GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json
     ```
* **Security Best Practices**:
  * Use least-privilege roles for service accounts.
  * Store keys in a secure vault (e.g., Google Secret Manager).
  * Rotate keys periodically via the Cloud Console.

**JavaScript/Node.js Integration**

Use the `@google-cloud` libraries for specific services. Example: Interacting with **Cloud Storage**.

1. **Install the Library**:

   ```bash
   npm install @google-cloud/storage
   ```
2. **Example: Upload and List Files**:

   ```javascript
   const { Storage } = require('@google-cloud/storage');
   const storage = new Storage({ keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS });
   const bucketName = 'your-bucket-name';

   // Upload a file
   async function uploadFile(filePath, destination) {
     await storage.bucket(bucketName).upload(filePath, { destination });
     console.log(`${filePath} uploaded to ${bucketName}/${destination}`);
   }

   // List files
   async function listFiles() {
     const [files] = await storage.bucket(bucketName).getFiles();
     files.forEach(file => console.log(file.name));
   }

   uploadFile('local-file.txt', 'remote-file.txt').catch(console.error);
   listFiles().catch(console.error);
   ```

**Next.js Integration**

Incorporate Google Cloud services in Next.js API routes or server-side logic.

1. **API Route Example** (`pages/api/storage.js`):

   ```javascript
   import { Storage } from '@google-cloud/storage';

   const storage = new Storage({ keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS });
   const bucketName = 'your-bucket-name';

   export default async function handler(req, res) {
     if (req.method === 'POST') {
       try {
         await storage.bucket(bucketName).upload(req.body.filePath, {
           destination: req.body.fileName,
         });
         res.status(200).json({ message: 'File uploaded successfully' });
       } catch (error) {
         res.status(500).json({ error: error.message });
       }
     } else {
       res.status(405).json({ error: 'Method not allowed' });
     }
   }
   ```
2. **Environment Variables**:
   * In `.env.local`:

     ```
     GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json
     ```
3. **Serverless Deployment**:
   * Deploy Next.js apps to **Cloud Run**:

     ```bash
     gcloud run deploy my-app \
       --source . \
       --platform managed \
       --region us-central1 \
       --allow-unauthenticated
     ```

**Useful Commands**

* List projects: `gcloud projects list`
* Deploy a Cloud Function: `gcloud functions deploy myFunction --runtime nodejs20 --trigger-http`
* Manage storage: `gsutil cp local-file gs://your-bucket/`
* View logs: `gcloud functions logs read myFunction`

#### 📈 Usefulness in Projects

* **Scalability**: Handles millions of users with GCP’s global infrastructure.
* **Cost Management**: Integrates with GCP Billing for cost tracking.
* **Advanced Analytics**: BigQuery enables real-time data insights.
* **AI Capabilities**: Vertex AI simplifies ML model deployment.

#### 🔗 Links

* [Official Documentation](https://cloud.google.com/sdk/docs)
* [Client Libraries](https://cloud.google.com/apis/docs/client-libraries)
* [Google Cloud Console](https://console.cloud.google.com/)
* [Cloud Storage Tutorial](https://cloud.google.com/storage/docs)

***

### 2. **AWS SDK**

#### 📌 What is the AWS SDK?

The **AWS SDK** provides libraries to interact with **Amazon Web Services (AWS)** services, such as **S3**, **EC2**, **Lambda**, **DynamoDB**, **SNS**, and more. The JavaScript SDK (`aws-sdk` or `@aws-sdk/*`) supports both Node.js and browser environments, with modular packages for modern applications.

#### ✅ Why Use It?

* **Comprehensive Service Access**: Supports over 200 AWS services.
* **Serverless Architecture**: Ideal for Lambda and API Gateway.
* **Flexibility**: Works in server-side and client-side contexts.
* **Ecosystem**: Extensive community support and integrations.

#### 📅 When to Use It?

* **Serverless Applications**: Running code with AWS Lambda.
* **Cloud Storage**: Storing and serving files via S3.
* **Database Operations**: Managing NoSQL (DynamoDB) or relational (RDS) databases.
* **IoT or AI**: Building IoT solutions or using SageMaker for ML.

#### ⚙️ Project Types and Use Cases

| **Project Type**         | **Why Use AWS SDK?**                                               | **Example Services**    |
| ------------------------ | ------------------------------------------------------------------ | ----------------------- |
| **SaaS Applications**    | Scalable APIs and storage for multi-tenant platforms.              | API Gateway, Lambda, S3 |
| **E-commerce Platforms** | Manage inventory, user data, and payments with high availability.  | DynamoDB, SQS, SNS      |
| **IoT Solutions**        | Process real-time sensor data with low latency.                    | AWS IoT Core, Kinesis   |
| **Static Web Hosting**   | Host static sites with global CDN distribution.                    | S3, CloudFront          |
| **Machine Learning**     | Deploy ML models or use pre-built AI services (e.g., Rekognition). | SageMaker, Comprehend   |

#### 🛠️ How to Use It?

**Installation**

1. **Legacy SDK**:

   ```bash
   npm install aws-sdk
   ```
2. **Modular SDK** (recommended for modern apps):

   ```bash
   npm install @aws-sdk/client-s3
   ```

**Key Management**

* **IAM Credentials**:
  1. In the [AWS Management Console](https://aws.amazon.com/console/), create an IAM user:
     * Navigate to **IAM** > **Users** > **Add User**.
     * Assign permissions (e.g., `AmazonS3FullAccess`).
     * Generate an access key and secret key.
  2. Configure credentials:

     ```bash
     aws configure
     ```

     * Enter the access key, secret key, region (e.g., `us-east-1`), and output format (e.g., `json`).
  3. Alternatively, use environment variables:

     ```bash
     export AWS_ACCESS_KEY_ID='YOUR_ACCESS_KEY'
     export AWS_SECRET_ACCESS_KEY='YOUR_SECRET_KEY'
     export AWS_REGION='us-east-1'
     ```
* **Security Best Practices**:
  * Use IAM roles for EC2 or Lambda instead of hardcoding keys.
  * Rotate access keys regularly via the IAM Console.
  * Store keys in AWS Secrets Manager or Parameter Store.

**JavaScript/Node.js Integration**

Example: Uploading a file to **S3** using the modular SDK.

1. **Install the S3 Client**:

   ```bash
   npm install @aws-sdk/client-s3
   ```
2. **Example Code**:

   ```javascript
   import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

   const s3Client = new S3Client({
     region: 'us-east-1',
     credentials: {
       accessKeyId: process.env.AWS_ACCESS_KEY_ID,
       secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
     },
   });

   async function uploadFile(fileContent, fileName) {
     const params = {
       Bucket: 'your-bucket-name',
       Key: fileName,
       Body: fileContent,
     };

     try {
       await s3Client.send(new PutObjectCommand(params));
       console.log(`File uploaded to ${fileName}`);
     } catch (error) {
       console.error('Error:', error);
     }
   }

   uploadFile('Hello, AWS!', 'example.txt');
   ```

**Next.js Integration**

Use AWS SDK in API routes or server-side functions.

1. **API Route Example** (`pages/api/s3-upload.js`):

   ```javascript
   import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

   const s3Client = new S3Client({
     region: 'us-east-1',
     credentials: {
       accessKeyId: process.env.AWS_ACCESS_KEY_ID,
       secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
     },
   });

   export default async function handler(req, res) {
     if (req.method === 'POST') {
       const params = {
         Bucket: 'your-bucket-name',
         Key: req.body.fileName,
         Body: req.body.content,
       };

       try {
         await s3Client.send(new PutObjectCommand(params));
         res.status(200).json({ message: 'File uploaded successfully' });
       } catch (error) {
         res.status(500).json({ error: error.message });
       }
     } else {
       res.status(405).json({ error: 'Method not allowed' });
     }
   }
   ```
2. **Environment Variables**:
   * In `.env.local`:

     ```
     AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY
     AWS_SECRET_ACCESS_KEY=YOUR_SECRET_KEY
     AWS_REGION=us-east-1
     ```
3. **Serverless Deployment**:
   * Deploy Next.js to **AWS Amplify** or **Lambda**:

     ```bash
     amplify init
     amplify push
     ```

**Useful Commands**

* Configure AWS CLI: `aws configure`
* Upload to S3: `aws s3 cp local-file s3://your-bucket/`
* Deploy Lambda: `aws lambda create-function --function-name myFunction --runtime nodejs20.x --handler index.handler --zip-file fileb://function.zip`
* List S3 buckets: `aws s3 ls`

#### 📈 Usefulness in Projects

* **Cost-Effective**: Pay-as-you-go pricing for serverless and storage.
* **Global Reach**: AWS’s extensive region availability ensures low latency.
* **Flexibility**: Modular SDK reduces bundle size for modern apps.
* **Enterprise Ready**: Supports complex architectures with VPCs and multi-region setups.

#### 🔗 Links

* [AWS SDK for JavaScript](https://aws.amazon.com/developer/language/javascript/)
* [Modular AWS SDK](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html)
* [AWS CLI Documentation](https://aws.amazon.com/cli/)
* [AWS Management Console](https://aws.amazon.com/console/)
* [S3 Getting Started](https://docs.aws.amazon.com/AmazonS3/latest/userguide/GetStartedWithS3.html)

***

### 3. **Firebase SDK**

#### 📌 What is the Firebase SDK?

The **Firebase SDK** is a JavaScript library for building web, mobile, and server applications using **Firebase** services, including **Firestore**, **Realtime Database**, **Authentication**, **Cloud Storage**, **Cloud Functions**, and **Hosting**. It’s optimized for real-time, serverless, and rapid development.

#### ✅ Why Use It?

* **Real-Time Sync**: Firestore and Realtime Database enable instant data updates.
* **Authentication**: Supports Google, Email, OAuth, and anonymous logins.
* **Serverless Backend**: Cloud Functions for event-driven logic.
* **Rapid Prototyping**: Simplifies backend setup for MVPs.

#### 📅 When to Use It?

* **Real-Time Applications**: Chat apps, live dashboards, or collaborative tools.
* **User Authentication**: Secure login systems with minimal setup.
* **Static Hosting**: Deploying single-page apps (SPAs) or static sites.
* **Mobile/Web Prototypes**: Building MVPs with minimal backend configuration.

#### ⚙️ Project Types and Use Cases

| **Project Type**        | **Why Use Firebase SDK?**                                | **Example Services**                       |
| ----------------------- | -------------------------------------------------------- | ------------------------------------------ |
| **Social Media Apps**   | Real-time feeds, notifications, and user authentication. | Firestore, Authentication, Cloud Functions |
| **Collaborative Tools** | Real-time document editing or live collaboration.        | Realtime Database, Firestore               |
| **E-commerce MVPs**     | Quick setup for product catalogs and user accounts.      | Firestore, Authentication, Hosting         |
| **Gaming Leaderboards** | Real-time updates for scores and player data.            | Realtime Database, Cloud Functions         |
| **Static Web Apps**     | Host SPAs or marketing sites with global CDN.            | Firebase Hosting                           |

#### 🛠️ How to Use It?

**Installation**

1. **Create a Firebase Project**:
   * Visit the [Firebase Console](https://console.firebase.google.com/).
   * Click **Add Project** and follow the setup.
2. **Install Firebase SDK**:

   ```bash
   npm install firebase
   ```
3. **Install Firebase CLI** (for deployments):

   ```bash
   npm install -g firebase-tools
   firebase login
   firebase init
   ```

**Key Management**

* **API Key**:
  1. In the Firebase Console, go to **Project Settings** > **General** > **Web App**.
  2. Register a web app to get the `firebaseConfig` object, including the API key.
  3. Example `firebaseConfig`:

     ```javascript
     const firebaseConfig = {
       apiKey: "YOUR_API_KEY",
       authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
       projectId: "YOUR_PROJECT_ID",
       storageBucket: "YOUR_BUCKET.appspot.com",
       messagingSenderId: "YOUR_SENDER_ID",
       appId: "YOUR_APP_ID",
     };
     ```
  4. Restrict the API key in the [Google Cloud Console](https://console.cloud.google.com/apis/credentials):
     * Navigate to **APIs & Services** > **Credentials**.
     * Set API restrictions to specific Firebase services.
* **Security Rules**:
  * Protect Firestore/Realtime Database with rules:

    ```javascript
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if request.auth != null;
        }
      }
    }
    ```
  * Deploy rules:

    ```bash
    firebase deploy --only firestore:rules
    ```
* **Security Best Practices**:
  * Use Firebase Authentication to secure data access.
  * Avoid exposing sensitive keys in client-side code.
  * Regularly audit Security Rules in the Firebase Console.

**JavaScript/Node.js Integration**

Example: Managing users in **Firestore** with Authentication.

1. **Initialize Firebase**:

   ```javascript
   // firebase.js
   import { initializeApp } from 'firebase/app';
   import { getFirestore } from 'firebase/firestore';
   import { getAuth } from 'firebase/auth';

   const firebaseConfig = {
     apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
     authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
     projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
     storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
     messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
     appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
   };

   const app = initializeApp(firebaseConfig);
   export const db = getFirestore(app);
   export const auth = getAuth(app);
   ```
2. **Example: Add User Data**:

   ```javascript
   import { collection, addDoc } from 'firebase/firestore';
   import { signInWithEmailAndPassword } from 'firebase/auth';
   import { db, auth } from './firebase';

   async function signInAndAddUser(email, password, userData) {
     try {
       await signInWithEmailAndPassword(auth, email, password);
       await addDoc(collection(db, 'users'), {
         name: userData.name,
         age: userData.age,
         createdAt: new Date(),
       });
       console.log('User added successfully');
     } catch (error) {
       console.error('Error:', error);
     }
   }

   signInAndAddUser('user@example.com', 'password123', { name: 'Alice', age: 30 });
   ```

**Next.js Integration**

Firebase works seamlessly with Next.js for both client-side and server-side operations.

1. **Client-Side Example** (React Component):

   ```javascript
   // pages/index.js
   import { useEffect, useState } from 'react';
   import { collection, getDocs } from 'firebase/firestore';
   import { db } from '../firebase';

   export default function Home() {
     const [users, setUsers] = useState([]);

     useEffect(() => {
       async function fetchUsers() {
         const querySnapshot = await getDocs(collection(db, 'users'));
         setUsers(querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));
       }
       fetchUsers();
     }, []);

     return (
       <div>
         <h1>Users</h1>
         <ul>
           {users.map(user => (
             <li key={user.id}>{user.name} - {user.age}</li>
           ))}
         </ul>
       </div>
     );
   }
   ```
2. **Server-Side Example** (API Route, `pages/api/users.js`):

   ```javascript
   import { collection, getDocs } from 'firebase/firestore';
   import { db } from '../../firebase';

   export default async function handler(req, res) {
     try {
       const querySnapshot = await getDocs(collection(db, 'users'));
       const users = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
       res.status(200).json(users);
     } catch (error) {
       res.status(500).json({ error: error.message });
     }
   }
   ```
3. **Environment Variables**:
   * In `.env.local`:

     ```
     NEXT_PUBLIC_FIREBASE_API_KEY=YOUR_API_KEY
     NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=YOUR_PROJECT_ID.firebaseapp.com
     NEXT_PUBLIC_FIREBASE_PROJECT_ID=YOUR_PROJECT_ID
     NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=YOUR_BUCKET.appspot.com
     NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=YOUR_SENDER_ID
     NEXT_PUBLIC_FIREBASE_APP_ID=YOUR_APP_ID
     ```
4. **Hosting with Firebase**:
   * Initialize hosting:

     ```bash
     firebase init hosting
     ```
   * Deploy Next.js app:

     ```bash
     npm run build
     firebase deploy --only hosting
     ```

**Useful Commands**

* Initialize project: `firebase init`
* Deploy hosting: `firebase deploy --only hosting`
* Deploy functions: `firebase deploy --only functions`
* Start emulator: `firebase emulators:start`

#### 📈 Usefulness in Projects

* **Rapid Development**: Simplifies backend setup for MVPs and startups.
* **Real-Time Features**: Ideal for chat, gaming, or collaborative apps.
* **Cost-Effective**: Generous free tier for small projects.
* **Scalability**: Firestore scales automatically for growing apps.

#### 🔗 Links

* [Firebase Documentation](https://firebase.google.com/docs)
* [Add Firebase to JavaScript](https://firebase.google.com/docs/web/setup)
* [Firebase CLI Reference](https://firebase.google.com/docs/cli)
* [Firebase Console](https://console.firebase.google.com/)
* [Firestore Security Rules](https://firebase.google.com/docs/firestore/security/get-started)

***

### ⚖️ SDK Comparison and Selection Guide

| **Feature/Use Case**       | **Google Cloud SDK**                     | **AWS SDK**                                  | **Firebase SDK**                       |
| -------------------------- | ---------------------------------------- | -------------------------------------------- | -------------------------------------- |
| **Best For**               | Enterprise infrastructure, ML, analytics | Serverless, SaaS, IoT, complex architectures | Real-time apps, MVPs, frontend-focused |
| **Ideal Project Types**    | Data platforms, ML models, microservices | APIs, e-commerce, IoT, static hosting        | Chat apps, social media, prototypes    |
| **Database**               | BigQuery, Cloud Datastore                | DynamoDB, RDS, Aurora                        | Firestore, Realtime Database           |
| **Hosting**                | App Engine, Cloud Run, GKE               | S3, Amplify, Lambda                          | Firebase Hosting                       |
| **CLI Tool**               | `gcloud`, `gsutil`                       | `aws` CLI                                    | `firebase` CLI                         |
| **JavaScript Integration** | `@google-cloud/*`                        | `aws-sdk`, `@aws-sdk/*`                      | `firebase`                             |
| **Authentication**         | IAM, OAuth                               | IAM, Cognito                                 | Firebase Authentication                |
| **Real-Time Support**      | Limited (Pub/Sub)                        | Limited (Kinesis)                            | Strong (Firestore, Realtime Database)  |
| **Learning Curve**         | Moderate to High                         | Moderate                                     | Low to Moderate                        |

#### 📋 Choosing the Right SDK

* **Google Cloud SDK**:
  * **When**: You need advanced infrastructure, ML, or big data analytics.
  * **Why**: Offers robust tools for enterprise-grade apps and AI.
  * **Example**: A fintech platform analyzing transaction data with BigQuery.
* **AWS SDK**:
  * **When**: You’re building serverless APIs, IoT solutions, or complex architectures.
  * **Why**: Provides granular control and a vast service ecosystem.
  * **Example**: An e-commerce backend with DynamoDB and Lambda.
* **Firebase SDK**:
  * **When**: You need rapid development, real-time features, or simple authentication.
  * **Why**: Simplifies backend setup for web/mobile apps.
  * **Example**: A real-time chat app with Firestore and Authentication.

***

### 🔐 Security Best Practices

* **Google Cloud SDK**:
  * Use IAM roles with minimal permissions.
  * Store service account keys in a secure vault.
  * Enable VPC Service Controls for sensitive data.
* **AWS SDK**:
  * Prefer IAM roles over access keys for EC2/Lambda.
  * Use AWS Secrets Manager for key storage.
  * Enable MFA for IAM users.
* **Firebase SDK**:
  * Implement strict Firestore/Realtime Database Security Rules.
  * Restrict API key usage in Google Cloud Console.
  * Use Firebase Authentication for data access control.

***

### 📁 Advanced Project Examples

#### 1. **Real-Time Analytics Dashboard (Firebase SDK)**

* **Use Case**: A dashboard displaying live user activity for a SaaS app.
* **Implementation**:
  * Store events in Firestore.
  * Use Firebase Authentication for user access.
  * Deploy with Firebase Hosting.
* **Code Snippet** (Add event):

  ```javascript
  import { collection, addDoc, serverTimestamp } from 'firebase/firestore';
  import { db } from './firebase';

  async function logEvent(userId, action) {
    await addDoc(collection(db, 'events'), {
      userId,
      action,
      timestamp: serverTimestamp(),
    });
  }
  ```

#### 2. **Serverless API for E-commerce (AWS SDK)**

* **Use Case**: An API for product listings and orders.
* **Implementation**:
  * Store products in DynamoDB.
  * Use Lambda and API Gateway for endpoints.
  * Serve images from S3.
* **Code Snippet** (Get products):

  ```javascript
  import { DynamoDBClient, ScanCommand } from '@aws-sdk/client-dynamodb';

  const client = new DynamoDBClient({ region: 'us-east-1' });

  async function getProducts() {
    const command = new ScanCommand({ TableName: 'Products' });
    const response = await client.send(command);
    return response.Items;
  }
  ```

#### 3. **ML-Powered Recommendation System (Google Cloud SDK)**

* **Use Case**: Recommend products based on user behavior.
* **Implementation**:
  * Store data in BigQuery.
  * Train models with Vertex AI.
  * Serve predictions via Cloud Functions.
* **Code Snippet** (Query BigQuery):

  ```javascript
  const { BigQuery } = require('@google-cloud/bigquery');
  const bigquery = new BigQuery();

  async function queryUserBehavior() {
    const query = 'SELECT user_id, product_id FROM `project.dataset.user_behavior` LIMIT 10';
    const [rows] = await bigquery.query({ query });
    return rows;
  }
  ```

***

### 🚀 Final Thoughts

The **Google Cloud SDK**, **AWS SDK**, and **Firebase SDK** are indispensable tools for modern cloud development. By mastering their use cases, integration patterns, and security practices, you can build scalable, secure, and efficient applications. This guide equips you with the knowledge to showcase these skills in your **GitBook portfolio**, demonstrating expertise in cloud-based development.

For further customization, such as generating a `.md` file, adding specific project demos, or integrating with GitBook’s styling, let me know!

***

### ✅ Quick Command Reference

| **SDK**          | **CLI Init**    | **Deploy Example**               | **Install in JS**         |
| ---------------- | --------------- | -------------------------------- | ------------------------- |
| **Google Cloud** | `gcloud init`   | `gcloud run deploy`              | `npm i @google-cloud/*`   |
| **AWS**          | `aws configure` | `aws lambda create-function`     | `npm i @aws-sdk/client-*` |
| **Firebase**     | `firebase init` | `firebase deploy --only hosting` | `npm i firebase`          |


# AWS SDK

#### 📌 What is the AWS SDK?

The **AWS SDK** provides libraries to interact with **Amazon Web Services (AWS)** services, such as **S3**, **EC2**, **Lambda**, **DynamoDB**, **SNS**, and more. The JavaScript SDK (`aws-sdk` or `@aws-sdk/*`) supports both Node.js and browser environments, with modular packages for modern applications.

#### ✅ Why Use It?

* **Comprehensive Service Access**: Supports over 200 AWS services.
* **Serverless Architecture**: Ideal for Lambda and API Gateway.
* **Flexibility**: Works in server-side and client-side contexts.
* **Ecosystem**: Extensive community support and integrations.

#### 📅 When to Use It?

* **Serverless Applications**: Running code with AWS Lambda.
* **Cloud Storage**: Storing and serving files via S3.
* **Database Operations**: Managing NoSQL (DynamoDB) or relational (RDS) databases.
* **IoT or AI**: Building IoT solutions or using SageMaker for ML.

#### ⚙️ Project Types and Use Cases

| **Project Type**         | **Why Use AWS SDK?**                                               | **Example Services**    |
| ------------------------ | ------------------------------------------------------------------ | ----------------------- |
| **SaaS Applications**    | Scalable APIs and storage for multi-tenant platforms.              | API Gateway, Lambda, S3 |
| **E-commerce Platforms** | Manage inventory, user data, and payments with high availability.  | DynamoDB, SQS, SNS      |
| **IoT Solutions**        | Process real-time sensor data with low latency.                    | AWS IoT Core, Kinesis   |
| **Static Web Hosting**   | Host static sites with global CDN distribution.                    | S3, CloudFront          |
| **Machine Learning**     | Deploy ML models or use pre-built AI services (e.g., Rekognition). | SageMaker, Comprehend   |

#### 🛠️ How to Use It?

**Installation**

1. **Legacy SDK**:

   ```bash
   npm install aws-sdk
   ```
2. **Modular SDK** (recommended for modern apps):

   ```bash
   npm install @aws-sdk/client-s3
   ```

**Key Management**

* **IAM Credentials**:
  1. In the [AWS Management Console](https://aws.amazon.com/console/), create an IAM user:
     * Navigate to **IAM** > **Users** > **Add User**.
     * Assign permissions (e.g., `AmazonS3FullAccess`).
     * Generate an access key and secret key.
  2. Configure credentials:

     ```bash
     aws configure
     ```

     * Enter the access key, secret key, region (e.g., `us-east-1`), and output format (e.g., `json`).
  3. Alternatively, use environment variables:

     ```bash
     export AWS_ACCESS_KEY_ID='YOUR_ACCESS_KEY'
     export AWS_SECRET_ACCESS_KEY='YOUR_SECRET_KEY'
     export AWS_REGION='us-east-1'
     ```
* **Security Best Practices**:
  * Use IAM roles for EC2 or Lambda instead of hardcoding keys.
  * Rotate access keys regularly via the IAM Console.
  * Store keys in AWS Secrets Manager or Parameter Store.

**JavaScript/Node.js Integration**

Example: Uploading a file to **S3** using the modular SDK.

1. **Install the S3 Client**:

   ```bash
   npm install @aws-sdk/client-s3
   ```
2. **Example Code**:

   ```javascript
   import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

   const s3Client = new S3Client({
     region: 'us-east-1',
     credentials: {
       accessKeyId: process.env.AWS_ACCESS_KEY_ID,
       secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
     },
   });

   async function uploadFile(fileContent, fileName) {
     const params = {
       Bucket: 'your-bucket-name',
       Key: fileName,
       Body: fileContent,
     };

     try {
       await s3Client.send(new PutObjectCommand(params));
       console.log(`File uploaded to ${fileName}`);
     } catch (error) {
       console.error('Error:', error);
     }
   }

   uploadFile('Hello, AWS!', 'example.txt');
   ```

**Next.js Integration**

Use AWS SDK in API routes or server-side functions.

1. **API Route Example** (`pages/api/s3-upload.js`):

   ```javascript
   import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

   const s3Client = new S3Client({
     region: 'us-east-1',
     credentials: {
       accessKeyId: process.env.AWS_ACCESS_KEY_ID,
       secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
     },
   });

   export default async function handler(req, res) {
     if (req.method === 'POST') {
       const params = {
         Bucket: 'your-bucket-name',
         Key: req.body.fileName,
         Body: req.body.content,
       };

       try {
         await s3Client.send(new PutObjectCommand(params));
         res.status(200).json({ message: 'File uploaded successfully' });
       } catch (error) {
         res.status(500).json({ error: error.message });
       }
     } else {
       res.status(405).json({ error: 'Method not allowed' });
     }
   }
   ```
2. **Environment Variables**:
   * In `.env.local`:

     ```
     AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY
     AWS_SECRET_ACCESS_KEY=YOUR_SECRET_KEY
     AWS_REGION=us-east-1
     ```
3. **Serverless Deployment**:
   * Deploy Next.js to **AWS Amplify** or **Lambda**:

     ```bash
     amplify init
     amplify push
     ```

**Useful Commands**

* Configure AWS CLI: `aws configure`
* Upload to S3: `aws s3 cp local-file s3://your-bucket/`
* Deploy Lambda: `aws lambda create-function --function-name myFunction --runtime nodejs20.x --handler index.handler --zip-file fileb://function.zip`
* List S3 buckets: `aws s3 ls`

#### 📈 Usefulness in Projects

* **Cost-Effective**: Pay-as-you-go pricing for serverless and storage.
* **Global Reach**: AWS’s extensive region availability ensures low latency.
* **Flexibility**: Modular SDK reduces bundle size for modern apps.
* **Enterprise Ready**: Supports complex architectures with VPCs and multi-region setups.

#### 🔗 Links

* [AWS SDK for JavaScript](https://aws.amazon.com/developer/language/javascript/)
* [Modular AWS SDK](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html)
* [AWS CLI Documentation](https://aws.amazon.com/cli/)
* [AWS Management Console](https://aws.amazon.com/console/)
* [S3 Getting Started](https://docs.aws.amazon.com/AmazonS3/latest/userguide/GetStartedWithS3.html)

***

### 3. **Firebase SDK**

#### 📌 What is the Firebase SDK?

The **Firebase SDK** is a JavaScript library for building web, mobile, and server applications using **Firebase** services, including **Firestore**, **Realtime Database**, **Authentication**, **Cloud Storage**, **Cloud Functions**, and **Hosting**. It’s optimized for real-time, serverless, and rapid development.

#### ✅ Why Use It?

* **Real-Time Sync**: Firestore and Realtime Database enable instant data updates.
* **Authentication**: Supports Google, Email, OAuth, and anonymous logins.
* **Serverless Backend**: Cloud Functions for event-driven logic.
* **Rapid Prototyping**: Simplifies backend setup for MVPs.

#### 📅 When to Use It?

* **Real-Time Applications**: Chat apps, live dashboards, or collaborative tools.
* **User Authentication**: Secure login systems with minimal setup.
* **Static Hosting**: Deploying single-page apps (SPAs) or static sites.
* **Mobile/Web Prototypes**: Building MVPs with minimal backend configuration.

#### ⚙️ Project Types and Use Cases

| **Project Type**        | **Why Use Firebase SDK?**                                | **Example Services**                       |
| ----------------------- | -------------------------------------------------------- | ------------------------------------------ |
| **Social Media Apps**   | Real-time feeds, notifications, and user authentication. | Firestore, Authentication, Cloud Functions |
| **Collaborative Tools** | Real-time document editing or live collaboration.        | Realtime Database, Firestore               |
| **E-commerce MVPs**     | Quick setup for product catalogs and user accounts.      | Firestore, Authentication, Hosting         |
| **Gaming Leaderboards** | Real-time updates for scores and player data.            | Realtime Database, Cloud Functions         |
| **Static Web Apps**     | Host SPAs or marketing sites with global CDN.            | Firebase Hosting                           |

#### 🛠️ How to Use It?

**Installation**

1. **Create a Firebase Project**:
   * Visit the [Firebase Console](https://console.firebase.google.com/).
   * Click **Add Project** and follow the setup.
2. **Install Firebase SDK**:

   ```bash
   npm install firebase
   ```
3. **Install Firebase CLI** (for deployments):

   ```bash
   npm install -g firebase-tools
   firebase login
   firebase init
   ```

**Key Management**

* **API Key**:
  1. In the Firebase Console, go to **Project Settings** > **General** > **Web App**.
  2. Register a web app to get the `firebaseConfig` object, including the API key.
  3. Example `firebaseConfig`:

     ```javascript
     const firebaseConfig = {
       apiKey: "YOUR_API_KEY",
       authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
       projectId: "YOUR_PROJECT_ID",
       storageBucket: "YOUR_BUCKET.appspot.com",
       messagingSenderId: "YOUR_SENDER_ID",
       appId: "YOUR_APP_ID",
     };
     ```
  4. Restrict the API key in the [Google Cloud Console](https://console.cloud.google.com/apis/credentials):
     * Navigate to **APIs & Services** > **Credentials**.
     * Set API restrictions to specific Firebase services.
* **Security Rules**:
  * Protect Firestore/Realtime Database with rules:

    ```javascript
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if request.auth != null;
        }
      }
    }
    ```
  * Deploy rules:

    ```bash
    firebase deploy --only firestore:rules
    ```
* **Security Best Practices**:
  * Use Firebase Authentication to secure data access.
  * Avoid exposing sensitive keys in client-side code.
  * Regularly audit Security Rules in the Firebase Console.

**JavaScript/Node.js Integration**

Example: Managing users in **Firestore** with Authentication.

1. **Initialize Firebase**:

   ```javascript
   // firebase.js
   import { initializeApp } from 'firebase/app';
   import { getFirestore } from 'firebase/firestore';
   import { getAuth } from 'firebase/auth';

   const firebaseConfig = {
     apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
     authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
     projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
     storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
     messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
     appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
   };

   const app = initializeApp(firebaseConfig);
   export const db = getFirestore(app);
   export const auth = getAuth(app);
   ```
2. **Example: Add User Data**:

   ```javascript
   import { collection, addDoc } from 'firebase/firestore';
   import { signInWithEmailAndPassword } from 'firebase/auth';
   import { db, auth } from './firebase';

   async function signInAndAddUser(email, password, userData) {
     try {
       await signInWithEmailAndPassword(auth, email, password);
       await addDoc(collection(db, 'users'), {
         name: userData.name,
         age: userData.age,
         createdAt: new Date(),
       });
       console.log('User added successfully');
     } catch (error) {
       console.error('Error:', error);
     }
   }

   signInAndAddUser('user@example.com', 'password123', { name: 'Alice', age: 30 });
   ```

**Next.js Integration**

Firebase works seamlessly with Next.js for both client-side and server-side operations.

1. **Client-Side Example** (React Component):

   ```javascript
   // pages/index.js
   import { useEffect, useState } from 'react';
   import { collection, getDocs } from 'firebase/firestore';
   import { db } from '../firebase';

   export default function Home() {
     const [users, setUsers] = useState([]);

     useEffect(() => {
       async function fetchUsers() {
         const querySnapshot = await getDocs(collection(db, 'users'));
         setUsers(querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));
       }
       fetchUsers();
     }, []);

     return (
       <div>
         <h1>Users</h1>
         <ul>
           {users.map(user => (
             <li key={user.id}>{user.name} - {user.age}</li>
           ))}
         </ul>
       </div>
     );
   }
   ```
2. **Server-Side Example** (API Route, `pages/api/users.js`):

   ```javascript
   import { collection, getDocs } from 'firebase/firestore';
   import { db } from '../../firebase';

   export default async function handler(req, res) {
     try {
       const querySnapshot = await getDocs(collection(db, 'users'));
       const users = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
       res.status(200).json(users);
     } catch (error) {
       res.status(500).json({ error: error.message });
     }
   }
   ```
3. **Environment Variables**:
   * In `.env.local`:

     ```
     NEXT_PUBLIC_FIREBASE_API_KEY=YOUR_API_KEY
     NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=YOUR_PROJECT_ID.firebaseapp.com
     NEXT_PUBLIC_FIREBASE_PROJECT_ID=YOUR_PROJECT_ID
     NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=YOUR_BUCKET.appspot.com
     NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=YOUR_SENDER_ID
     NEXT_PUBLIC_FIREBASE_APP_ID=YOUR_APP_ID
     ```
4. **Hosting with Firebase**:
   * Initialize hosting:

     ```bash
     firebase init hosting
     ```
   * Deploy Next.js app:

     ```bash
     npm run build
     firebase deploy --only hosting
     ```

**Useful Commands**

* Initialize project: `firebase init`
* Deploy hosting: `firebase deploy --only hosting`
* Deploy functions: `firebase deploy --only functions`
* Start emulator: `firebase emulators:start`

#### 📈 Usefulness in Projects

* **Rapid Development**: Simplifies backend setup for MVPs and startups.
* **Real-Time Features**: Ideal for chat, gaming, or collaborative apps.
* **Cost-Effective**: Generous free tier for small projects.
* **Scalability**: Firestore scales automatically for growing apps.

#### 🔗 Links

* [Firebase Documentation](https://firebase.google.com/docs)
* [Add Firebase to JavaScript](https://firebase.google.com/docs/web/setup)
* [Firebase CLI Reference](https://firebase.google.com/docs/cli)
* [Firebase Console](https://console.firebase.google.com/)
* [Firestore Security Rules](https://firebase.google.com/docs/firestore/security/get-started)

***

### ⚖️ SDK Comparison and Selection Guide

| **Feature/Use Case**       | **Google Cloud SDK**                     | **AWS SDK**                                  | **Firebase SDK**                       |
| -------------------------- | ---------------------------------------- | -------------------------------------------- | -------------------------------------- |
| **Best For**               | Enterprise infrastructure, ML, analytics | Serverless, SaaS, IoT, complex architectures | Real-time apps, MVPs, frontend-focused |
| **Ideal Project Types**    | Data platforms, ML models, microservices | APIs, e-commerce, IoT, static hosting        | Chat apps, social media, prototypes    |
| **Database**               | BigQuery, Cloud Datastore                | DynamoDB, RDS, Aurora                        | Firestore, Realtime Database           |
| **Hosting**                | App Engine, Cloud Run, GKE               | S3, Amplify, Lambda                          | Firebase Hosting                       |
| **CLI Tool**               | `gcloud`, `gsutil`                       | `aws` CLI                                    | `firebase` CLI                         |
| **JavaScript Integration** | `@google-cloud/*`                        | `aws-sdk`, `@aws-sdk/*`                      | `firebase`                             |
| **Authentication**         | IAM, OAuth                               | IAM, Cognito                                 | Firebase Authentication                |
| **Real-Time Support**      | Limited (Pub/Sub)                        | Limited (Kinesis)                            | Strong (Firestore, Realtime Database)  |
| **Learning Curve**         | Moderate to High                         | Moderate                                     | Low to Moderate                        |

#### 📋 Choosing the Right SDK

* **Google Cloud SDK**:
  * **When**: You need advanced infrastructure, ML, or big data analytics.
  * **Why**: Offers robust tools for enterprise-grade apps and AI.
  * **Example**: A fintech platform analyzing transaction data with BigQuery.
* **AWS SDK**:
  * **When**: You’re building serverless APIs, IoT solutions, or complex architectures.
  * **Why**: Provides granular control and a vast service ecosystem.
  * **Example**: An e-commerce backend with DynamoDB and Lambda.
* **Firebase SDK**:
  * **When**: You need rapid development, real-time features, or simple authentication.
  * **Why**: Simplifies backend setup for web/mobile apps.
  * **Example**: A real-time chat app with Firestore and Authentication.

***

### 🔐 Security Best Practices

* **Google Cloud SDK**:
  * Use IAM roles with minimal permissions.
  * Store service account keys in a secure vault.
  * Enable VPC Service Controls for sensitive data.
* **AWS SDK**:
  * Prefer IAM roles over access keys for EC2/Lambda.
  * Use AWS Secrets Manager for key storage.
  * Enable MFA for IAM users.
* **Firebase SDK**:
  * Implement strict Firestore/Realtime Database Security Rules.
  * Restrict API key usage in Google Cloud Console.
  * Use Firebase Authentication for data access control.

***

### 📁 Advanced Project Examples

#### 1. **Real-Time Analytics Dashboard (Firebase SDK)**

* **Use Case**: A dashboard displaying live user activity for a SaaS app.
* **Implementation**:
  * Store events in Firestore.
  * Use Firebase Authentication for user access.
  * Deploy with Firebase Hosting.
* **Code Snippet** (Add event):

  ```javascript
  import { collection, addDoc, serverTimestamp } from 'firebase/firestore';
  import { db } from './firebase';

  async function logEvent(userId, action) {
    await addDoc(collection(db, 'events'), {
      userId,
      action,
      timestamp: serverTimestamp(),
    });
  }
  ```

#### 2. **Serverless API for E-commerce (AWS SDK)**

* **Use Case**: An API for product listings and orders.
* **Implementation**:
  * Store products in DynamoDB.
  * Use Lambda and API Gateway for endpoints.
  * Serve images from S3.
* **Code Snippet** (Get products):

  ```javascript
  import { DynamoDBClient, ScanCommand } from '@aws-sdk/client-dynamodb';

  const client = new DynamoDBClient({ region: 'us-east-1' });

  async function getProducts() {
    const command = new ScanCommand({ TableName: 'Products' });
    const response = await client.send(command);
    return response.Items;
  }
  ```

#### 3. **ML-Powered Recommendation System (Google Cloud SDK)**

* **Use Case**: Recommend products based on user behavior.
* **Implementation**:
  * Store data in BigQuery.
  * Train models with Vertex AI.
  * Serve predictions via Cloud Functions.
* **Code Snippet** (Query BigQuery):

  ```javascript
  const { BigQuery } = require('@google-cloud/bigquery');
  const bigquery = new BigQuery();

  async function queryUserBehavior() {
    const query = 'SELECT user_id, product_id FROM `project.dataset.user_behavior` LIMIT 10';
    const [rows] = await bigquery.query({ query });
    return rows;
  }
  ```

***

### 🚀 Final Thoughts

The **Google Cloud SDK**, **AWS SDK**, and **Firebase SDK** are indispensable tools for modern cloud development. By mastering their use cases, integration patterns, and security practices, you can build scalable, secure, and efficient applications. This guide equips you with the knowledge to showcase these skills in your **GitBook portfolio**, demonstrating expertise in cloud-based development.

For further customization, such as generating a `.md` file, adding specific project demos, or integrating with GitBook’s styling, let me know!

***

### ✅ Quick Command Reference

| **SDK**          | **CLI Init**    | **Deploy Example**               | **Install in JS**         |
| ---------------- | --------------- | -------------------------------- | ------------------------- |
| **Google Cloud** | `gcloud init`   | `gcloud run deploy`              | `npm i @google-cloud/*`   |
| **AWS**          | `aws configure` | `aws lambda create-function`     | `npm i @aws-sdk/client-*` |
| **Firebase**     | `firebase init` | `firebase deploy --only hosting` | `npm i firebase`          |


# Firebase SDK

📌 What is the Firebase SDK?

The **Firebase SDK** is a JavaScript library for building web, mobile, and server applications using **Firebase** services, including **Firestore**, **Realtime Database**, **Authentication**, **Cloud Storage**, **Cloud Functions**, and **Hosting**. It’s optimized for real-time, serverless, and rapid development.

#### ✅ Why Use It?

* **Real-Time Sync**: Firestore and Realtime Database enable instant data updates.
* **Authentication**: Supports Google, Email, OAuth, and anonymous logins.
* **Serverless Backend**: Cloud Functions for event-driven logic.
* **Rapid Prototyping**: Simplifies backend setup for MVPs.

#### 📅 When to Use It?

* **Real-Time Applications**: Chat apps, live dashboards, or collaborative tools.
* **User Authentication**: Secure login systems with minimal setup.
* **Static Hosting**: Deploying single-page apps (SPAs) or static sites.
* **Mobile/Web Prototypes**: Building MVPs with minimal backend configuration.

#### ⚙️ Project Types and Use Cases

| **Project Type**        | **Why Use Firebase SDK?**                                | **Example Services**                       |
| ----------------------- | -------------------------------------------------------- | ------------------------------------------ |
| **Social Media Apps**   | Real-time feeds, notifications, and user authentication. | Firestore, Authentication, Cloud Functions |
| **Collaborative Tools** | Real-time document editing or live collaboration.        | Realtime Database, Firestore               |
| **E-commerce MVPs**     | Quick setup for product catalogs and user accounts.      | Firestore, Authentication, Hosting         |
| **Gaming Leaderboards** | Real-time updates for scores and player data.            | Realtime Database, Cloud Functions         |
| **Static Web Apps**     | Host SPAs or marketing sites with global CDN.            | Firebase Hosting                           |

#### 🛠️ How to Use It?

**Installation**

1. **Create a Firebase Project**:
   * Visit the [Firebase Console](https://console.firebase.google.com/).
   * Click **Add Project** and follow the setup.
2. **Install Firebase SDK**:

   ```bash
   npm install firebase
   ```
3. **Install Firebase CLI** (for deployments):

   ```bash
   npm install -g firebase-tools
   firebase login
   firebase init
   ```

**Key Management**

* **API Key**:
  1. In the Firebase Console, go to **Project Settings** > **General** > **Web App**.
  2. Register a web app to get the `firebaseConfig` object, including the API key.
  3. Example `firebaseConfig`:

     ```javascript
     const firebaseConfig = {
       apiKey: "YOUR_API_KEY",
       authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
       projectId: "YOUR_PROJECT_ID",
       storageBucket: "YOUR_BUCKET.appspot.com",
       messagingSenderId: "YOUR_SENDER_ID",
       appId: "YOUR_APP_ID",
     };
     ```
  4. Restrict the API key in the [Google Cloud Console](https://console.cloud.google.com/apis/credentials):
     * Navigate to **APIs & Services** > **Credentials**.
     * Set API restrictions to specific Firebase services.
* **Security Rules**:
  * Protect Firestore/Realtime Database with rules:

    ```javascript
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if request.auth != null;
        }
      }
    }
    ```
  * Deploy rules:

    ```bash
    firebase deploy --only firestore:rules
    ```
* **Security Best Practices**:
  * Use Firebase Authentication to secure data access.
  * Avoid exposing sensitive keys in client-side code.
  * Regularly audit Security Rules in the Firebase Console.

**JavaScript/Node.js Integration**

Example: Managing users in **Firestore** with Authentication.

1. **Initialize Firebase**:

   ```javascript
   // firebase.js
   import { initializeApp } from 'firebase/app';
   import { getFirestore } from 'firebase/firestore';
   import { getAuth } from 'firebase/auth';

   const firebaseConfig = {
     apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
     authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
     projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
     storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
     messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
     appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
   };

   const app = initializeApp(firebaseConfig);
   export const db = getFirestore(app);
   export const auth = getAuth(app);
   ```
2. **Example: Add User Data**:

   ```javascript
   import { collection, addDoc } from 'firebase/firestore';
   import { signInWithEmailAndPassword } from 'firebase/auth';
   import { db, auth } from './firebase';

   async function signInAndAddUser(email, password, userData) {
     try {
       await signInWithEmailAndPassword(auth, email, password);
       await addDoc(collection(db, 'users'), {
         name: userData.name,
         age: userData.age,
         createdAt: new Date(),
       });
       console.log('User added successfully');
     } catch (error) {
       console.error('Error:', error);
     }
   }

   signInAndAddUser('user@example.com', 'password123', { name: 'Alice', age: 30 });
   ```

**Next.js Integration**

Firebase works seamlessly with Next.js for both client-side and server-side operations.

1. **Client-Side Example** (React Component):

   ```javascript
   // pages/index.js
   import { useEffect, useState } from 'react';
   import { collection, getDocs } from 'firebase/firestore';
   import { db } from '../firebase';

   export default function Home() {
     const [users, setUsers] = useState([]);

     useEffect(() => {
       async function fetchUsers() {
         const querySnapshot = await getDocs(collection(db, 'users'));
         setUsers(querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));
       }
       fetchUsers();
     }, []);

     return (
       <div>
         <h1>Users</h1>
         <ul>
           {users.map(user => (
             <li key={user.id}>{user.name} - {user.age}</li>
           ))}
         </ul>
       </div>
     );
   }
   ```
2. **Server-Side Example** (API Route, `pages/api/users.js`):

   ```javascript
   import { collection, getDocs } from 'firebase/firestore';
   import { db } from '../../firebase';

   export default async function handler(req, res) {
     try {
       const querySnapshot = await getDocs(collection(db, 'users'));
       const users = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
       res.status(200).json(users);
     } catch (error) {
       res.status(500).json({ error: error.message });
     }
   }
   ```
3. **Environment Variables**:
   * In `.env.local`:

     ```
     NEXT_PUBLIC_FIREBASE_API_KEY=YOUR_API_KEY
     NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=YOUR_PROJECT_ID.firebaseapp.com
     NEXT_PUBLIC_FIREBASE_PROJECT_ID=YOUR_PROJECT_ID
     NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=YOUR_BUCKET.appspot.com
     NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=YOUR_SENDER_ID
     NEXT_PUBLIC_FIREBASE_APP_ID=YOUR_APP_ID
     ```
4. **Hosting with Firebase**:
   * Initialize hosting:

     ```bash
     firebase init hosting
     ```
   * Deploy Next.js app:

     ```bash
     npm run build
     firebase deploy --only hosting
     ```

**Useful Commands**

* Initialize project: `firebase init`
* Deploy hosting: `firebase deploy --only hosting`
* Deploy functions: `firebase deploy --only functions`
* Start emulator: `firebase emulators:start`

#### 📈 Usefulness in Projects

* **Rapid Development**: Simplifies backend setup for MVPs and startups.
* **Real-Time Features**: Ideal for chat, gaming, or collaborative apps.
* **Cost-Effective**: Generous free tier for small projects.
* **Scalability**: Firestore scales automatically for growing apps.

#### 🔗 Links

* [Firebase Documentation](https://firebase.google.com/docs)
* [Add Firebase to JavaScript](https://firebase.google.com/docs/web/setup)
* [Firebase CLI Reference](https://firebase.google.com/docs/cli)
* [Firebase Console](https://console.firebase.google.com/)
* [Firestore Security Rules](https://firebase.google.com/docs/firestore/security/get-started)

***

### ⚖️ SDK Comparison and Selection Guide

| **Feature/Use Case**       | **Google Cloud SDK**                     | **AWS SDK**                                  | **Firebase SDK**                       |
| -------------------------- | ---------------------------------------- | -------------------------------------------- | -------------------------------------- |
| **Best For**               | Enterprise infrastructure, ML, analytics | Serverless, SaaS, IoT, complex architectures | Real-time apps, MVPs, frontend-focused |
| **Ideal Project Types**    | Data platforms, ML models, microservices | APIs, e-commerce, IoT, static hosting        | Chat apps, social media, prototypes    |
| **Database**               | BigQuery, Cloud Datastore                | DynamoDB, RDS, Aurora                        | Firestore, Realtime Database           |
| **Hosting**                | App Engine, Cloud Run, GKE               | S3, Amplify, Lambda                          | Firebase Hosting                       |
| **CLI Tool**               | `gcloud`, `gsutil`                       | `aws` CLI                                    | `firebase` CLI                         |
| **JavaScript Integration** | `@google-cloud/*`                        | `aws-sdk`, `@aws-sdk/*`                      | `firebase`                             |
| **Authentication**         | IAM, OAuth                               | IAM, Cognito                                 | Firebase Authentication                |
| **Real-Time Support**      | Limited (Pub/Sub)                        | Limited (Kinesis)                            | Strong (Firestore, Realtime Database)  |
| **Learning Curve**         | Moderate to High                         | Moderate                                     | Low to Moderate                        |

#### 📋 Choosing the Right SDK

* **Google Cloud SDK**:
  * **When**: You need advanced infrastructure, ML, or big data analytics.
  * **Why**: Offers robust tools for enterprise-grade apps and AI.
  * **Example**: A fintech platform analyzing transaction data with BigQuery.
* **AWS SDK**:
  * **When**: You’re building serverless APIs, IoT solutions, or complex architectures.
  * **Why**: Provides granular control and a vast service ecosystem.
  * **Example**: An e-commerce backend with DynamoDB and Lambda.
* **Firebase SDK**:
  * **When**: You need rapid development, real-time features, or simple authentication.
  * **Why**: Simplifies backend setup for web/mobile apps.
  * **Example**: A real-time chat app with Firestore and Authentication.

***

### 🔐 Security Best Practices

* **Google Cloud SDK**:
  * Use IAM roles with minimal permissions.
  * Store service account keys in a secure vault.
  * Enable VPC Service Controls for sensitive data.
* **AWS SDK**:
  * Prefer IAM roles over access keys for EC2/Lambda.
  * Use AWS Secrets Manager for key storage.
  * Enable MFA for IAM users.
* **Firebase SDK**:
  * Implement strict Firestore/Realtime Database Security Rules.
  * Restrict API key usage in Google Cloud Console.
  * Use Firebase Authentication for data access control.

***

### 📁 Advanced Project Examples

#### 1. **Real-Time Analytics Dashboard (Firebase SDK)**

* **Use Case**: A dashboard displaying live user activity for a SaaS app.
* **Implementation**:
  * Store events in Firestore.
  * Use Firebase Authentication for user access.
  * Deploy with Firebase Hosting.
* **Code Snippet** (Add event):

  ```javascript
  import { collection, addDoc, serverTimestamp } from 'firebase/firestore';
  import { db } from './firebase';

  async function logEvent(userId, action) {
    await addDoc(collection(db, 'events'), {
      userId,
      action,
      timestamp: serverTimestamp(),
    });
  }
  ```

#### 2. **Serverless API for E-commerce (AWS SDK)**

* **Use Case**: An API for product listings and orders.
* **Implementation**:
  * Store products in DynamoDB.
  * Use Lambda and API Gateway for endpoints.
  * Serve images from S3.
* **Code Snippet** (Get products):

  ```javascript
  import { DynamoDBClient, ScanCommand } from '@aws-sdk/client-dynamodb';

  const client = new DynamoDBClient({ region: 'us-east-1' });

  async function getProducts() {
    const command = new ScanCommand({ TableName: 'Products' });
    const response = await client.send(command);
    return response.Items;
  }
  ```

#### 3. **ML-Powered Recommendation System (Google Cloud SDK)**

* **Use Case**: Recommend products based on user behavior.
* **Implementation**:
  * Store data in BigQuery.
  * Train models with Vertex AI.
  * Serve predictions via Cloud Functions.
* **Code Snippet** (Query BigQuery):

  ```javascript
  const { BigQuery } = require('@google-cloud/bigquery');
  const bigquery = new BigQuery();

  async function queryUserBehavior() {
    const query = 'SELECT user_id, product_id FROM `project.dataset.user_behavior` LIMIT 10';
    const [rows] = await bigquery.query({ query });
    return rows;
  }
  ```

***

### 🚀 Final Thoughts

The **Google Cloud SDK**, **AWS SDK**, and **Firebase SDK** are indispensable tools for modern cloud development. By mastering their use cases, integration patterns, and security practices, you can build scalable, secure, and efficient applications. This guide equips you with the knowledge to showcase these skills in your **GitBook portfolio**, demonstrating expertise in cloud-based development.

For further customization, such as generating a `.md` file, adding specific project demos, or integrating with GitBook’s styling, let me know!

***

### ✅ Quick Command Reference

| **SDK**          | **CLI Init**    | **Deploy Example**               | **Install in JS**         |
| ---------------- | --------------- | -------------------------------- | ------------------------- |
| **Google Cloud** | `gcloud init`   | `gcloud run deploy`              | `npm i @google-cloud/*`   |
| **AWS**          | `aws configure` | `aws lambda create-function`     | `npm i @aws-sdk/client-*` |
| **Firebase**     | `firebase init` | `firebase deploy --only hosting` | `npm i firebase`          |


# EOF EVM Object Format

This guide is designed for your **GitBook portfolio**, providing an in-depth exploration of the **EVM Object Format (EOF)**, a transformative upgrade for the **Ethereum Virtual Machine (EVM)**. It covers EOF’s purpose, launch details, usage, integration in **Solidity**, **Rust**, and **Go**, code snippets, structural details, and practical guides. Whether you’re building smart contracts, developing tools, or exploring Ethereum’s execution layer, this resource equips you with the knowledge to leverage EOF effectively.

***

### 📌 What is EVM Object Format (EOF)?

The **EVM Object Format (EOF)** is a set of Ethereum Improvement Proposals (EIPs) that introduces a structured, versioned, and extensible container format for EVM bytecode. Unlike the legacy EVM bytecode, which lacks structure and requires repeated runtime validations, EOF validates bytecode once at deployment, separating code and data, removing dynamic jumps, and introducing new opcodes for better efficiency and security. EOF modernizes the EVM, addressing long-standing issues and enabling advanced tooling, formal verification, and Layer 2 (L2) optimizations.

#### Key Features of EOF

* **Structured Bytecode**: Separates code, data, and metadata into distinct sections.
* **One-Time Validation**: Validates bytecode at deployment, reducing runtime overhead.
* **Static Jumps**: Replaces dynamic jumps (e.g., `JUMP`/`JUMPI`) with static relative jumps for predictable control flow.
* **Versioning**: Includes a version field for future EVM upgrades and backward compatibility.
* **New Opcodes**: Introduces opcodes like `EXTCALL`, `EOFCREATE`, `DUPN`, and `SWAPN` for improved stack management and address space expansion.
* **Subroutines**: Supports structured subroutines, enhancing code modularity and fuzz testing.

***

### ✅ Why is EOF Needed?

EOF addresses critical limitations in the legacy EVM, which was designed for simplicity but became a bottleneck for performance, security, and developer experience. Here’s why EOF is essential:

* **Performance Optimization**: Eliminates repetitive runtime checks (e.g., stack underflow/overflow, jump destination analysis) by validating bytecode once at deployment, reducing gas costs.
* **Security**: Structured bytecode prevents issues like executing data as code, improving static analysis and formal verification.
* **Tooling Support**: Provides a clear structure for compilers, debuggers, and static analyzers, lowering the barrier for tool development.
* **Scalability for L2**: Enables L2 solutions to optimize execution and supports zero-knowledge EVMs (zkEVMs) with structured control flow.
* **Developer Experience**: Solves issues like Solidity’s “stack too deep” error with new stack management opcodes (`DUPN`/`SWAPN`).
* **Future-Proofing**: Versioning allows seamless EVM upgrades (e.g., address space expansion, account abstraction) without breaking legacy contracts.

#### Usefulness in Projects

| **Project Type**               | **Why EOF is Useful**                                                              | **Benefits**                            |
| ------------------------------ | ---------------------------------------------------------------------------------- | --------------------------------------- |
| **Smart Contract Development** | Structured bytecode simplifies debugging and auditing, reducing vulnerabilities.   | Safer contracts, lower gas costs        |
| **Tooling Development**        | Clear code/data separation enables better static analysis and formal verification. | Easier tool creation, improved accuracy |
| **Layer 2 Solutions**          | Static jumps and subroutines optimize execution for zkEVMs and rollups.            | Faster L2 processing, DDoS resistance   |
| **DeFi Applications**          | Larger bytecode size limits (via EIP-7830) support complex logic without proxies.  | Simplified contract design, lower costs |
| **Compiler Optimization**      | Compilers can target EOF for efficient code generation, dropping legacy support.   | Reduced maintenance, optimized bytecode |

***

### 📅 Launch Details

EOF was initially planned for the **Shanghai upgrade** (2023) but faced delays due to complexity and ecosystem readiness. As of May 19, 2025, EOF was excluded from the **Fusaka upgrade** to maintain a lighter scope but is targeted for the **Pectra upgrade** (scheduled for May 7, 2025). The Solidity team and Ethereum clients (e.g., Geth, Reth) are actively implementing EOF, with Solidity v0.8.30 setting the default EVM version to `prague` to support EOF.

#### Implementation Status

* **EIPs Included**: EIP-3540, EIP-3670, EIP-4200, EIP-4750, EIP-5450, EIP-6206, EIP-663, EIP-7698, and others.
* **Client Support**: Implemented in Geth, Besu, Nethermind, and Reth, with ongoing testing.
* **Solidity Support**: Full support in Solidity v0.8.30, with plans to phase out legacy EVM support.
* **Testing**: Available in testnets like Holesky, with Remix IDE supporting EOF compilation.

***

### ⚙️ How to Use EOF

EOF is primarily a bytecode-level upgrade, so developers interact with it through compilers (e.g., Solidity, Vyper) and tools (e.g., Remix, Hardhat). Below are the steps to use EOF in your Ethereum projects.

#### Prerequisites

* **Solidity Compiler**: Version 0.8.30 or higher, configured for the `prague` EVM version.
* **Ethereum Client**: Geth, Besu, or Nethermind with EOF support (use testnet builds for now).
* **IDE**: Remix IDE or VS Code with Solidity extensions.
* **Wallet**: MetaMask for testnet deployments.
* **Node**: Access to a testnet node (e.g., via QuickNode or Infura).

#### Setup

1. **Install Solidity Compiler**:

   ```bash
   npm install -g solc@0.8.30
   ```
2. **Configure Remix IDE**:
   * Open [Remix IDE](https://remix.ethereum.org/).
   * In the **Compile** tab, select Solidity v0.8.30 and EVM version `prague`.
   * Ensure the **Environment** is set to a testnet (e.g., Holesky).
3. **Set Up MetaMask**:
   * Connect to a testnet like Holesky.
   * Obtain test Ether from a faucet (e.g., [Holesky Faucet](https://holesky-faucet.com/)).
4. **Clone Example Repo** (optional):

   ```bash
   git clone https://github.com/ethereum/eof-examples
   cd eof-examples
   ```

#### Deployment Workflow

1. **Write an EOF-Compatible Contract**:
   * Use Solidity v0.8.30 with `pragma solidity ^0.8.30;`.
   * Ensure the contract avoids legacy opcodes (e.g., `JUMP`, `JUMPI`), which are disabled in EOF.
2. **Compile with EOF**:

   ```bash
   solc --evm-version prague contract.sol --bin
   ```
3. **Deploy via Remix**:
   * In Remix, select the compiled contract.
   * Deploy to the Holesky testnet using MetaMask.
   * Verify deployment on the Holesky explorer.
4. **Verify Bytecode**:
   * Use `evm.codes` to inspect the deployed bytecode and confirm EOF structure (magic number `0xEF00`, version, and section headers).

***

### 🛠️ Code Snippets and Integration

EOF impacts how smart contracts are compiled and executed, with specific implications for **Solidity**, **Rust**, and **Go**. Below are integration details and code snippets for each language.

#### 1. **Solidity**

Solidity is the primary language for EOF, with full support in v0.8.30. EOF simplifies contract development by solving issues like “stack too deep” and enabling larger bytecode sizes (via EIP-7830).

**Example: EOF-Compatible Storage Contract**

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract EOFStorage {
    mapping(address => uint256) public balances;

    // Event for logging
    event BalanceUpdated(address indexed user, uint256 amount);

    // Set balance
    function setBalance(uint256 amount) public {
        balances[msg.sender] = amount;
        emit BalanceUpdated(msg.sender, amount);
    }

    // Get balance
    function getBalance() public view returns (uint256) {
        return balances[msg.sender];
    }
}
```

**Integration in Solidity Projects**

1. **Hardhat Setup**:
   * Install Hardhat:

     ```bash
     npm init -y
     npm install --save-dev hardhat
     npx hardhat init
     ```
   * Update `hardhat.config.js`:

     ```javascript
     module.exports = {
       solidity: {
         version: "0.8.30",
         settings: {
           evmVersion: "prague",
         },
       },
       networks: {
         holesky: {
           url: "YOUR_HOLESKY_RPC_URL",
           accounts: ["YOUR_PRIVATE_KEY"],
         },
       },
     };
     ```
2. **Deploy Script** (`scripts/deploy.js`):

   ```javascript
   const hre = require("hardhat");

   async function main() {
     const EOFStorage = await hre.ethers.getContractFactory("EOFStorage");
     const storage = await EOFStorage.deploy();
     await storage.deployed();
     console.log("EOFStorage deployed to:", storage.address);
   }

   main().catch(error => {
     console.error(error);
     process.exit(1);
   });
   ```
3. **Run Deployment**:

   ```bash
   npx hardhat run scripts/deploy.js --network holesky
   ```

**Benefits in Solidity**

* **Stack Management**: `DUPN` and `SWAPN` opcodes eliminate “stack too deep” errors.
* **Larger Contracts**: EIP-7830 allows bytecode sizes beyond 24 KB, reducing the need for proxy patterns.
* **Static Analysis**: Structured bytecode improves tools like Slither and Mythril.

#### 2. **Rust**

Rust is used for Ethereum client development (e.g., Reth) and WebAssembly (WASM) smart contracts, with libraries like `ethers-rs` supporting EOF-compatible deployments.

**Example: Deploying an EOF Contract with `ethers-rs`**

```rust
use ethers::prelude::*;
use std::path::Path;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to Holesky testnet
    let provider = Provider::<Http>::try_from("YOUR_HOLESKY_RPC_URL")?;
    let wallet = "YOUR_PRIVATE_KEY".parse::<LocalWallet>()?.with_chain_id(17000u64);
    let client = SignerMiddleware::new(provider, wallet);

    // Load ABI and bytecode (compiled with solc --evm-version prague)
    let abi = include_str!("../artifacts/EOFStorage.json");
    let bytecode = include_bytes!("../artifacts/EOFStorage.bin");

    // Deploy contract
    let factory = ContractFactory::new(abi.parse()?, bytecode.to_vec().into(), client);
    let contract = factory.deploy(())?.send().await?;
    println!("Deployed EOFStorage at: {}", contract.address());

    Ok(())
}
```

**Integration in Rust Projects**

1. **Setup `Cargo.toml`**:

   ```toml
   [package]
   name = "eof-deploy"
   version = "0.1.0"
   edition = "2021"

   [dependencies]
   ethers = { version = "2.0", features = ["abigen"] }
   tokio = { version = "1.0", features = ["full"] }
   ```
2. **Compile Solidity Contract**:

   ```bash
   solc --evm-version prague contract.sol --bin --abi --out artifacts
   ```
3. **Run Deployment**:

   ```bash
   cargo run
   ```

**Benefits in Rust**

* **Client Development**: EOF’s structured bytecode simplifies EVM implementations in Reth.
* **WASM Contracts**: Rust’s WASM support (via `wasmi`) aligns with EOF’s static jump model.
* **Safety**: Rust’s memory safety ensures robust client-side EOF processing.

#### 3. **Go**

Go is used in Ethereum clients like Geth and for tooling. The `go-ethereum` library supports EOF-compatible contract deployments.

**Example: Deploying an EOF Contract with `go-ethereum`**

```go
package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"math/big"

	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/ethclient"
)

func main() {
	// Connect to Holesky testnet
	client, err := ethclient.Dial("YOUR_HOLESKY_RPC_URL")
	if err != nil {
		panic(err)
	}

	// Load private key
	privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY")
	if err != nil {
		panic(err)
	}

	// Create transactor
	auth, err := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(17000)) // Holesky chain ID
	if err != nil {
		panic(err)
	}

	// Load bytecode
	bytecode, err := ioutil.ReadFile("artifacts/EOFStorage.bin")
	if err != nil {
		panic(err)
	}

	// Deploy contract
	_, tx, _, err := bind.DeployContract(auth, bind.ContractBackend(client), nil, bytecode)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Contract deployment TX: %s\n", tx.Hash().Hex())
}
```

**Integration in Go Projects**

1. **Setup `go.mod`**:

   ```go
   module eof-deploy

   go 1.20

   require github.com/ethereum/go-ethereum v1.14.0
   ```
2. **Compile Solidity Contract**:

   ```bash
   solc --evm-version prague contract.sol --bin --out artifacts
   ```
3. **Run Deployment**:

   ```bash
   go run main.go
   ```

**Benefits in Go**

* **Client Integration**: Geth’s EOF support simplifies node development.
* **Tooling**: Go’s concurrency model enhances EOF bytecode analysis tools.
* **Performance**: Go’s efficiency aligns with EOF’s one-time validation.

***

### 🧱 EOF Structure Details

EOF introduces a container format for EVM bytecode, with the following structure:

```
+-------------------------------------------------+
| Magic Number (0xEF00) | Version (0x01)         |
+-------------------------------------------------+
| Section Headers (Type, Size)                    |
| - Code Section Header                           |
| - Data Section Header (optional)                |
| - Type Section Header (optional)                |
+-------------------------------------------------+
| Code Section (Bytecode with static jumps)       |
+-------------------------------------------------+
| Data Section (Immutable data, e.g., constants)  |
+-------------------------------------------------+
| Type Section (Function signatures, optional)    |
+-------------------------------------------------+
```

#### Key Components

* **Magic Number**: `0xEF00` identifies EOF bytecode.
* **Version**: Starts at `0x01`, enabling future upgrades.
* **Section Headers**: Define the size and type of each section (code, data, type).
* **Code Section**: Contains executable bytecode with static jumps and new opcodes (e.g., `EXTCALL`, `DUPN`).
* **Data Section**: Stores immutable data, preventing execution as code.
* **Type Section**: Optional metadata for function signatures, aiding tooling.

#### Benefits of Structure

* **Separation of Concerns**: Code and data isolation improves security and analysis.
* **Extensibility**: Versioning supports future EVM features (e.g., EIP-7701 for account abstraction).
* **Static Analysis**: Structured control flow enables linear-time analysis and fuzz testing.

***

### 📋 Practical Guides

#### 1. **Testing EOF Contracts in Remix**

1. **Open Remix IDE**:
   * Navigate to [Remix IDE](https://remix.ethereum.org/).
   * Create a new file, `EOFStorage.sol`, with the Solidity example above.
2. **Compile**:
   * Select Solidity v0.8.30 and EVM version `prague`.
   * Click **Compile**.
3. **Deploy**:
   * Set the environment to **Injected Provider - MetaMask** (connected to Holesky).
   * Deploy the contract and confirm the transaction in MetaMask.
4. **Test Functions**:
   * Call `setBalance(100)` and verify the `BalanceUpdated` event.
   * Call `getBalance()` and confirm the returned value is `100`.

#### 2. **Analyzing EOF Bytecode**

1. **Compile with `solc`**:

   ```bash
   solc --evm-version prague --bin-runtime EOFStorage.sol
   ```
2. **Inspect with `evm.codes`**:
   * Paste the bytecode into [evm.codes](https://www.evm.codes/).
   * Verify the EOF structure (magic number, section headers, static jumps).
3. **Check Opcodes**:
   * Look for new opcodes like `DUPN` or `EXTCALL` in the disassembled code.

#### 3. **Integrating with Hardhat**

1. **Create a Hardhat Project**:

   ```bash
   npx hardhat init
   ```
2. **Add Contract**:
   * Place `EOFStorage.sol` in the `contracts` folder.
3. **Configure and Deploy**:
   * Update `hardhat.config.js` as shown in the Solidity integration section.
   * Run:

     ```bash
     npx hardhat run scripts/deploy.js --network holesky
     ```

#### 4. **Building EOF-Compatible Tools**

* **Static Analyzer** (Rust):
  * Use `revm` (Rust EVM implementation) to parse EOF bytecode.
  * Example: Check for valid section headers and static jumps.
* **Debugger** (Go):
  * Extend Geth’s tracer to support EOF opcodes like `EOFCREATE`.
  * Example: Log stack changes for `DUPN`/`SWAPN`.

***

### 🔐 Security and Best Practices

* **Validate Bytecode**: Ensure the magic number (`0xEF00`) and version are correct before processing.
* **Use Latest Compiler**: Solidity v0.8.30 includes EOF-specific optimizations and security checks.
* **Audit Tools**: Leverage EOF’s structured bytecode with tools like Slither for better vulnerability detection.
* **Test Thoroughly**: Use testnets (Holesky) to verify EOF contract behavior, as some legacy patterns may break.
* **Monitor Gas Costs**: While EOF reduces runtime gas, deployment gas may increase due to validation. Optimize data sections to minimize costs.

***

### 🔗 Useful Resources

* **Official Documentation**: [Solidity EOF Support](https://soliditylang.org/blog/2025/03/27/the-case-for-eof/)
* **EIP Specifications**: [EIP-3540](https://eips.ethereum.org/EIPS/eip-3540), [EIP-3670](https://eips.ethereum.org/EIPS/eip-3670), [EIP-4200](https://eips.ethereum.org/EIPS/eip-4200)
* **Tools**:
  * [Remix IDE](https://remix.ethereum.org/) for testing
  * [evm.codes](https://www.evm.codes/) for bytecode analysis
  * [Hardhat EOF Plugin](https://hardhat.org/plugins) (check for EOF support)
* **Testnet**: [Holesky Explorer](https://holesky.etherscan.io/)
* **Community**: [Solidity Forum](https://forum.soliditylang.org/) for EOF discussions

***

### 🚀 Final Thoughts

The **EVM Object Format (EOF)** is a game-changer for Ethereum, enhancing performance, security, and developer experience. By integrating EOF into your Solidity, Rust, or Go projects, you can build more efficient smart contracts, develop advanced tools, and support L2 scalability. This guide equips you to showcase EOF expertise in your **GitBook portfolio**, positioning you as a forward-thinking Ethereum developer.

For further customization, such as adding EOF-specific contract templates, integrating with your `smart-contracts-library-evm` repo, or generating a `.md` file, let me know!


# Medium Articles

####

* **Ethereum’s Fusaka Upgrade: The Most Ambitious Step Since The Merge** \
  [Read here](https://dev.to/codebyankita/ethereums-fusaka-upgrade-the-most-ambitious-step-since-the-merge-live-on-mainnet-dec-3-2025-37nl)
* **Kohaku: A Practical Privacy Framework for Ethereum Wallets**\
  [Read here](https://dev.to/codebyankita/kohaku-a-practical-privacy-framework-for-ethereum-wallets-4aof)
* **EIP-7939: Count Leading Zeros (CLZ) Opcode**\
  [Read here](https://dev.to/codebyankita/eip-7939-count-leading-zeros-clz-opcode-2g6d)

#### Blockchain Security

1. **Smart Contract Security Audits: Protecting Blockchain Applications**\
   [Link](https://medium.com/@ankitacode11/smart-contract-security-audits-protecting-blockchain-applications-f833cc085f6b)
2. **Eclipse Attacks: Unveiling a Hidden Threat to Blockchain Security**\
   [Link](https://medium.com/@ankitacode11/eclipse-attacks-unveiling-a-hidden-threat-to-blockchain-security-0fa966306cf)
3. **Unmasking Multisig Scams: A Beginner’s Guide to Staying Safe in Crypto**\
   [Link](https://medium.com/@ankitacode11/unmasking-privacy-coin-mixing-and-coinjoins-in-crypto-48b1964c1008)
4. **Air-Gapped Wallets: A Deep Dive into Offline Crypto Security**\
   [Link](https://medium.com/@ankitacode11/air-gapped-wallets-a-deep-dive-into-offline-crypto-security-0aaacd0fafd6)
5. **Essential Tips for Using a Hardware Wallet Securely**\
   [Link](https://medium.com/@ankitacode11/essential-tips-for-using-a-hardware-wallet-securely-4cbaa9085306)
6. **Securing Smart Contracts with Solodit: A Comprehensive Guide**\
   [Link](https://medium.com/@ankitacode11/1-securing-smart-contracts-with-solodit-a-comprehensive-guide-7be7b562c323)
7. **Part 1: Breaking the Gas Trap — Defending Smart Contracts Against Denial of Service Attacks**\
   [Link](https://medium.com/@ankitacode11/part-1-breaking-the-gas-trap-defending-smart-contracts-against-denial-of-service-attacks-c62d9fcbe63c)
8. **Part 2: How to Protect Your Smart Contracts from State Bloating and Gas Griefing Attacks**\
   [Link](https://medium.com/@ankitacode11/part-2-how-to-protect-your-smart-contracts-from-state-bloating-and-gas-griefing-attacks-2a0be91e249e)
9. **Part 3: Protecting Smart Contracts from Donation Attacks — A Guide to Secure ETH Handling**\
   [Link](https://medium.com/@ankitacode11/part-3-protecting-smart-contracts-from-donation-attacks-a-guide-to-secure-eth-handling-b05561228ab2)
10. **Part 5: Gas Wasters Beware — Defending Ethereum Smart Contracts Against Griefing Attacks**\
    [Link](https://medium.com/@ankitacode11/part-5-gas-wasters-beware-defending-ethereum-smart-contracts-against-griefing-attacks-4bf17eecb575)
11. **Part 6: Outsmarting the Block Producers — Safeguarding Ethereum Smart Contracts Against Miner Attacks**\
    [Link](https://medium.com/@ankitacode11/part-6-outsmarting-the-block-producers-safeguarding-ethereum-smart-contracts-against-miner-d0029db4bc21)
12. **Part 7: Shielding Ethereum Smart Contracts from Price Manipulation Attacks**\
    [Link](https://medium.com/@ankitacode11/part-7-shielding-ethereum-smart-contracts-from-price-manipulation-attacks-6ef8587377b6)
13. **Part 8: Defending Ethereum Smart Contracts Against Reentrancy Attacks**\
    [Link](https://medium.com/@ankitacode11/part-8-defending-ethereum-smart-contracts-against-reentrancy-attacks-e32915316ef6)
14. **Outsmarting the Mempool Marauders: Countering Front-Running and Griefing Attacks in Ethereum Smart Contracts**\
    [Link](https://medium.com/@ankitacode11/outsmarting-the-mempool-marauders-countering-front-running-and-griefing-attacks-in-ethereum-smart-8e53934c310c)

#### Cryptography & Quantum Computing

1. **End-to-End Encryption: The Ultimate Guide to Secure Digital Communication**\
   [Link](https://medium.com/@ankitacode11/end-to-end-encryption-the-ultimate-guide-to-secure-digital-communication-1bd20c199f27)
2. **Quantum Fully Homomorphic Encryption**\
   [Link](https://medium.com/@ankitacode11/quantum-fully-homomorphic-encryption-b93b4f0fa535)
3. **Quantum Public Key Encryption: Securing the Future of Cryptography**\
   [Link](https://medium.com/@ankitacode11/quantum-public-key-encryption-securing-the-future-of-cryptography-e96c4294d629)
4. **Quantum Cryptographic Protocols**\
   [Link](https://medium.com/@ankitacode11/quantum-cryptographic-protocols-c27f63e9f53c)
5. **Advanced Cryptographic Techniques**\
   [Link](https://medium.com/@ankitacode11/advanced-cryptographic-techniques-9f3ef3194472)
6. **Post-Quantum Cryptography: Understanding Lattices and Modern Cryptographic Problems**\
   [Link](https://medium.com/@ankitacode11/post-quantum-cryptography-understanding-lattices-and-modern-cryptographic-problems-edd76721118c)
7. **Breaking Cryptography with Quantum Computing**\
   [Link](https://medium.com/@ankitacode11/breaking-cryptography-with-quantum-computing-e011af9e0779)
8. **Quantum Algorithmic Tools**\
   [Link](https://medium.com/@ankitacode11/quantum-algorithmic-tools-98912813d2e0)
9. **Quantum Cryptography Key Exchange and Encryption**\
   [Link](https://medium.com/@ankitacode11/quantum-cryptography-key-exchange-and-encryption-b26036c558c8)
10. **Quantum Key Distribution (QKD): Secure Encryption Techniques**\
    [Link](https://medium.com/@ankitacode11/quantum-key-distribution-qkd-secure-encryption-techniques-31c6a736ce8e)
11. **SPHINCS+: A Comprehensive Guide to Post-Quantum Signatures in Blockchain**\
    [Link](https://medium.com/@ankitacode11/sphincs-a-comprehensive-guide-to-post-quantum-signatures-in-blockchain-7c6e0bbfd4aa)
12. **Introduction to Quantum Computing**\
    [Link](https://medium.com/@ankitacode11/introduction-to-quantum-computing-7da5f4691da1)
13. **Entanglement, No Cloning, and Quantum Parallelism**\
    [Link](https://medium.com/@ankitacode11/entanglement-no-cloning-and-quantum-parallelism-18cc801e633e)
14. **Quantum Algorithms: Unraveling the Power of Quantum Computing**\
    [Link](https://medium.com/@ankitacode11/quantum-algorithms-unraveling-the-power-of-quantum-computing-bde55ae641cd)
15. **Quantum Cryptography: Understanding the Basics of Quantum Information**\
    [Link](https://medium.com/@ankitacode11/quantum-cryptography-understanding-the-basics-of-quantum-information-959b2e7af06e)

#### Web3 Innovations & DeFi

1. **The Future of Self-Custody Wallets: Moving Trust Beyond the UI**\
   [Link](https://medium.com/@ankitacode11/the-future-of-self-custody-wallets-moving-trust-beyond-the-ui-2b4fb9325c21)
2. **Aave V3: Improved Lending, Liquidity, and Risk Management**\
   [Link](https://medium.com/@ankitacode11/aave-v3-improved-lending-liquidity-and-risk-management-1faf6f8b8928)
3. **Understanding Uniswap V3 Liquidity Pools: A Comprehensive Guide**\
   [Link](https://medium.com/@ankitacode11/understanding-uniswap-v3-liquidity-pools-a-comprehensive-guide-a5a4a9e32080)
4. **Unraveling Gas Fees: A Comprehensive Guide to Transaction Costs Across Blockchains**\
   [Link](https://medium.com/@ankitacode11/unraveling-gas-fees-a-comprehensive-guide-to-transaction-costs-across-blockchains-72509f649811)
5. **Zooko’s Triangle: Mastering the Art of Naming in a Decentralized World**\
   [Link](https://medium.com/@ankitacode11/zookos-triangle-mastering-the-art-of-naming-in-a-decentralized-world-b25c0631ff96)
6. **EIP-4844: Proto-Danksharding and Ethereum’s Scalability Leap**\
   [Link](https://medium.com/@ankitacode11/eip-4844-proto-danksharding-and-ethereums-scalability-leap-a11e6a1398e2)
7. **Ethereum’s Security: V, R, S in Digital Signatures**\
   [Link](https://medium.com/@ankitacode11/ethereums-security-v-r-s-in-digital-signatures-2ae1ef6d7093)
8. **Cardano CIP-1694 Upgrade and Trust Wallet Integration**\
   [Link](https://medium.com/@ankitacode11/cardano-cip-1694-upgrade-and-trust-wallet-integration-8c5de464edd7)
9. **The RIPs in Web3: Scaling Ethereum and Redefining NFTs**\
   [Link](https://medium.com/@ankitacode11/the-rips-in-web3-scaling-ethereum-and-redefining-nfts-7546e67795c3)
10. **Huff Unleashed: Advanced Optimization and DeFi Use Cases (Part 3)**\
    [Link](https://medium.com/@ankitacode11/huff-unleashed-advanced-optimization-and-defi-use-cases-part-3-bd9b91a2cfdb)
11. **Mastering Huff: Building Gas-Optimized Smart Contracts from Scratch (Part 1)**\
    [Link](https://medium.com/@ankitacode11/mastering-huff-building-gas-optimized-smart-contracts-from-scratch-part-1-6276104ccac5)
12. **How Vault Withdrawals Work in EulerSwap: Full Flow Explained**\
    [Link](https://medium.com/@ankitacode11/how-vault-withdrawals-work-in-eulerswap-full-flow-explained-7647e01d1f61)
13. **Unmasking Privacy: Coin Mixing and CoinJoins in Crypto**\
    [Link](https://medium.com/@ankitacode11/unmasking-privacy-coin-mixing-and-coinjoins-in-crypto-48b1964c1008)
14. **ERC-7484: Secure Module Registries for Modular Smart Accounts**\
    [Link](https://medium.com/@ankitacode11/erc-7484-secure-module-registries-for-modular-smart-accounts-559c0a871824)
15. **ERC-7579: Revolutionizing Modular Smart Accounts**\
    [Link](https://medium.com/@ankitacode11/erc-7579-revolutionizing-modular-smart-accounts-e97c53a31311)
16. **What Is RedStone (RED)? The Modular Oracle Network**\
    [Link](https://medium.com/@ankitacode11/what-is-redstone-red-the-modular-oracle-network-9b588baf00c9)
17. **Understanding Moonriver: The Ethereum-Compatible Parachain on Kusama**\
    [Link](https://medium.com/@ankitacode11/understanding-moonriver-the-ethereum-compatible-parachain-on-kusama-7aa7b959f46c)
18. **Chainlink’s Transformative Partnerships Revolutionizing Onchain Finance**\
    [Link](https://medium.com/@ankitacode11/chainlinks-transformative-partnerships-revolutionizing-onchain-finance-9d66a0c29c90)
19. **Mastering Restaking with KernelDAO (KERNEL): A Complete Guide to DeFi’s Next Big Thing**\
    [Link](https://medium.com/@ankitacode11/mastering-restaking-with-kerneldao-kernel-a-complete-guide-to-defis-next-big-thing-189be28ebf77)
20. **Native Bitcoin Integration: Unlocking DeFi and dApps with Blockchain’s Pioneer**\
    [Link](https://medium.com/@ankitacode11/native-bitcoin-integration-unlocking-defi-and-dapps-with-blockchains-pioneer-8074b793fa7c)
21. **What Is Nillion (NIL)? The Future of Secure Data Processing**\
    [Link](https://medium.com/@ankitacode11/what-is-nillion-nil-the-future-of-secure-data-processing-c89e17610812)
22. **Nexus Unveiled: The Operating Systems Powering Smart Accounts in Web3 and Enterprise Networking**\
    [Link](https://medium.com/@ankitacode11/nexus-unveiled-the-operating-systems-powering-smart-accounts-in-web3-and-enterprise-networking-b71c2ef1f9b6)
23. **Bubblemaps (BMT): Revolutionizing Blockchain Analytics with Visual Insights**\
    [Link](https://medium.com/@ankitacode11/bubblemaps-bmt-revolutionizing-blockchain-analytics-with-visual-insights-e15d6ea1ab37)
24. **Particle Network (PARTI): The Future of Chain Abstraction in Web3**\
    [Link](https://medium.com/@ankitacode11/particle-network-parti-the-future-of-chain-abstraction-in-web3-3d9218c294ba)
25. **Agglayer v0.2: Pessimistic Proofs Power a Multistack Web3 Future**\
    [Link](https://medium.com/@ankitacode11/agglayer-v0-2-pessimistic-proofs-power-a-multistack-web3-future-31969e5298cb)
26. **Introduction to Supertransactions**\
    [Link](https://medium.com/@ankitacode11/introduction-to-supertransactions-93f77a009dae)
27. **EIP-7702: Revolutionizing Ethereum Accounts with Seamless Integration into ERC-4337**\
    [Link](https://medium.com/@ankitacode11/eip-7702-revolutionizing-ethereum-accounts-with-seamless-integration-into-erc-4337-account-df1483314cc1)
28. **Quantum-Secure Blockchain Technology: Preparing for the Post-Quantum Era**\
    [Link](https://medium.com/@ankitacode11/quantum-secure-blockchain-technology-preparing-for-the-post-quantum-era-e70644e41611)
29. **Interoperability and Cross-Chain Solutions**\
    [Link](https://medium.com/@ankitacode11/interoperability-and-cross-chain-solutions-bd952fc44f28)
30. **ERC-6551: Revolutionizing NFTs with Token-Bound Accounts**\
    [Link](https://medium.com/@ankitacode11/erc-6551-revolutionizing-nfts-with-token-bound-accounts-ccd112cb8408)
31. **EIP-7702: Revolutionizing Ethereum Account Abstraction**\
    [Link](https://medium.com/@ankitacode11/eip-7702-revolutionizing-ethereum-account-abstraction-cb16401a1288)
32. **DAO Governance Models: Reshaping Organizational Structures in Web3**\
    [Link](https://medium.com/@ankitacode11/dao-governance-models-reshaping-organizational-structures-in-web3-5171128689c4)
33. **Understanding Web3: The Next Evolution of the Internet**\
    [Link](https://medium.com/@ankitacode11/dao-governance-models-reshaping-organizational-structures-in-web3-5171128689c4)
34. **Web3 Social Media: Can Decentralization Fix Online Privacy?**\
    [Link](https://medium.com/@ankitacode11/web3-social-media-can-decentralization-fix-online-privacy-ff9ab39205ce)
35. **Automated Market Makers (AMMs)**\
    [Link](https://medium.com/@ankitacode11/automated-market-makers-amms-38dca325d6d9)
36. **ERC-7806: Empowering Ethereum with Intent-Centric Smart Accounts and Native Yield Distribution**\
    [Link](https://medium.com/@ankitacode11/erc-7806-empowering-ethereum-with-intent-centric-smart-accounts-and-native-yield-distribution-38b303786ec5)

#### Blockchain Development & Tools

1. **Decoding Opcodes: The Heartbeat of Machine Code and Blockchain Execution**\
   [Link](https://medium.com/@ankitacode11/decoding-opcodes-the-heartbeat-of-machine-code-and-blockchain-execution-675d6ff58020)
2. **ERC-2335: A Simple Guide to Secure Key Management on Ethereum**\
   [Link](https://medium.com/@ankitacode11/erc-2335-a-simple-guide-to-secure-key-management-on-ethereum-420baa779276)
3. **Ditch .env Files for Good: Secure Key Management with Foundry**\
   [Link](https://medium.com/@ankitacode11/ditch-env-files-for-good-secure-key-management-with-foundry-ef0105c8bbc2)
4. **Understanding the Ethereum Virtual Machine (EVM): The Engine Powering Decentralized Innovation**\
   [Link](https://medium.com/@ankitacode11/understanding-the-ethereum-virtual-machine-evm-the-engine-powering-decentralized-innovation-3f0bdc7cbe41)
5. **Fuel Network: The Future of Scalable and Efficient Blockchain Execution**\
   [Link](https://medium.com/@ankitacode11/fuel-network-the-future-of-scalable-and-efficient-blockchain-execution-24e9df80c5d4)
6. **Deploying an NFT Contract on Polygon Network**\
   [Link](https://medium.com/@ankitacode11/deploying-an-nft-contract-on-polygon-network-f754b0a9db15)
7. **Create ERC721 NFT Collection with Pinata**\
   [Link](https://medium.com/@ankitacode11/create-erc721-nft-collection-with-pinata-4df1ad80aeaa)
8. **Solidity Development Using VSCode (Testnet: Sepolia, Mainnet: Polygon)**\
   [Link](https://medium.com/@ankitacode11/solidity-development-using-vscode-testnet-sepolia-mainnet-polygon-19c6bbcd2a60)
9. **Comprehensive Guide to Solidity Smart Contract Development**\
   [Link](https://medium.com/@ankitacode11/comprehensive-guide-to-solidity-smart-contract-development-d106d7051b07)
10. **Remix IDE: Browser-Based Solidity Development**\
    [Link](https://medium.com/@ankitacode11/comprehensive-guide-to-solidity-smart-contract-development-432f0247285c)
11. **EOF Suite in Solidity: A Major Evolution for the EVM (Part 2: Changes and Structure of EOF)**\
    [Link](https://medium.com/@ankitacode11/exploring-the-eof-suite-in-solidity-a-major-evolution-for-the-ethereum-virtual-machine-evm-07a8aec43c22)
12. **Ethereum Object Format (EOF): A Comprehensive Guide (Part 1: Introduction)**\
    [Link](https://medium.com/@ankitacode11/ethereum-object-format-eof-a-comprehensive-guide-3431ae9a05de)
13. **The Evolution of Package Managers: NPM, Yarn, PNPM, and Bun**\
    [Link](https://medium.com/@ankitacode11/the-evolution-of-package-managers-npm-yarn-pnpm-and-bun-cf16906ef37e)
14. **MongoDB Schema Design: Mastering Data Modeling Techniques**\
    [Link](https://medium.com/@ankitacode11/mongodb-schema-design-mastering-data-modeling-techniques-0319a3a3805b)
15. **Solidity 0.8.30 Release: What’s New and Why It Matters for Ethereum Developers**\
    [Link](https://medium.com/@ankitacode11/the-evolution-of-package-managers-npm-yarn-pnpm-and-bun-cf16906ef37e)
16. **Ethereum Pectra Upgrade: The Ultimate Guide to Smarter Wallets, Scalability, and Secure Key Management**\
    [Link](https://medium.com/@ankitacode11/the-evolution-of-package-managers-npm-yarn-pnpm-and-bun-cf16906ef37e)
17. **Migrating from SimpleHash to Alchemy: Seamless Transition for Web3 Developers**\
    [Link](https://medium.com/@ankitacode11/the-evolution-of-package-managers-npm-yarn-pnpm-and-bun-cf16906ef37e)

#### Blockchain Ecosystems & Cryptocurrencies

1. **What Is the Official Trump Meme Coin (TRUMP)? A Detailed Exploration**\
   [Link](https://medium.com/@ankitacode11/what-is-the-official-trump-meme-coin-trump-a-detailed-exploration-693084986841)
2. **Cryptocurrency Taxation Around the World in 2025**\
   [Link](https://medium.com/@ankitacode11/cryptocurrency-taxation-around-the-world-in-2025-03d475ad75fd)
3. **The Strategic Bitcoin Reserve: Revolutionizing National Wealth in the Digital Era**\
   [Link](https://medium.com/@ankitacode11/the-strategic-bitcoin-reserve-revolutionizing-national-wealth-in-the-digital-era-22d5352987dd)
4. **What Is Cryptocurrency and How Does It Work?**\
   [Link](https://medium.com/@ankitacode11/what-is-cryptocurrency-and-how-does-it-work-a25bfe19691c)
5. **Polkadot Blockchain: Detailed Exploration**\
   [Link](https://medium.com/@ankitacode11/polkadot-blockchain-detailed-exploration-77a26fff6414)
6. **Cryptographic Algorithms in Cardano Blockchain**\
   [Link](https://medium.com/@ankitacode11/cryptographic-algorithms-in-cardano-blockchain-8f7be72373e5)
7. **Solana Blockchain: Cryptographic Foundations and Architecture**\
   [Link](https://medium.com/@ankitacode11/solana-blockchain-cryptographic-foundations-and-architecture-ba8827f28108)
8. **Ethereum Blockchain: Cryptographic Algorithms and Hash Functions**\
   [Link](https://medium.com/@ankitacode11/ethereum-blockchain-cryptographic-algorithms-and-hash-functions-12de89a5730f)
9. **Cryptocurrencies of the Blockchain: A Comprehensive Guide to Digital Assets**\
   [Link](https://medium.com/@ankitacode11/cryptocurrencies-of-the-blockchain-a-comprehensive-guide-to-digital-assets-013367042fed)
10. **Blockchain: A Comprehensive Guide**\
    [Link](https://medium.com/@ankitacode11/blockchain-a-comprehensive-guide-79d6b2b38281)
11. **Cryptographic Algorithms in Blockchain Technology**\
    [Link](https://medium.com/@ankitacode11/cryptographic-algorithms-in-blockchain-technology-17a97e471de0)
12. **The GENIUS Act: How New U.S. Stablecoin Laws Are Reshaping Crypto for Everyone**\
    [Link](https://medium.com/@ankitacode11/the-genius-act-how-new-u-s-stablecoin-laws-are-reshaping-crypto-for-everyone-391fa36643ce)

#### GameFi & NFTs

1. **Unveiling GameFi Security: Common Threats and Robust Solutions**\
   [Link](https://medium.com/@ankitacode11/unveiling-gamefi-security-common-threats-and-robust-solutions-f93b71b07fc5)
2. **GUNZ (GUN): The Blockchain Gaming Revolution Unveiled**\
   [Link](https://medium.com/@ankitacode11/gunz-gun-the-blockchain-gaming-revolution-unveiled-c49e0f574d68)
3. **NFTs Beyond Digital Art: Exploring the Evolving Landscape of Non-Fungible Tokens**\
   [Link](https://medium.com/@ankitacode11/nfts-beyond-digital-art-exploring-the-evolving-landscape-of-non-fungible-tokens-3096ab43e48f)

#### Market Insights & Optimization

1. **The Psychology of Market Cycles: A Comprehensive Guide to Investor Behavior**\
   [Link](https://medium.com/@ankitacode11/the-psychology-of-market-cycles-a-comprehensive-guide-to-investor-behavior-22a51013e8bb)
2. **The Long Game of Crypto: How to Win Beyond the Hype**\
   [Link](https://medium.com/@ankitacode11/the-long-game-of-crypto-how-to-win-beyond-the-hype-ac66aba6b45b)
3. **AI-Driven Cost Optimization in Blockchain Networks: The Future of Efficient Decentralization**\
   [Link](https://medium.com/@ankitacode11/ai-driven-cost-optimization-in-blockchain-networks-the-future-of-efficient-decentralization-65bc3e6f6659)
4. **Deep Dive into Proof of Liquidity: Berachain’s Game-Changing Consensus Mechanism**\
   [Link](https://medium.com/@ankitacode11/deep-dive-into-proof-of-liquidity-berachains-game-changing-consensus-mechanism-0e95bb057112)

#### Blockchain Infrastructure

1. **ANALOG: The Bridgeless Future of Blockchain**\
   [Link](https://medium.com/@ankitacode11/analog-the-bridgeless-future-of-blockchain-1e5dcbc2f798)
2. **What Are Blockchain Relayers?**\
   [Link](https://medium.com/@ankitacode11/what-are-blockchain-relayers-cb4b8995e7fc)
3. **How Do Blockchain Relayers Reduce Gas Fees?**\
   [Link](https://medium.com/@ankitacode11/how-do-blockchain-relayers-reduce-gas-fees-7c137aeac066)
4. **Decoding Blockchain Transactions: A Comprehensive Guide to Transaction Hashes and Block Explorers**\
   [Link](https://medium.com/@ankitacode11/decoding-blockchain-transactions-a-comprehensive-guide-to-transaction-hashes-and-block-explorers-949029f852b9)


# 🌐 My Work

### Open-Source Contributions

**Zoriumorg Smart Contracts Library**

I actively contribute to the **Zoriumorg/smart-contracts-library-evm**, an open-source repository featuring a diverse collection of Solidity smart contracts for the Ethereum Virtual Machine (EVM). This library includes contracts ranging from basic utilities to advanced DeFi and governance solutions, designed to support developers building decentralized applications (dApps). All contracts are documented with detailed READMEs in the repository.

[🔗 Explore the repository: Zoriumorg/smart-contracts-library-evm](https://github.com/Zoriumorg/smart-contracts-library-evm/tree/main)

### Web Projects

I’ve contributed to the development of several web-based and blockchain projects, showcasing my skills in smart contracts, frontend development, and innovative technologies. Below are some of the websites and platforms I’ve worked on:

<https://www.tanthetaa.com/>

<https://www.wavebot.app/>

<https://promindholdings.com/>

<https://airein.io/>

<https://www.qsafewallet.com/>

<https://www.quranium.org/>

[Cresowallet](https://x.com/cresowallet?lang=en)

<https://oxablock.com/>

**YouTube Channel**\
I also create coding tutorials and blockchain development content on my YouTube channel:\
▶️ [CodeByAnkita](https://www.youtube.com/@codebyankita)

<https://github.com/codebyankita/solidity-smart-contract-course>

Visit these links to explore my projects, smart contracts, and tutorials.


# Ethereum Open-Source Contributions

### Ethereum.org | Official Documentation

**Type:** Documentation improvement\
**Scope:** Public Ethereum developer and user content\
**Contribution:** Submitted and merged updates to the official Ethereum.org website to improve clarity and correctness.

🔗 <https://github.com/ethereum/ethereum-org-website/pull/16832>

***

### Go-Ethereum (geth) | Client-Level Analysis

**Type:** Technical issue analysis and review\
**Scope:** Ethereum execution client behavior\
**Contribution:** Participated in technical discussion and issue analysis to assist maintainers in understanding and resolving client behavior.

🔗 <https://github.com/ethereum/go-ethereum/issues/32761#issuecomment-3344978620>


# 📞 Get in Touch

If you're interested in discussing potential collaborations, have any questions, or want to propose a project, don’t hesitate to contact me. I’m always open to new ideas and connections, and I’ll get back to you as soon as possible!

### 📧 Email

Email is the quickest way to reach me for both professional inquiries and general communication. Whether you're looking for support, collaboration opportunities, or just want to chat about blockchain technology, feel free to send me an email!

**Primary Email**: <ankitacode@gmail.com>\
✉️ Click to send me a message!

### 📱 Phone / WhatsApp

For real-time communication or urgent queries, you can reach me via phone or WhatsApp. I’m available during standard business hours and can accommodate calls or texts based on your convenience.

**WhatsApp Contact**: [Connect on Whatsapp](https://api.whatsapp.com/send/?phone=%2B917698448520\&text\&type=phone_number\&app_absent=0)\
📱 Available for calls and messages.

### &#x20;📲 Telegram

Join me on Telegram for quick chats about blockchain, smart contracts, or potential collaborations. I’m active and ready to discuss innovative ideas!

* **Telegram Handle**: [@ankitaeth](https://t.me/ankitaeth)
* 📲 Message me to connect in the blockchain community!

### 💼 LinkedIn

Let’s connect professionally! Whether you're looking to discuss business ventures, industry trends, or network within the blockchain space, I’d be happy to add you to my LinkedIn network.

**LinkedIn Profile**: [Connect on LinkedIn](https://www.linkedin.com/in/ankita-virani-4bb478282/)\
🔗 Click to join my professional network!

### 🖥️ GitHub

Explore my work on GitHub, where I contribute to open-source projects and share my code. I’m always open to collaborating on interesting development challenges or blockchain solutions.

**GitHub Profile**: [View my GitHub](https://github.com/CodeByAnkita)\
💻 Check out my repositories!

### 🌐 Farcaster (Wrapcast)

Connect with me through Wrapcast on Farcaster for a decentralized social experience. Let’s collaborate and share ideas across the blockchain ecosystem.

**Farcaster Profile**: Join me on Farcaster\
📡 Let’s connect via Wrapcast!

### 🐦 Twitter

Stay updated with my latest tweets, including project updates, announcements, and insights from my work in blockchain. Follow me on Twitter to stay in the loop!

**Twitter**: [Follow me on Twitter](https://x.com/anki_eth)\
🐦 Catch my latest updates!

### 🕒 Availability

I’m generally available to discuss new ideas, collaborations, or any technical questions. Feel free to reach out via email, phone, or any of the platforms listed above, and I’ll aim to respond within 24-48 hours.

**Business Hours**: Open to connect 24/7 for innovative blockchain ideas.\
📅 For urgent requests, WhatsApp or Telegram is recommended.

***

If you have any further queries or need more details, feel free to contact me through any of the listed methods. I look forward to connecting with you!


