0% found this document useful (0 votes)
76 views1,465 pages

Vyper and Python Smart Contracts on Blockchain – Full Course for Beginners [English (Auto-generated)] [DownloadYoutubeSubtitles.com]

This comprehensive 30-hour course, created by Patrick Collins, teaches blockchain software development from scratch using Python and Viper, catering to both beginners and experienced developers. The curriculum covers smart contracts, decentralized finance (DeFi), and AI-assisted development, providing hands-on tutorials and resources for effective learning. Participants will engage with a community for support and can expect to gain the knowledge necessary to become successful smart contract developers or security researchers in the web3 space.

Uploaded by

Spencer Xu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views1,465 pages

Vyper and Python Smart Contracts on Blockchain – Full Course for Beginners [English (Auto-generated)] [DownloadYoutubeSubtitles.com]

This comprehensive 30-hour course, created by Patrick Collins, teaches blockchain software development from scratch using Python and Viper, catering to both beginners and experienced developers. The curriculum covers smart contracts, decentralized finance (DeFi), and AI-assisted development, providing hands-on tutorials and resources for effective learning. Participants will engage with a community for support and can expect to gain the knowledge necessary to become successful smart contract developers or security researchers in the web3 space.

Uploaded by

Spencer Xu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1465

if you're interested in learning how to

write software that runs on a blockchain

distributed Ledger database this

comprehensive 30-hour course will teach

you everything from scratch using Python

and Viper even if you're a complete

beginner through Hands-On tutorials

you'll Master smart contracts Defi and

AI assisted development while learning

modern blockchain development practices

Patrick Collins created this course

Patrick is one of the most popular

blockchain instructors out there welcome

to the ultimate smart contract developer

security researcher full course and

platform python Edition this course this

set of videos is all you need to go from

where you are to successful smart

contract developer or security

researcher we have been doing this for

over four years now teaching the next

generation of smart contract developers

how to be successful on YouTube alone

our videos have over 6 million views

where we have both the number one and

number two most watched smart contract

educational content on the planet and

that doesn't even count the number of

viewers and users who watch and learn on

our education platform cyphon updraft


and we've taken all the learnings in

those years of doing this education wrap

them all up to make what you're

currently watching the best one yet this

one has a ton of ADV advancements in it

making it the most Cutting Edge web3

developer course period having made one

of these courses for the last four plus

years I've been reached out to by

countless developers who are now

full-time developers in the web 3 space

making a living doing well and

contributing to web 3 and there are

thousands that I have not met who have

left comments or left me notes and I

know we're going to do it again with

this video If you're looking to become a

web 3 solidity smart contract or

blockchain developer or any of those

terms this is the course for you and

this course is for anybody and everybody

no matter your blockchain or developer

experience level and additionally we're

going to be using artificial

intelligence to accelerate our learning

progress and I'm going to teach you not

only how to become a blockchain

developer but how to work with AI tools

to make you a 10x developer if you have


a little bit of developer experience

before this this course will be even

easier to get through but again don't

worry if you've never coded before and

for those of you who are already

familiar with blockchain and smart

contract development feel free to jump

around the different modules and

different sections and grab the

learnings that you want I promise

there's a lot of cutting edge

information in here and maybe you need a

brush up and when I say this course I

mean this path in its entirety if you're

watching this on YouTube this is just

one giant long humongous video watch

this all the way to the end to have the

highest chance of success for those of

you who are watching this on Cipher

updraft and you all should be you have a

buffet of choices of where to go but

don't worry I'm going to make picking

the choices incredibly easy for you so

no matter if you're brand new to coding

brand new to blockchain or you're an

experienced smart contract engineer

you're in the right place welcome to the

edge of the rabbit hole let's get froggy

for those of you who don't know me my

name is Patrick Collins I'm a smart


contract engineer security researcher

and just lover of all things web 3 I'm

one of the co-founders of the smart

contract auditing firm cyphon average

smart contract YouTuber and I live and

breathe smart contract development I

absolutely love web 3 blockchain and

smart contracts and I love the power and

the tools that they enable us to use but

not only that I love taking blockchain

developers like yourself watching this

video right now on the journey to

becoming a successful smart contract

developer I think the key to web 3 to

blockchain to cryptocurrencies being

successful is having a phenomenal

Foundation of developers so I'm

incredibly excited that you're here with

me and for those you who don't want to

become blockchain developers the first

two lessons of this course lesson zero

and lesson one are foundational pieces

of conceptual information

for you just to understand how to get

into this web3 thing so if you don't

want to become a developer just stop

once we get to the coding in any case

I'm incredibly excited for your journey

this is a data dump passion project of


all the knowledge that I've collected

over the past few years of working in

this industry and being a smart contract

developer myself and at this point I

have the track record to show that I am

100% confident that if you follow along

if you code along with us if you follow

me on this journey you will come out the

other side armed with the knowledge to

be a posit positive force for the

cryptocurrency and blockchain Industry

being here you have the opportunity to

be a Pioneer ushering in the age of web

3 of cryptocurrency Blazing the trail of

where this phenomenal industry has yet

to go like I said this isn't the first

time we've done this we've already

helped so many developers get into the

space and we're going to give you the

Cutting Edge most modern tools for

Industries like dii nfts Dows tokens

upgradeable smart contracts blockchains

and everything else that you can think

of once you finish this course it will

be abundantly clear what you want your

next steps to be and you'll have a ton

of Economic Opportunity at your

fingertips and opportunities to make a

huge difference in this amazing industry

however I can't just give it to you you


have to come with me on this journey you

have to take the step despite what you

might think you know cryptocurrencies

and smart contracts enable a more

accountable World a more transparent

World a more collaborative world a world

where promises can't be broken that's

the world that I want to live in we'll

teach you about the purpose of smart

contracts in section one of this course

and then later we'll teach you how to

build them so before we even get started

I want to give you a huge thank you for

even being here on this video and

listening and being interested in

engaging in this phenomenal technology

so thank you for being here and welcome

to the rabbit hole cuz we're about to

drop down with that being said let's get

frogy so let's begin our journey by

talking about some best practices that

way you can get the absolute most out of

this course and be as effective as

possible now you're either watching this

on cyphon updraft or on YouTube and I

encourage everybody to watch this on

cyphon updraft because we've got a ton

of features to make the learning

experience that much easier for you so


if you are watching this in Cypher up

trp though there's a couple links I need

you to be aware of the first one in the

top right is going to be the GitHub

resources page this will bring you over

to what's called a GitHub repo or a

GitHub repository or basic basally a

site that has all the code and all the

information and basically all the

materials that you're going to need to

learn everything in our curriculum you

could basically think of this as your

Bible for the duration of your

blockchain developer Journey

additionally in this GitHub there's a

discussions tab right here that you can

click on and in here is where you can

ask questions discuss with other people

taking the course interact with members

helping out and it's where you can

discuss anything that you're having

trouble with then on the other side

you'll see this tab called written

lessons if you cannot stand the voice

coming out of my mouth you can just flip

over to that and just read the course

curriculum as well if you prefer the

written content over the video content

and it's good to go over to the written

lessons anyways to maybe copy paste some


stuff if you scroll down here right now

it's blank but if anytime there's an

update to a video something's changed in

the video and we haven't swapped out the

video yet you'll see a little updates

section with information saying hey the

video says this but you should do this

instead now like I said this is a very

fast moving industry and sometimes

things change and sometimes things need

to be updated so when you're watching

one of these videos be sure to look for

the updates tab at the bottom and then

additionally whenever you're working

with the code that we're working with I

will give you a link to the finalized

Edition that you can use as a reference

as well to make sure that the code that

you're working with actually is going to

match what we are going to build

additionally if you think you found

something that is different or doesn't

quite work be sure to make a discussion

for it in that GitHub repo like I said

it's going to be your Bible additionally

there's a link to join the GitHub

discussions this is your platform to ask

questions and engage with the community

and learn with both other people taking


the course and also our Tas who are

going to be helping you out along the

way additionally there is a link to the

Discord for more realtime communication

I urge you to ask questions in the

GitHub discussions as well because those

are going to be indexed going to make

them much easier to Google search later

and have them show up as opposed to

Discord Discord is still phenomenal for

you to join them for those of you

watching on YouTube hello you should

scroll down to the description and in

the description are going to to be links

to these resources as well and

additionally a link to cyphon updraft if

you've been watching you've already seen

some of the advantages that cipon

updraft has including written lessons

single videos and there's also ways to

track your progress instead of having to

scrub on a giant YouTube video so for

all of you who are watching this on

YouTube definitely be sure to go over to

cyphon updraft sign up there and watch

the curriculum there because your

learning experience will be much better

but leave this video playing in the

background on YouTube so we get the bump

from the YouTube algorithm thank you


that being said as we go through this

course we're also going to teach you

some best practices on working with

artificial intelligence how to best

prompt these AI so that they can give

you the best results just keep in mind

they sometimes get things wrong and it's

a good idea if you are going to use an

AI to fact check it with a human or

another resource so be sure to say hi in

the discussions and maybe meet some

like-minded peers and additionally once

we do get to the coding portion of this

course it's a good idea to code along

with me as I'm explaining things so

having the video up as well as your

coding screen is a good idea so you can

follow along with me as I'm explaining

it if you're watching this on cyon

updraft you can just click the little

video pop out button and have the video

pop out as such en code next to it all

of this is to say if you run into an

issue jump to that GitHub repo and make

a discussion we will also be giving you

some tips very soon about how to best

make a discussion yes asking questions

to other human beings is a skill and

we're going to try to teach you to be


the most eff because asking well

formatted questions is not only the

secret to being a fantastic AI prompt

engineer but also becoming an incredibly

successful developer we're going to

learn how to ask well-formatted

questions and whenever we post on

discussions or forums or whatever we're

going to work on formatting them as best

as possible take breaks I cannot tell

you how many people have tried to rush

through these courses and be like Oh I'm

going to finish in a single weekend your

brain doesn't work like that your brain

needs time to absorb the information so

take breaks maybe every 25 minutes to a

half hour take a 5 minute break or maybe

you like working in longer chunks maybe

take a whole hour and then take a 15

20-minute break don't try to rush

through the whole video in a day you're

not going to retain the information go

outside go for a walk grab some ice

cream get some coffee go to the gym your

brain needs time to have the information

settled maybe every 2 hours just step

away maybe be done for the day work at

whatever Pace makes sense for you

everyone's going to have a different

learning pace there is no right speed


for this course I've had people take my

courses in 2 weeks in 3 months in 6

months it doesn't matter pick a pace

that you can do and stick to it not only

work at your pace make sure that I'm

talking at a pace that makes sense for

you there's a little gear icon in the

YouTube video here where you can change

the speed of how I'm talking and how

fast the video is going so if I'm

talking way too fast for you then you

can slow me down but if I'm talking too

slow then you can speed me up and if

you're watching this on cphon updraft

you have the same dials as well in the

bottom right hand corner additionally if

English isn't your native language we

have seven different subtitles in the

cyphon updraft video player as well so

make the adjustments you need to make me

go the speed you want me to go and of

course this course is modular so you can

Bounce Around topic to topic and go to

where you want to go if you don't want

to do any full stack stuff then skip

that section if you want to go right to

the advanced stuff do that like I said

go the pace and take the learnings that

you want to do and after every lesson it


might be a good idea to go back and

reflect on each lesson to really make

sure the knowledge gets ingrained

repetition is the mother of skill and

we're going to be repeating a lot of

smart contract development now the last

bit here is in the cyphon updraft

platform we're going to have quizzes

that you can take to help see if you

learn the knowledge that you were

supposed to learn if you're watching

this on YouTube you don't have that so

go sign up for cyphon updraft and then

play the YouTube video in the background

so the YouTube algorithm bumps us up but

additionally at the end of every section

if you go to the GitHub repo associated

with that section and you scroll down

there's going to be a bonus nfts section

with a link this will bring you to a

coding Challenge on chain that you can

actually solve to Mint yourself in nft a

badge of honor proving that you gained

the knowledge that you were supposed to

these are optional challenges that you

can do to try to make sure that you

actually learned what was meant to be

learned here and if you do solve them

you get a very cool nft along with it

don't know what an nft is don't worry


we'll teach you later blockchain

development and open source development

world is incredibly collaborative so be

sure to use tools like of course the

GitHub discussions tab ethereum stack

exchange the decentralized Q&A Forum

piranha issues on different

githubschool

Works knowing where to go for

information and how to collaborate with

people is often more more important than

your smart contract knowledge because

often times you're going to run into

issues you don't know how to solve so

we're going to teach you to unblock

yourself on this and really anything in

life plus syncing with other people in

the space makes it way more fun now

before we can actually get to coding we

need to understand how the blockchain

even works what the purpose of these

smart contracts even are and this is

essential to becoming a successful smart

contract developer because a technology

is really just a solution and a solution

is only as good as the problem is so we

need to make sure we understand the

problem really well so we know how to

attack it with this smart contract


technology and the better you understand

the smart cont technology the better

you'll be able to architect your smart

contracts in the future and make really

intelligent really powerful systems that

further this amazing industry but if you

already know the basics of blockchain

feel free to jump into lesson two and

skip over lesson one so those are some

of the best practices to be really

successful with this course but with

that knowledge you're now standing at

the edge of the rabbit hole and if

you're like me once you jump in you'll

just want to keep going deeper and

deeper I'm so excited for you to embark

on this journey with us and I'm looking

forward to seeing you on the other side

just like the thousands of other

developers who have taken these courses

and have emerged the other side

triumphant so it all starts with

blockchain Basics let's get

froggy now throughout this course you

will see a number of different guest

lecturers who are going to be giving you

this information we work with some of

the best people in the industry to give

you this information for lead

instructors I've already introduced


myself but just to reiterate my name is

Patrick Collins and I will be the lead

instructor for the majority of your

journey on cyphon updraft but it's not

just me who helps out creating the

curriculum here I'd like to also

introduce our co-lead instructor Kira

Nightingale I will let her go ahead and

introduce herself just a brief interlude

from Patrick to say hi and introduce

myself my name is Kiera Nightingale and

I am a developer relations and engineer

at cyphon and I love all things smart

contract engineering and I'm going to be

helping Patrick out with creating

content for you guys to become the best

smart contract engineers in the world so

if you see my face now and again not to

be concerned cuz now you guys know who I

am and with that said back to Patrick so

don't be too surprised if you see her

face popping up from time to time and

with that let's

continue now for you developers who are

going to be going on to the solidity

Basics and Foundry fundamentals or Viper

or any of the other courses we are

additionally going to be teaching you

how to deploy to an L2 called ZK sync at


the time of recording there are a couple

of differences that make deploying to ZK

sync slightly different from deploying

to ethereum but we imagine that in the

future we won't need these couple

differences as ZK sync matures we

imagine that the differences will become

fewer and fewer Kira will teach you more

about l2s and how they work in a future

lesson and in our best practices section

we talked about different challenge

contracts that you can go out and you

can solve to win an nft and it's on ZK

sync where these challenge contracts are

going to be deployed Kira will go over

why ZK sync is such a phenomenal layer 2

rollup and additionally we want to give

a massive thank you to matter labs and

the ZK sync team for being the lead

sponsor of cyphon updraft it's thanks to

their sponsorship and their dedication

to making web3 developer and security

research education accessible that we

are able to bring this course completely

free to all of you so you can help

support them support us by looking to

deploy to their chain now we of course

think closures are very important so

anytime we work with a sponsor we will

have a list of them in the sponsor


section of the GitHub repo associated

with this course and additionally we

will also give you Alternatives as well

so that you can use the technology that

is correct for you we also want to give

a thank you to arbitrum and optimism who

historically have also donated to cyphon

updraft now as of recording there are a

few scenarios where if you're looking to

deploy a real live professional smart

contract to ZK sync it might be a little

extra challenging so we have a file in

the GitHub repo associated with with

this course that we recommend that you

take a look at before you deploy a

production smart contract to ZK sync in

the future of course since you're

watching this right now this probably

doesn't apply to you but in any case a

huge thank you to ZK sync and the matter

Labs teams for helping sponsor cyphon

updraft K will tell you more about why

they are a really cool layer to and

we're looking forward to seeing what

cool smart contracts you deploy to ZK

sync

now since you're here you've probably

heard of Bitcoin before Bitcoin was one

of the first protocols to use this


revolutionary technology called

blockchain the Bitcoin white paper was

created by the pseudo Anonymous Satoshi

Nakamoto and it outlined how Bitcoin

could make peer-to-peer transactions in

a decentralized network this network was

powered by cryptography and decentral

and allowed people to engage in

censorship resistant Finance in a

decentralized manner due to its features

which we'll talk about in a little bit

people took to this as a superior

digital store of value a better store of

value over something like gold for

example and that's why you'll also hear

people commonly refer to it as a digital

gold similar to Gold there's a scarce

amount or a set amount of Bitcoin

available on the planet only so much

that you can buy and sell you can read

more about the original Vision in the

white paper we have a link to the white

paper in the GitHub repo associated with

this course now this was an insane

breakthrough and a little bit we're

going to learn exactly how this is all

possible and how this actually works

under the hood some people though saw

this technology and wanted to take it a

little bit farther and do even more with


this blockchain technology and a few

years later a man named vitalic butterin

released a white paper for a new

protocol named ethereum which used this

same blockchain infrastructure with an

additional feature and in 2015 him and a

number of other co-founders released the

project ethereum where people could not

only make decentralized transactions but

decentralized agreements decentralized

organizations and all these other ways

to interact with each other without a

centralized intermediary or centralized

governing Force basically their idea was

to take this thing that made Bitcoin so

great and add decentralized agreements

to it or smart contracts and in fact

technically these smart contracts

weren't even really a new idea back in

1994 a man named Nick Zabo had actually

originally come up with the idea smart

contracts are a set of instructions

executed in a decentralized autonomous

way without the need for a third party

or centralized body to run them and they

come to life on these blockchains or

these smart contract platforms like

ethereum and it's these smart contracts

that are going to be the core thing that


we're going to be working on in this

course and that we're going to be

developing you can think of smart cont

contracts in the same way you think of

traditional contracts or traditional

agreements they're just a set of

instructions between parties except

instead of written on pen and paper or

typed up in Microsoft Word they are

written in code and embodied on these

decentralized blockchain platforms and

that's also where they're executed

instead of being executed by the two

parties or three parties or however many

parties that are involved this removes

this centralized issue that we'll talk

about more in a bit this is one of the

main differentiators between the

ethereum protocol and the bit Bitcoin

protocol it's these smart contracts now

technically Bitcoin does have Smart

contracts but they're intentionally

touring incomplete which means they

don't have all the functionality that a

programming language would give them

this was an intentional move by Bitcoin

developers Bitcoin developers viewed

Bitcoin as a store of value versus

ethereum developers viewed ethereum as

both a store of value and a utility to


facilitate these decentralized

agreements now these smart contracts on

blockchains alone are absolutely

incredible however they do come with a

huge issue if we want these digital

agreements to replace the agreements in

our everyday lives they probably are

going to need data from The Real World

blockchains by themselves actually can't

interact with and can't read or listen

to data from The Real World this is

what's known as the Oracle problem these

blockchains are deterministic systems

and they're deterministic on purpose and

we'll learn about more about how that

works in the sessions to come so

everything that happens with them

happens in their little world but if

they're going to be these agreements

they need external data and they need

external computation and this is where

oracles come into play oracles are any

device that delivers data to these

decentralized blockchain or runs

external computation however if we want

our applications to stay truly

decentralized we can't work with a

single Oracle or a single data provider

or a single Source that's running these


external computations so we need a

decentralized Oracle Network similar to

our decentralized blockchain Network

your onchain logic will be decentralized

but you also need your offchain data and

computation to be decentralized

combining this onchain decentralized

logic with this offchain decentralized

data and decentralized computation gives

rise to something called hybrid smart

contracts and most of the biggest

protocols that we interact with today

are some type of hybrid smart contract

or interact with hybrid smart contracts

to some extent this is where the

protocol chain link comes into play it

is a modular decentralized Oracle

Network that can both bring external

data and external computation into our

smart contracts to make sure they're

decentralized end to end while giving

them the feature richness that we need

for our agreements chain link allows for

us to get data do upkeeps get random

numbers or really customize our smart

contracts in any meaningful way now

throughout the course we're going to use

the terminology smart contract however

whenever we say smart contract we're

often using it a little interchangeably


with hybrid smart contracts but just

know that when when we say hybrid smart

contract we're talking specifically

about smart contracts that have some

type of offchain component now since

ethereum's released a number of

different blockchains or smart contract

platforms have come to light such as

Avalanche polygon Phantom Harmony and

more for the majority of this course

we're going to be assuming that we're

going to be deploying to the ethereum

network however everything that we learn

here is going to be applicable to the

vast majority of the blockchains out

there like polygon Avalanche Phantom

Harmony Etc and understanding everything

from ethereum fundamentals will give you

the skills that you need to switch

chains very easily with literally one

line of code so don't worry about

learning a specific tool or with a

specific chain because most of them work

together seamlessly now there are a

couple of smart contract platforms that

don't use solidity but still learning

the fundamentals here will make you much

better at those as well and ethereum by

far has the most value locked and is the


most used blockchain and smart contract

platform out there you'll also hear

those two terms used a little bit

interchangeably as well sometimes I'll

say smart contract platform sometimes

I'll say blockchain they kind of mean

the same thing obviously blockchains

could mean store of value and smart

contract platform but you get the idea

similarly chain link is the most popular

and Powerful decentralized Oracle

network is the one that we're going to

be focusing on for this course as well

chain link is also blockchain agnostic

so it'll work on ethereum Avalanche

polygon salana or really any other

blockchain out there now additionally

over the last year a new term has come

to light called an L2 or a layer two

this solves an issue that most

blockchains see where they don't scale

very well or they don't grow big very

well we'll be talking about l2s a little

bit more in the future but the basic

concept of is that blockchains can

really only get so big so what they do

if if this is ethereum you can actually

have blockchains hook into them to

essentially make them bigger if that

doesn't really make too much sense don't


worry about it for right now layer 2os

solve this scale avability issues and at

the moment there are two different types

of true layer 2s optimistic rollups and

zero knowledge Roll-Ups optimistic RS

like arbitrum and optimism or zero

knowledge RS like ZK sync or polygon ZK

evm yes there's a polycon chain but

there's also a polycon z k evm L2 the

two of them are very different don't

worry about them for now but like I said

once we learn how blockchains work from

a basic Level under the hood then we'll

explain more about how these l2s

actually work now throughout this course

you'll hear the term dap or

decentralized protocol or smart contract

protocol or decentralized application

and they all kind of mean the same thing

a decentralized application is usually

the combination of many smart contracts

and when we get into solidity you'll see

what a singular smart contract really

looks like and like I said learning all

these core fundamentals will make you a

better solidity and a better smart

contract developer you'll also hear the

term web 3 a lot in this video and in

the industry web 3 is the idea that


blockchains and smart contracts are the

next iteration of the web web one being

this permissionless open-source world

with static content web 2 being the

permissioned web with Dynamic content

but all the agreements and logic runs

off of centralized servers where they

control your information and then web 3

comes back to the permissionless web but

once again with Dynamic content and

instead of centralized servers running

your logic decentralized networks run

the logic creating these censorship

resistant agreement M ments that these

smart contracts enable it is also

generally accompanied by the idea that

the users own the protocols that they

work with and it's an ownership economy

you'll see what I mean later in this

course now we've talked a lot about the

history and about the high level of

these protocols and of these smart

contracts and what they can do but what

do these smart contracts really mean

what is it when I say trust minimized

agreements or unbreakable promises what

is the real value ad of these smart

contracts before we look under the hood

and take a peek at how this all works

from a technical standpoint let's learn


what all the value of this is what is

the purpose of us building all these

Technologies of you taking this course

what problem does this technology solve

in my mind a technology is really only

as good as the problem that it solves if

it doesn't solve a problem then why

bother smart contracts blockchain web 3

cryptocurrencies those are all just

different words that encapsulate the

idea of what we're doing in such a

unique Paradigm I think the easiest way

to sum up what these smart contracts do

is that they create trust minimized

agreements and if you might be

scratching your head to that a much

easier way to think about it is just

they give rise to Unbreakable promises

Yes you heard that right unbreakable

agreements and Promises additionally

they give rise to speed efficiency and

transparency and a number of other

things I made a video pretty recently

about exactly this let's dive in and

take a listen to the purpose the

undeniable value of smart contracts

cryptocurrencies fundamentally Rel

landscape markets and agreements as we

know them unfortunately you've probably


only been bombarded with people

screaming about nfts and money now some

of the memes are fun but let's forget

the and get down to the essence

of this space if you're already in web 3

this is the video to send to your

friends to explain why you're so excited

about this space and explain why we're

here and then if you're not into crypto

you've come to the right place and yes

there are fun memes and markets and

there's some money stuff and there all

these things but outside of all that the

purpose of blockchains relates to the

ageold elementary school unbreakable

promise the pinky swear let's get froggy

nearly everything you do in life is the

result of an agreement or a contract

your chair was a result of an agreement

to buy and sell lumber to assemble and

sell the chair to a retailer on Amazon

then you made an agreement to buy the

chair for $40 the lights in your house

are powered by electricity which is an

agreement from you and the electric

company you agree to pay them in return

they'll keep the lights on the

electricity that they generate is

agreements between them and Engineers

who built turbines to generate the


electricity with insurance you agree to

pay some amount of money to them every

month and in return they will do nothing

or I mean they'll cover your medical

bills almost everything you do and

everything you interact with is the

result of some form of agreement or

contract in some aspect now agreements

and contracts can feel kind of abstract

and boring to really grasp on to so to

simplify we can also refer to them as

promises when you get an oil change

they're promising that they will

Faithfully change your oil in exchange

for money when you put money in the bank

they promise to keep it safe in exchange

for them to use your money to give out

loans when you buy a lottery ticket the

lottery promises to give you a fair

chance at winning a ton of money in

exchange for you buying the ticket

whenever you make one of these

agreements in a way you're asking them

to pinky swear to not screw you over and

to treat you fairly but this doesn't

always happen let's look at a real world

example Le of someone breaking the pinky

swear back in the ' 80s and 90s

McDonald's ran a promotion for people to


win money by collecting McDonald's

Monopoly game cards the idea was simple

you buy McDonald's in return you get a

chance to win $1

million you can imagine McDonald's

literally going hey everybody I promise

if you buy our MC food and McNuggets

we'll give you a fair chance of winning

this

money but they ended up breaking This

Promise instead of having a fair chance

of winning your chance was in fact zero

in the mid90s between 13 and $24 million

went into the pockets of not people

playing the game honestly but a group of

corrupt insiders who had rigged the game

meaning that when you played the

McDonald's Monopoly game you were buying

into a set of lies and promises that

were 100% always going to be broken and

the thing is it doesn't really matter if

this was McDonald's fault or not they

were the ones making the promises that

they ultimately could not keep another

way you can think about it is that

that's $24 million that they essentially

stole from you and I now if this system

was deployed on a blockchain with

something called a smart contract it

would have been impossible to defraud


this $24 million due to Smart contracts

being immutable decentralized and

transparent but I'll get back to that in

minute in all the agreements and

contracts we make imagine making a pinky

swear with a 10-year-old and imagining

how that agreement would hold up hey

buddy could you could you please keep my

money safe you can play with if you like

but just just please have it when I come

back immediately you might get that

worrying feeling in your chest something

might go wrong that this 10-year-old

might lose your money you might be

thinking how could I trust them will

they break their promise and this

feeling of I can't breathe because of

untrustworthy situations happens to us

all the time can I trust this used car

salesperson to give me a good car can I

trust this tag that says machine

washable or will it make my shirt shrink

will my insurance provider break their

promise of covering my medical bills

when I get hit by a bus when Patrick

promises he'll go on a hike with me will

he actually yes I I I actually will the

issue with our current agreements and


contracts is we have to trust the people

who are making them to do the right

thing however often they're actually

incentivized to not do the right thing

insurance doesn't want to pay out money

sometimes salespeople just want to get

the off their shelves and with my

girlfriend I promis to go on a hike but

I hate hikes where else has this

happened now you might be thinking okay

Patrick this seems cool but like where

has this actually affected me well the

McDonald's Lottery that we just spoke

about above during the Great Depression

with the run of the Banks Banks promis

to keep our money safe and that when we

went back to go get it they would

actually have the money there and well

and behold there were times that they

didn't have the money there just last

year Robin Hood painted this amazing

picture come use our application we will

give you access to the markets we

promise we will give you a retail

investor a fair chance of interacting

with the world of Finance

psych but not this asset this asset this

asset or this asset the 2008 financial

crisis remember that shady deals behind

closed doors combined with lies about


financial product brought the world to

its economic knees how are youing us

hyperinflation in Zimbabwe

hyperinflation in Brazil fairs history

is a Relentless lesson of trustworthy

entities being notorious promise

Breakers we finally have a way to fix it

with smart contracts now before I jump

into smart contracts a lot of people

might be thinking hey cool and all

however we have systems in place to

protect against a lot of these things

which is true and which is great and

that is a very helpful step forward but

these systems often break ones in 2008

definitely didn't work the ones with the

Robin Hood crisis definitely didn't work

and even if these systems apply and you

go to court to try to work them out

maybe you're in court for years before

you actually see a resolution and by

that time what you needed the money for

is long gone so what is this technology

what is this tool tool that can fix this

fundamental problem in our agreements

today this tool is smart contracts and

this tool is what the blockchain was

built for now I'm going to give you a

quick overview of what a smart contract


is however I'm leaving some links in the

description for more in-depth

explanations but the basics of them is a

smart contract is an agreement contract

or a set of instructions deployed on a

decentralized blockchain and once the

contract or set of instructions is

deployed it cannot be altered it

automatically executes and everyone can

see the terms of the agreement the real

basics of it is that the code is

executed by a decentralized collective

like a group of people but a group of

people running a certain software this

means that no one person or entity can

actually alter any of these agreements

or change the terms of the arrangement

in these traditional agreements whoever

owns the contract whoever owns the

execution of the contract can flip a

switch and say we're not going to do

that anymore in smart contracts in web 3

in blockchain you no longer can do that

typically smart contracts are in a

decentralized blockchain and used in

combination with a decentralized Oracle

Network to get the real world assets and

information and if these words sound

like I'm Conjuring up a magic spell well

again check the links in the description


if you want to learn more about the

technical implications if you're not a

technical person and you're not

interested in getting to the NR you can

kind of think of it like https I bet the

vast majority of you don't even know

what https stands for and yet you use it

every single day whenever you lock onto

the internet so how does this fix the

McDonald's Monopoly issue in its

tradition form the lottery was executed

behind closed doors somebody operated

and owned the code and the contracts and

the agreements that ran the lottery and

they had the power to alter it and

nobody other than the people internal on

the lottery could audit this altering

happening now if the code for this

Lottery was deployed onto a blockchain

every time a hacker attempted to alter

it everyone would be notified not only

that but you couldn't even alter it

because the terms of a smart contract

cannot be altered once deployed combined

that smart contract with a chain link

vrf Oracle to get a verifiably random

number and Presto you now have a

perfectly decentralized unalterable

agreement that is impossible to hack


commit fraud or manipulate we have just

saved the public between 13 million and

$24 million just by fixing the issue of

trust how does this fix Robin Hood well

the problem with Robin Hood is already

fixed right again the problem is that

there's a centralized body that can flip

a switch at any time and say yeah can't

access these markets anymore we're

breaking our promise of actually giving

you access to the markets this is

already fixed with something called

decentralized exchanges and these exist

today one of these exchanges is one

called Unis swap you can swap erc20

tokens which are kind of the equivalent

of stocks but some aren't some are it's

a little confusing I won't get into that

here either but it doesn't have that

centralized body that can flip a switch

and ruin access to the markets and had

these investors been on a decentralized

exchange it would have saved them

hundreds of millions of dollars and it

would have prevented fraudulent Market

manipulation how does it fix run of the

banks with transparency built in and

automated solvency checks you can build

a bank like smart contract that has

insolvency checks built in that make it


impossible to get there insolvent means

broke as any agreement or any history

lesson where there was a trust

assumption that was broken smart

contracts can be applied to and should

be applied to especially in a time where

big money runs owns and controls

everything we desperately need to move

to a world where some self-interested

centralized entity can't flip a switch

and ruin people's access to the services

that they need we can move away from a

world that is brand-based to a world

that is math-based right now if you

interact with a service that you don't

like or that they break their promise

the only thing you can do is walk down

the street to the next service that's

going to make the same set of promises

and you have to hope and pray that

they're actually going to keep it we can

move from that to world where we can

just look at the math and say oh okay 1

+ 1 equal 2 this is what this agreement

is going to do for me every single time

guaranteed because it's a decentralized

autonomous agent has no incentive to be

evil and everything is transparent and

out in the open prob a big company and


if it was better for me for 1+ 1 to

equal three maybe I would go behind some

closed doors and fudge some numbers and

come back out and be like hey 1 + 1

equal 3 but with smart contracts that's

impossible doing the right thing is

infrastructural now given the choice

between two agreements one where you

have to trust a single centralized

entity that they're going to do the

right thing for you versus a

decentralized untable collective which

one are you going to choose I'm picking

the one that can't screw me over every

single time for every agreement I can

apply it to now this technology is

relatively new but we have already seen

it Rel landscape entire markets and

continue to do so the traditional

Financial world is already getting its

lunch eat by defi or decentralized

Finance there's already over $200

billion doll of people's money in these

protocols to help have a more fair more

accountable more transparent Financial

system this D5 movement is one of the

main reasons I got into the space

because we desperately need to move away

from where we are right now and end

people's chances for wealth being sucked


up by some group that's bending the

rules in their favor and smart contracts

are our ticket to that better World more

and more Industries are also coming over

to Smart contracts and blockchain

because of all the Innovations and

because of all the advantages that it

has as we grow and as we get better we

get closer to this vision of having this

concept fulfilled trust minimized

agreements these smart contracts are

minimizing the trust that we need to

give other people in order for these

agreements to be executed if trust

minimized agreements is too confusing

for you just say unbreakable promises

now I got to be honest with you guys

blockchains and smart contracts and

cryptocurrencies can actually do more

than just trust minimized agreements

what they have Security benefits uptime

benefits execution speed benefits and a

whole lot more but it's a lot easier to

just learn about one and learn the other

ones later right it's kind of like

sprinkles on top so this is why we are

here this is why we're building this

future and this is why we are so excited

about
it last year 2022 there were a lot of

issues with a couple different companies

like for example spfs FTX platform the

thing to me that's most frustrating

about that situation is that FTX

platform was wasn't anything that I just

talked about it wasn't decentralized it

wasn't trustless it wasn't transparent

it was purely a traditional web to

company pretending to be web 3 and just

using the cryptocurrency part of web 3

but not actually using the smart

contracts and we're doing a much better

job as a community getting rid of the

Bad actors and this is something that's

incredibly important for you when

working with protocols and when building

protocols I want you to be incredibly

successful here but I want you to be

incredibly successful because you're

making a ton of value a lot of these

platforms that we saw collapsing last

year were not creating value they were

stealing value they were siphoning value

they were faking having value and as you

learn and as you build smart contracts

yourself it'll start to become innately

aware of what protocols and what

companies are centralized and are not

the ethos of web 3 and the ones that are


we are building verifiable trust

minimized agreements unbreakable

promises and if you can't verify those

promises then it's not trust minimized

it's not web 3 it's not what this

industry is for that's what I want you

to do as you finish this course is be a

force for good unfortunately because a

lot of people haven't taken my course

not everybody understands the difference

between a legitimate project and a token

that's just meant to pump somebody's

bags as this space continues to grow and

as people like yourself take courses

like this we will get to continue to

push real legitimate projects forward

and wash out the projects that aren't

actually contributing

even in just this introduction part

we've learned a ton so let's do a quick

summary of what we've learned so far

Bitcoin was the first protocol to take

this blockchain technology into the

Limelight and take these

cryptocurrencies into the mainstream

Bitcoin is a sort of digital gold or a

store of value able to make transactions

between users in a decentralized manner

ethereum and other smart contract


platforms take this blockchain

technology one step further enabling

people to make smart contracts and

decentralized trust minimized agreements

these smart contracts and decentralized

applications can access and interact

with the real world using something

called decentralized Oracle networks

chain link is a decentralized network

that allows us to build these hybrid

smart contracts which combines our

onchain logic with our offchain

decentralized data and decentralized

computation giving rise to our logic

being completely decentralized and our

data and external computation being

completely decentralized giving us all

the features that traditional agreements

and traditional contracts have now these

digital currencies like ethereum and

Bitcoin have value even without the

smart contract part having a censorship

resistant decentralized store of value

is measurably powerful in its own right

we have some links in the GitHub

repository that'll teach you how this

decentralized store of value flips

traditional Finance on its head and it's

another one of the great reasons for

building smart contracts but again the


easiest way to boil it down is trust

minimized agreements or unbreakable

promises

but let's also go into some of these

other features that smart contracts have

over our traditional environment the

first feature of course is that they are

decentralized and they have no

centralized intermediary the different

individuals that run one of these

blockchains are known as node operators

and it's the combination of all these

thousands of node operators running the

same software running these algorithms

running these smart contracts that make

the network decentralized we'll dive

deeper into how that works later the

next feature is transparency and

flexibility in these decentralized

networks since all these individual node

operators run this software everybody

can see everything that's happening on

chain meaning there's no Shady deals

there's no weird things happening

anything that's going to be unfair

people would be able to see and just not

use everybody has perfect information

and has to play by the same rules now

additionally this doesn't mean that


there's no privacy the blockchain is

pseudo Anonymous meaning that you aren't

necessarily tied to and identity in real

life they also have the feature of speed

and efficiency for those of you who have

ever tried to do a bank transfer or send

money across Seas you know it sometimes

can take two to three weeks when in fact

all these banks are really doing is

basic math they're subtracting money

from your balance and adding it to some

other balance why does it take so long

in the blockchain all of these

transactions happen instantly another

instance for those in the financial

world today know that clearing houses

and settlement days can take a long time

in the blockchain there's no need for

any of that because they happen

instantly this obviously is much quicker

but it also makes for much more

efficient interactions with each other

security and immutability again

immutable means that it can't be changed

once a smart contract is deployed that's

it whatever is in the code is going to

be in the code Forever they cannot be

altered or tampered with in any way this

means that the security is much easier

whereas in a centralized World somebody


can hack into the server jump out the

database and change some numbers you

can't do that in the blockchain world

and since it's decentralized in order to

hack the blockchain you'd have to take

over half of the nodes as opposed to in

the centralized world where you only

have to take over one in the regular

world if your computer and your backup

computer go down all of your data is

gone in the blockchain world if your

computer and your backup computer go

down all your data is safe because it's

being run on all these other

decentralized nodes and even if a few

hundred nodes or if a few thousand nodes

go down it doesn't matter because as

long as one node has a copy of the

blockchain you're good to go hacking a

blockchain is nearly impossible and

Leaps and Bounds more difficult than

hacking a centralized server not only

that but this is safer in the asset

sense as well all you need to access

your credentials and your information

and your assets is your private key

which is basically your password for all

of this and as we've discussed in the

video these smart contracts remove this


counterparty risk remove this

centralized intermediary remove these

trust gateways that we have to do in web

2 when we engage with users and

individuals they don't always have our

best interests at heart smart contracts

remove this counterparty risk because

once one of these contracts is created

they can't go in and they can't alter it

and they can't let greed or ego or

anything else get the better of them and

alter the terms of the deal and as we

said this gives rise to these trust

minimized agreements or these

programmatic unbreakable promises we

move away from brand based bed

agreements to math-based agreements

where we can look at the cryptography we

can look right at the code and see

exactly what something is going to do

and how it's going to execute versus

having to rely on a human being doing

the right thing with smart contracts and

decentralized hybrid smart contracts

doing the right thing is infrastructural

all these pieces boil down to us having

the freedom to interact the way we want

to interact without having to be afraid

that interacting like that is going to

screw us over this trust minimized piece


these unbreakable promises make

interactions so much better in the

purely web 2 world we're constantly

bombarded with messages of projects and

protocols pushing us to move or act in

the direction that makes them more

profitable versus in the smart contract

space we can see everything

transparently and we can even engage in

interact and be partially owners of the

protocols and the interactions that we

decide that we want to be a part

of but let's also go into to some of

these other features that smart

contracts have over our traditional

environment the first feature of course

is that they are decentralized and they

have no centralized intermediary the

different individuals that run one of

these blockchains are known as node

operators and it's the combination of

all these thousands of node operators

running the same software running these

algorithms running these smart contracts

that make the network decentralized

we'll dive deeper into how that works

later the next feature is transparency

and flexibility in these decentralized

networks since all these individual node


operators run this software everybody

can see everything that's happening on

chain meaning there's no Shady deals

there's no weird things happening

anything that's going to be unfair

people would be able to see and just not

use everybody has perfect information

and has to play by the same rules now

additionally this doesn't mean that

there's no privacy the blockchain is

pseudo Anonymous meaning that you aren't

necessarily tied to an identity in real

life they also have the feature of speed

and efficiency for those of you who have

ever tried to do a bank transfer or send

money across Seas you know it sometimes

can take 2 to 3 weeks when in fact all

these banks are really doing is basic

math they're subtracting money from your

balance and adding it to some other

balance why does it take so long in the

blockchain all of these transactions

happen instantly another instance for

those in the financial world today know

that clearing houses and settlement days

can take a long time in the blockchain

there's no need for any of that because

they happen instantly this obviously is

much quicker but it also makes for much

more efficient interactions with each


other security and immutability again

immutable means that it can't be changed

once a smart contract is deployed that's

it whatever is in the code is going to

be in the code Forever they cannot be

altered or tampered with in any way this

means that the security is much easier

whereas in a centralized World somebody

can hack into the server jump into the

database and change some numbers you

can't do that in the blockchain world

and since it's decentralized in order to

hack the blockchain you'd have to take

over half of the nodes as opposed to in

the centralized world where you only

have to take over one in the regular

world if your computer and your backup

computer go down all of your data is

gone in the blockchain world if your

computer and your backup computer go

down all your data is safe because it's

being run on all these other

decentralized nodes and even if a few

hundred nodes or if a few thousand nodes

go down it doesn't matter because as

long as one node has a a copy of the

blockchain you're good to go hacking a

blockchain is nearly impossible and

Leaps and Bounds more difficult than


hacking a centralized server not only

that but this is safer in the asset

sense as well all you need to access

your credentials and your information

and your assets is your private key

which is basically your password for all

of this and as we've discussed in the

video these smart contracts remove this

counterparty risk remove this

centralized intermediary remove these

trust gateways that we have to do in web

to when we engage with users and

individuals they don't always have our

best interests at heart smart contracts

remove this counterparty risk because

once one of these contracts is created

they can't go in and they can't alter it

and they can't let greed or ego or

anything else get the better of them and

alter the terms of the deal and as we

said this gives rise to these trust

minimized agreements or these

programmatic unbreakable promises we

move away from brand-based agreements to

math-based agreements where we can look

at the Crypt graphy we can look right at

the code and see exactly what something

is going to do and how it's going to

execute versus having to rely on a human

being doing the right thing with smart


contracts and decentralized hybrid smart

contracts doing the right thing is

infrastructural all these pieces boil

down to us having the freedom to

interact the way we want to interact

without having to be afraid that

interacting like that is going to screw

us over this trust minimized peace these

unbreakable promises make interactions

so much better in the purely web 2 world

we're constantly bombarded with messages

of projects and protocols pushing us to

move or act in the direction that makes

them more profitable versus in the smart

contract space we can see everything

transparently and we can even engage and

interact and be partially owners of the

protocols and the interactions that we

decide that we want to be a part

of so smart contracts have been around

for a few years now and what they

generated for what industries have come

about due to these smart contract

platforms being around well you've

probably heard of some of these and some

of these we've already mentioned but

let's give you a quick refresher defi

defi stands for decentralized finance

and it gives users the ability to engage


with finance and markets without having

to go through a centralized intermediary

for example like we said with Robin Hood

youd no longer have to trust that Robin

Hood would continue to give you access

to the markets you instead would be able

to see in the smart contract yes I have

access to the markets in the 2008

financial crisis you never have to trust

that these groups and institutions are

giving you the correct things on the

back end you can see everything

transparently right on the blockchain

you can engage with things like money

markets and sophisticated Financial

products easy effectively and securely

if you're really excited about defi we

have a ton of defi examples showing you

how to build and interact with these

protocols in coming lessons Dows or

decentralized autonomous organizations

are another group that we've already

mentioned Dows are groups that are

governed completely decentralized by a

set of instructions or smart contracts

on chain there are some massive benefits

here where engagement is much easier the

rules are black and white and you can

see everything directly on chain voting

and governance technology is completely


decentralized and the blockchain space

is one of the big ones pushing how we

can evolve politics and how we can

evolve governance to make it more

efficient fair and reasonable and you

better know it we have some examples of

how to build Dows and how to work with

Dows in coming lessons so be sure to

watch those nfts stand for non-fungible

tokens and can really be kind of

described as digital art or just a

unique asset they can do so much more

but we'll keep it high level for now

projects like board apes and crypt punks

have revolutionized the way that people

get paid for their work show off their

creativity status and so much more and

yes of course we have lessons showing

you how to create and interact with nfts

as well so many other groups and so many

other Industries are being created as a

result of this insane technology and

maybe after finishing the Journey with

us here you go out and you'll be the one

to Pioneer the next industry or the next

billion dooll idea you've learned so

much already but now that we've learned

a lot of this highlevel information

let's finally jump in and let's make


your first transaction and let's get you

set up to interact with this new world

in this next section we're going to get

you a wallet and we're going to show you

exactly what a transaction looks like

and feels like let's Dive In

this is the ethereum website

ethereum.org we are going to make a

transaction on a test ethereum

blockchain I'll explain what that means

in a little bit this is going to be our

first ever transaction that's made on

the blockchain and this process of

making a transaction is going to work

the exact same across all evm compatible

blockchains and layer 2os like arbitrum

ethereum ZK sync and Etc I'll explain

what evm means in the future for now

just follow along and have fun running

your first transaction now in order for

us to send a transaction on any of these

evm chains the first thing that we need

to do is set up a wallet so I'm going to

go to metamask because it's one of the

most popular wallets and one of the

easiest wallets to use I'm using the

brave browser but it works for Chrome or

Firefox or really any other popular

browsers out there and it's just going

to be an extension in the top right hand


of our browser it's going to make it

very easy to see anything to do with our

wallets and our transactions very easily

and it's going to store all of our evm

based currencies and evm based

transactions so I'm going to go ahead

and hit add to Brave ADD extension

although Brave does also come jam-packed

with its own wallet so now we come to

the get started page and I'm going to go

ahead and select create a new wallet

sure we'll agree to help out metamask

now we're going to create our password

make sure it's really secure for the

purpose of this demo mine's going to be

kind of mediocre now I'm going to

preface this this wallet that you're

making right now as you follow along

with me this is going to be your

development wallet so if you want to

make the password a little bit weak just

so that you can test things out very

quickly go for it just know we're never

ever going to put real money into this

wallet it's good if you treat this as if

it is a real wallet that way you'll get

used to and you'll get familiar with

good wallet safety you will then get a

video like this which will teach you


about the secret recovery phrase which

we saw a little bit earlier when we were

creating our wallet let's watch this

video metamask is a new way to connect

to sites and applications on traditional

websites a central database or bank is

responsible for controlling and

recovering your accounts but on metamask

all of the Power belongs to the holder

of a master key whoever holds the key

controls the accounts your secret

recovery phrase is your master key it's

a series of 12 words that are generated

when you first set up metamask which

allow you to recover your wallet and

funds if you ever lose access it's

important that you secure your wallet by

keeping your secret recovery phrase very

safe and very secret if anyone gets

access to it they will have the master

key to your wallet and can freely access

and take all of your funds to secure

your metamask wallet you'll want to

safely save your secret recovery phrase

you can write it down hide it somewhere

put it in a safe deposit box or use a

secure password manager some users even

in W their phrase onto a metal plate

nobody not even the team at metamask can

help you recover your wallet if you lose


your secret recovery phrase if you

haven't written down your secret

recovery phrase and stored it somewhere

safe do it now we'll wait and remember

never share your secret recovery phrase

with anyone not even us if anyone ever

asks you for it they're trying to scam

you that's it now you know what a secret

recovery phrase is and how to keep your

wallet safe and secure

awesome so that was a great introduction

to keeping your wallet safe we'll talk a

little bit more about safety with our

wallets in the future let's go ahead and

select secure my wallet now this is

where we need to write down our secret

recovery phrase and save it in a very

secure place it gives us some tips here

like a password manager a safety deposit

box or split it up and keep it in

multiple secret places for the purposes

of this video I'm going to be showing

you the secret recovery phrase because

I'm not going to put any real money into

this but you should never ever do this

additionally you'll sometimes hear

pneumonic as a synonym for secret

recovery phrase the main takeaway from

all this is you should never share any


of this this is for you only if you show

this secret phrase to anybody else they

will have access to not just one account

but every account that you make in

metamask so be absolutely certain to not

share this with anybody so again I know

I'm belaboring the point a little bit

but everything that we're going to do in

this tutorial we're going to do do with

fake money and fake assets and never put

actual money into this account that

we're making here once you get familiar

with using metamask and working with the

tools and stank secure then you can go

ahead and create a separate metamask

that will have real funds in it if you

want to put real money in different

metamask a lot of browsers have a

profile option and maybe you can make a

new profile install metamask on that

different profile call that profile real

money profile or something and that's

where you will store your money but for

this video for this tutorial the menam

that you using is going to be

specifically for testing things out and

you will never store real money to it

I'm going to harp on that a lot more in

this course so even if you're coming

here and you have a wallet I highly


recommend still making a brand new one

for this tutorial just in case you don't

accidentally code something or do

something autonomous and give away your

funds if this is your first wallet then

great but again when you're working with

real money if you lose access to the

secret phrase you will lose access to

all your money so be sure to write this

down promise me that won't use real

money for this course great I'm going to

hit copy to clipboard for now and we're

going to go ahead and hit next now we

need to confirm by adding our seed

phrase back in we can go ahead and hit

confirm and we now have created our

wallet let's go ahead and clict got it

awesome now we can see the interface of

our metamask full screen and depending

on your browser what you can normally do

is hit this little puzzle piece on your

browser and select this pin button so

now we can pin our metamask into the top

of our browser browser and we can click

it like so and we can see it give a

little drop down like this and we can

see the same information in this little

drop down as there is on the full screen

now even if you lose access to that page


now that this is bookmarked in your

browser you can select your metamask

select these three dots and hit expand

view to reach this tab now additionally

what we can do in here is we can

actually go up to our accounts and we

can actually create multiple accounts by

hitting create account and if you wanted

to you could give it a name here I'm

just going to leave it as default for

account two and now we have two separate

accounts we have an account zero with an

address and an account two with an

address as well both of these accounts

actually share that same secret phrase

so anybody with access to the secret

phrase can actually have access to both

accounts however they have different

private keys and that's what makes them

different we'll talk a little bit more

about that in the future if somebody

gets access to a private key they'll get

access ACC to a single account if they

get access to the secret phrase they'll

get access to all the accounts that you

make even you know if you made a third

one they' get access to this one as well

now if you look up in the top right of

the screen here you'll see the section

that says ethereum main net this is our


networks Tab and if you click it you can

see all the different networks that our

metamask has access to ethereum mainnet

is the main network of ethereum and this

is where real money is spent and used

for this course we're not going to be

working with ethereum mainnet we're

instead going to be working with

something called a test net for both

engineers and non-engineers we often

need a place to test or simulate our

transactions and for the developers here

throughout this course we are going to

teach you another technique for testing

out your transactions on a local network

and a local network is actually going to

be the preferred way we do our testing

and our simulations however it's still

really important to see end to end what

a real transaction looks like and that's

what a test net will do for us it

simulates exactly what a main net or a

live Money Network would look like

however there's no real money at stake

and we don't actually have to spend any

money to see some of the test Nets that

come default with metamask we can hit

the show/hide button which will bring us

to the settings page of metamask we can


turn on show test networks and if we

scroll back up now if we hit our

networks tab actually let's go ahead

close out of settings now if we hit this

drop down we can see gelli test Network

sapoia test Network and Linea really

test Network these networks are test

networks that resemble ethereum or

polygon or Linea or arbitrum or optimism

or ZK sync or any other evm compatible

chain that we want to work with and

again we'll Define evm in the future and

we can actually switch the network that

we're working on simply by clicking

another Network so let's switch to

sepolia we can see our Network changed

up here and now we can see we have zeroo

eth so on eth mainnet this new account

has zero ethereum and on the sapoia test

Network we also have zero sapoia eth

which makes sense because this is a

brand new wallet and we haven't put any

money into this brand new account yet so

of course we have zero at the time of

recording sapoia is one of the most

popular test networks out there so we're

going to be working mainly with sapoia

throughout this course however test Nets

often change because again they're run

out of the goodness of people's hearts


and sometimes people stop running them

you should absolutely have either the

web 3d. education site up or the GitHub

repository associated with this course

and an important note sometimes you'll

see this as the chain Excel or Foundry F

course we recently renamed it to The

cyphon Foundry F course so this is the

correct link but if you see chain Excel

org that's fine as well and you should

scroll down to the recommended test Nets

section to make sure you're on the most

up-to-date test net at the time of

recording like I said we're working with

sapoia throughout this course we are

going to show you how to work with

different test Nets and and different

networks as well because it's incredibly

important to do so the blockchain world

is moving into a multi-chain world and

especially with the popularity of l2s

which help ethereum scale learning the

differences between different chains and

different l2s is incredibly important

now same as ethereum what we can do is

we can actually go to sepolia etherscan

so we'll go to seo. etherscan.io and we

can grab our address from metamask by

clicking and copying the address here


pasting it into the to polia Explorer

and same as ethereum we can see our

account balance we have zero eth there

are no transactions no token transfers

nothing because obviously it's a brand

new wallet now I'm showing you this

because pretty soon we're going to send

our first ever blockchain transaction if

you've never sent a blockchain

transaction before we're going to do it

on this test net to give you some

confidence as what a transaction

actually looks like when you do move

over to a main net and I'm showing you

this site now because you're going to

see when we send a transaction action a

lot of this information is going to get

updated now just remember like I said

earlier a test net is run under the

goodness of people's hearts so please

use the transactions sparingly once you

send your first transaction here try not

to send too many more as one is good

enough for you to see what's going on

anyways and in order for us to simulate

one of these transactions we're going to

go to a faucet for a test net testnets

have this thing called faucets which

allow us to get some free sapoia eth so

that we can passed out sending


transactions and receiving transactions

if you go to the GitHub associated with

this course or web3

d.ed we can scroll down to this testnet

faucets section and select one of the

links to go to one of these test net

faucets right now the recommended faucet

that we're working with is faucets.

chain. link But be sure to use the

GitHub repo or web 3d. education to be

most up toate what this is going to do

is we're going to ask this faucet site

to send us testet ethereum and this is

why this test net ethereum isn't worth

any real money since we can get it for

free anytime that we want these

obviously don't exist on mainnet you

can't get free mainnet ethereum via a

faucet now what we can do is we can

actually connect our wallet to this site

and we can get some free testet sapoia

eth this will make it so that in our

balance here we'll actually have some

sepolia eth to play with so to do this

what we're going to do is we're going to

go ahead and hit connect wallet except

the chain link terms of service I've

already read them our metamask is going

to pop up to connect it to this website


now get familiar with this interface

because this is how websites will

interact with our wallet and interact

with the blockchain connecting our

account to the site we'll first select

the specific account that we want to

connect we're just going to choose

account one we'll hit next and then

we'll go ahead and hit connect and now

we can see our wallet address in the top

right and we can see that we're

connected

on the ethereum sapoia test net if we go

up to our wallet and we actually switch

to ethereum main net you can see that

the website has actually changed this

little dropdown to ethereum name net and

if we go in here we can actually switch

to ethereum spolia and our metamask will

pop up with this switch Network button

which will help us switch the network

for us so now we're back on sapoia test

Network connecting to these websites is

how we give these websites a way to

interact and connect with our wallets we

can go ahead and select this hit these

three dots and hit disconnect this

account but don't worry anytime we want

to send a transaction the website has to

ask us if we want to send a transaction


so just by connecting to the site it

won't actually send a bunch of

transactions for us and if we scroll

down we can see our wallet address is

placed right here and we can see we can

request test link and we can also

request test eth for now we don't need

any test link so we're going to leave

that off but in the future we will come

back back to the site to get some test

link for now we're just going to get 0.1

test ethereum and if all goes well we

should hopefully see it in ouria etherum

in order for us to get this test

ethereum we do have to log in Via

Twitter if you don't have a Twitter you

can use any of the other Faucets in the

test net faucets area of the GitHub such

as the Alchemy seoa faucet or the seoa

proof of work faucet but if you are on

Twitter now's a great time to give me a

follow maybe give me a shout out and

maybe say hey send my first

transaction thanks Patrick Alpha C or

not whatever you want to do just some

light Shilling of my own Twitter account

anyways we can log on Via Twitter we can

authorize this app verify that we're

human give our AI overlords The Prompt


here oh make sure we don't select the

link and let's go ahead and send the

request now what's going to happen is

it's going to give us this transaction

hash on sapoia and after a delay we'll

see it go from initiating to waiting for

confirmation to token transferred and

we'll see a transaction hash and if we

click the transaction hash we'll see a

transaction that was sent to our address

so this will be the first transaction

that we get to see and there's a ton of

information here but the most important

piece is if we open up our metamask now

we can see we now have 0.1 sapoia e in

our account and if we copy the address

again we paste it into here we can see

now we have a 0.1 eth balance you might

have to wait several minutes for the

transaction to finish going through and

if you accidentally refresh your browser

again we can go ahead and just select

our metamask copy our address and paste

it into ether scan or just view it right

in our metamask here and if you missed

that piece about the transaction data if

we go back to Ether scan with our

address remember we're on sepolia ether

scan and we scroll down we can see this

most recent transaction hash that just


occurred and we can click the link here

and we can see that d detail about the

transaction again here now importantly

remember though this is on sapoia if we

switch back to mainnet ethereum you'll

see we have zero eth on mainnet ethereum

if we switch to gly test Network you'll

see we have zero g eth on that network

if we switch to Linea gelli eth or any

other network other than sapoia you'll

see that sapoia is the only one that has

the 0.1 sapoia eth if you want to

practice working with a different test

net feel free to scroll up back to the

faucet select a different test net and

try to get test net in one of these

different test Nets just be sure to take

a look at what test Nets your metamask

comes with since some of the networks

this faucet is compatible with don't

come built into our metamask but again

like I said in the future I'll teach you

how to add these different networks to

our metamask in the future but huge

congratulations you received your first

transaction because again this faucet is

US asking them to send us money it's not

us sending money it's them sending money

to us and if this is the first


transaction that you've ever sent you

should be proud of yourself already give

yourself a big Pat in the back and

here's a picture of me holding a cat

with that cat's face all over my pajamas

as a congratulations now once more let's

grab our address paste it into ether

scan here and scroll down and we're

going to learn a little bit more about

what actually went down what actually

happened in this transaction you can see

on ether scan it gives us some basic

details it says from and to from is

going to be another address a different

address an address controlled by the

faucet and two is obviously going to be

our address and if we select this

transaction hash we can see even more

details in here understanding all these

different fields is essential to

becoming a smart contract developer and

even just a web 3 or ethereum or

blockchain user so let's learn a bit of

the basics of what's actually going down

in this transaction the first field on

this page is the transaction hash you

can even see a little question mark here

which tells you a little bit more about

it it's a unique identifier for this

specific transaction on this network so


this specific transaction hash we can

even copy and paste this into the

address bar and we'll get the exact same

transaction back this is the only

transaction in the entire blockchain

that will have this transaction hash

it's the unique identifier it identifies

the transaction of sending 0.1

from the faucet address to our address

we can see the status of this was

successful we can see the block number

and the number of block confirmations

which we will explain in the future we

can see the time stamp which of course

is when this transaction occurred we

could see the from and to who

initialized the transaction and who it

was sent to if we select this from and

open this in a new tab we can see some

details about who actually sent us this

test eth and if we go back to the

transaction detail and keep going we can

see the value here which again if we

roll over it's the value of ether or

test net ether and then in parentheses

the Fiat value or the dollar value which

of course since this is a test net it's

always going to be zero the value of

this transaction was 0.1


e now what's underneath this value thing

this transaction fee and this gas price

thing what are these if we zoom in a lot

more to these pieces here and we roll

over transaction fee we can see it says

it's the amount paid to the block

producer for processing the transaction

and then gas price is going to be the

cost per unit of gas specified for the

transaction in ether or gay the higher

the gas price the higher the chance of

getting included in a block I'm going to

explain that in a little bit but if we

scroll down even more let's Zoom back

out and we click click to show more we

can see even more details about this

transaction for now we're just going to

click to show less and just focus on the

details that are here so let's talk

about just the concept of transaction

fees and gas for second because they are

important concepts for you to understand

remember how I said that these

blockchains are actually run by a group

of different nodes well the question is

what's their economic incentive to keep

running these blockchains are they

running them out of the goodness of

their heart well on a real Network these

nodes actually get paid a little bit of


ether for processing transactions

whenever you send a transaction there's

a node sometimes referred to as a minor

or a validator depending on the network

you're on who gets paid a little bit of

the Native currency of the blockchain to

process that transaction for ethereum

they obviously get paid in ethereum or

for test ethereum they get paid in test

etherium which again the test ethereum

is worth nothing which is why I said

they're running them out of the goodness

of their heart if you're sending a

transaction on the polygon Network

they're going to get paid in madic the

native token of polygon if you send a

transaction on an L2 like arbitrum or

optimism you're going to get paid in eth

which is the native token of those l2s

this payment is obviously to incentivize

people to continue to run nodes and they

get paid more the more gas you use so

what is gas gas is a unit of

computational measurement the more

complex your transaction is the more gas

you have to pay for example if we hit

more details just really quickly and I

zoom in a little bit more we can see

this section here gas limit and usage by


transaction this means that when we sent

this transaction we limited it to a

maximum of 60,000 gas but in total we

only used 21,000 gas this 21,000 gas

represents how complex this transaction

was it was 21,000 gas units worth of

complexity now for simple things like

sending ether the units of gas are

usually pretty small for example 21,000

units of gas is actually a really small

amount of gas being sent but maybe for

more complex transactions like minting

and nft depositing some funds into a

defi protocol or deploying a smart

contract those are typically going to be

more expensive transactions because

they're more complicated they have to do

more stuff in the future we'll introduce

you to this concept of evm codes or op

codes and if you break down a

transaction to the lowest level this

assembly op code stuff you can actually

see exactly how much each op code cost

in terms of gas don't worry about this

at all right now just know that these

transactions are broken down into many

many many many very very small

instructions and each instruction has a

specific amount of gas the more

instructions usually means more gas like


I said we'll explain this much later in

the course don't worry about this too

much here but just know that we use

21,000 gas now if you take this gas used

and multiply it by the gas price in eth

instead of guay so we'll take 21,000 and

multiply by this gas price in eth not in

guay and hit enter we see the total

transaction fee of the transaction and

you can see that this number does indeed

match the transaction fee for you to

understand how much eth you're going to

pay for your transaction you multiply

the gas price times the gas used

transaction fee equals gas price times

gas used so this means that whoever sent

us this 0.1 e also paid

0.0000 0525 blah blah blah eth to a

blockchain node to a validator on the

sapoia ethereum test net now each

blockchain has their own unique way of

calculating how much transaction fee

someone's actually going to pay for most

evm chains this is the simple algorithm

it's going to be gas used times gas

price after we understand how the

blockchain works more in depth I'll

explain to you what the rest of these

values stand for for now just know that


anytime you make a transaction on chain

you have to pay the validators or the

blockchain nodes a little bit of gas or

a little bit of the Native token of the

blockchain which in our case is eth so

you have to pay a little bit of eth to

the blockchain nodes providing or

sending the transaction sometimes I'll

refer to this just as transaction gas

let's look at an example of this

ourselves if we pull up our metamask we

go ahead and hit expand view as we know

we have two different accounts in here

we have account one and count two count

one has 0.1 spolia eth Count 2 has zero

spolia eth if I send

0.05 from account one to account two how

much do you think I'll have left in

account one let's go ahead and do this

and this is going to be the first

transaction that you send on the

blockchain which is incredibly exciting

as well let's go ahead and hit this send

button in our metamask we'll hit send

we'll hit transfer between my accounts

we'll select account two and we'll say

0o

.05 spolia eth so we started with 0.1

spolia eth and we're going to send 0.05

to account two we'll scroll down we'll


hit next we can see some information

here about what's actually going on we

can see some gas information which

metamask automatically prompted for us

and it even gives us the total amount

that we're going to be paying in eth

it's adding this 0.05 e to the estimated

amount of gas that we actually have to

spend so that at the bottom it says the

amount Plus the gas fee is the two of

those combined the value that we're

sending plus the gas fee and

additionally in metamask if you select

this here you can get some more

information about editing our gas fees

the amount of gas that you choose to

spend can be different depending on how

many people are making transactions with

the blockchain the more people are

sending transactions at the same time

the more expensive gas costs are going

to be so if a lot of other people are

also sending transactions right now the

gas price is going to be higher if a lot

of people are sending transactions that

means there's not going to be enough

space for everyone's transaction to get

through so in order to throttle that

they increase the gas price that's a bit


of an oversimplification of what's

happening but if you take that

understanding that'll pretty much work

if you want to specify exactly how much

gas you want to spend you can clict the

Advan tab if you select zero gas there's

a high likelihood that your transaction

will never go through so we're just

going to go with the default which is

usually a good idea so let's go ahead

and confirm we now see a send

transaction in our Q in the activity tab

of our metamask which shows us that we

have a transaction currently sending and

if we click on it and click view on

block Explorer it'll actually open us up

on ether scan and we'll see well mine

was a little bit quick but normally

we'll see a little indexing Tab and we

won't see this having gone through we'll

see it as like indexing or sending or

something like that but after a little

bit it'll actually finish sending you

might have to wait a minute or or so for

this to actually finish going through

but it looks like mine was really quick

and same as our last transaction this

has a lot of the same information and if

we scroll down we'll see that of course

we sent a different amount of eth


0.05 and we have a different transaction

fee now if we pull up our metamask what

do you think that we're going to see

we're going to go ahead and click expand

view again and we see count one says

0.05 and account two also says 0.05 hm

that's kind of odd I thought we spent

some gas well if we click on the big

accounts button we can see exactly how

much eth is in each account we can see

we have

0.499 in account one and 0.05 in account

two and we can see in our activity

history our account one recently sent

0.05 eth and account two recently

received 0.05 saoa eth now here's the

best part of all this even if you don't

want to become a developer you just

learned the basics of sending a

transaction and interacting with sites

using your metamask congratulations now

here's something that's incredibly

exciting with just this little bit of

information you now know how to interact

with blockchains and interact with the

ethereum protocol so if you don't want

to learn how to code anything you can go

and you can start interacting with

ethereum and interacting with protocols


with just this much information however

I know most of you guys are here to

learn how to code so let's look under

the hood of ethereum and what is

actually going on with these

transactions and with these gas and with

these blockchains and what's really

going on let's learn all the

fundamentals of a blockchain now if you

want to just go ahead and jump into the

coding go ahead and grab a timestamp

from the description however learning

exactly how the blockchain works is

going to make you an incredibly powerful

developer so let's take a look at that

first so we're going to be going through

this blockchain demo on this site right

here now the creator of the site has a

fantastic video and a fantastic

walkthrough blockchain 101 it is right

on their site so if you're looking for

another explanation definitely check out

his video it is absolutely fantastic but

the first thing that we really need to

do in order to understand blockchain in

order to St really anything and

everything that's going on here we first

really need to understand this sha 256

hash or hashing just kind of in general

let's first understand what a hash is a


hash is a unique fixed length string

meant to identify any piece of data they

are created by putting some piece of

data into a hash function in this

example uh the hashing algorithm used is

Shaw 256 now ethereum actually used is

uh this uh this right here for its

hashing algorithm which isn't quite um

Shaw 256 but is in kind of this sha

family but it's it's really just another

way to Hash things and uh the specific

hash algorithm doesn't matter uh so much

so uh this example use Shaw 256 but you

can imagine it's the same as the

ethereum hash they're just going to you

know result in a different hash so

what's going to happen in this

application here is whatever data or

whatever information we put into this

data section here as you can see below

this hash changes so what's happening is

this data is running through this Shaw

256 hash algorithm and it's outputting

this unique hash so this hash is a

unique fixed length string that's going

to identify like a blank data piece here

right so if I put in you know my name

like you know Patrick Collins this is

the hash that's going to represent


Patrick Collins right and you can see

even when I put you know tons and tons

of data in here the length of the string

doesn't change right so it's always

going to be the same amount we can put

almost any amount of data in here there

is an upper limit on the max size of the

data but for all intents purposes we can

pretty much put any length in here and

you'll see too that you know every time

I type in Patrick Collins this hash is

always going to be this 7 e5b right I'm

going to delete it I'm going to do patri

colins again

you know 7 e 5B it's always this this

unique hash is always going to be unique

right it's always going to be this fixed

length string here so now we can take

this idea right of putting this data in

here and we can move on to uh this

concept of a block so with this block

concept we're going to take the exact

same thing with this hash this this data

section right but instead of having

everything just being in this this

singular data area right here we're

going to split this data up into block

nuns and data so all so what we're going

to do is we're actually going to Hash

all three of these to get to get this


hash right we're going to put all three

of these we're going to say all three of

these are combined uh together we're

going to put every all three of them

into this hashing algorithm uh to figure

it out so if I type a bunch of stuff

here we can see that block one with nuns

you know this nuns and this data we're

going to get this hash and as you can

see actually the screen turns red this

block turned red now what happens when I

hit this m button when I hit this mind

button it's actually going to take some

time it's going to think for a little

bit and we can see that the nuns here

actually changed right the nuns is

different from what it was before and

this hash now starts with four zeros

okay and then the back turned green when

we're talking about mining we're talking

about miners solving some type of very

difficult problem that takes a lot of

time to do now in this example here the

problem that uh the miners had to solve

was they had to find a nuns or or a

value in this nun section that when

hashed with at block number one with

this data it would start with four zeros

so the problem here the minors had to


solve was to start with four zeros and

the only way for them to really do that

is kind of this Brute Force you know

trying stuff so they tried one okay one

didn't work okay two nope two didn't

work three no four five six okay five

well that started with one zero but

that's not four and they have to keep

trying all these numbers until they uh

get to this one where you know let's hit

mine

again where it has four zeros at the top

at the start now this specific problem

changes blockchain to blockchain right

ethereum has a different problem for

miners to solve um Bitcoin has different

problems for miners solve but this

concept is going to be the same and

since ethereum is proof of stake now

nodes actually take turns solving these

problems again we're not going to go too

deep into that right now though so they

have to take um one block is going to be

this this uh this concept is going to be

all this data it's going to be the block

number and it's going to be this nuns

right and so this nuns is the solution

um is is going to be the the number that

they use to get like the solution to the

problem right so if I go to one here you


know and I do this

again we going to hit mine and the nuns

has changed right it went from one to

33,100 and so that's what's happening

when uh blockchain miners are mining

they're going through this process this

very computationally intensive process

of trying to find a nuns that fulfills

whatever the problem is so that's really

it actually so that's a block and and

that's really what's happening when

miners are mining they're just looking

there's trial and error Brute Force

trying to find this nut so so now that

we know what a block is let's go to the

next step and figure out okay well

what's a Block Chain so here we have an

example of what a block chain is going

to look like right we have a combination

you know we have back here in the block

section we have one what one block looks

like now here we have multiple different

blocks right each one of these

represents a different block but we have

an additional column here or we have

additional uh variable here so like

before you know we have block NS and

data right we have block nuns data but

we also have this thing called previous


right and so this is actually going to

be pointing to the previous hash of the

last block so for example we go to the

the last block in this blockchain it

says previous is 00 ae8 and if we look

at the hash of block number four it's

000000 a E8 and then we look at its

previous it's 4 Z's B9 we have 4 zos B9

and so on all the way back to our first

block which has previous of just all

zeros right and so the block with the

previous of all zeros is going to be

known as The Genesis block so you've

probably heard that before the Genesis

Block it's the first block in the

blockchain where the previous hash

points to a hash that doesn't actually

exist now as you can imagine kind of the

same as how this block worked how the

block nuns and data all go through the

hashing algorithm in the blockchain the

block nuns data and previous hash all go

through this hashing algorithm to figure

out you know what the hash is okay so if

we go to over here you know for example

if I type in you know Patrick obviously

this is now no longer valid right

because this nuns uh combined with the

block the data and the previous hash

aren't going to solve you know our


problem of having four zeros at the at

the start right so I'm going to go and

fix that and and that's that's kind of

an easy way to to see it being broken

but but let's take a look if I break

this block right here what happens if I

if I break the data in here if I do like

Patrick in here you can see that both of

these are now read both of these are now

invalid right because the block hash

with the nuns hash with the new data

which is my name Patrick hash withe

hashed with the previous block

is now a brand new hash right and this

block is still pointing to this previous

hash right here right is pointing to

this previous block and now it is wrong

and it is messed up and now um and now

it's Nuns with this previous hash is

also wrong right and this is where when

we talk about uh blockchains being

immutable this is exactly how it's

immutable right because if I go back and

I change anything you know if I just

typed a right here the entire enre

blockchain is now invalidated because

none of these are going to have uh Nunes

that solve this equation anymore so this

is why blockchains are immutable is


because anytime you change one thing you

ruin the rest of the blockchain okay so

however though you know if if an a was

here originally we can go ahead and mine

these we can mine all these but as you

can see you know this is going to start

getting very uh computationally

expensive because I have to go redo uh

basically the entire blockchain uh and

the the farther and farther down the

line you get the harder and harder it

becomes to you know rehash and and redo

all these different blockchains here now

this makes a lot of sense right so we

have this blockchain it's really hard to

change something in the past but if we

do we can just go ahead and remine it

now if I'm the one who controls the

blockchain right if I'm the one who

controls this you know and I want to

change something in the past well okay

great all I got to do is change this

data here and then you know mine each

one of these you know obviously it's

going to be very computationally

expensive but it's something that I can

do right if I'm the one who owns the

blockchain

now here's where the decentralized

nature or the distributed nature really


uh makes it incredibly powerful so we're

going to go to the distributed tab here

which I also refer to as the

decentralized tab here and it's going to

show us what a blockchain looks like uh

in a decentralized manner so we have

this exact same uh initial setup here we

have distributed blockchain we have you

know the our first blockchain which is

kind of exactly as the one from here but

we also have more than one so we have

Pier a pier B and Pier C and when people

are talking about peer-to-peer

peer-to-peer transactions they're really

talking uh this is kind of that concept

that they're talking about right so we

have a number of different peers who are

running this blockchain technology

they're all weighted equally right each

one of these peers or each one of these

nodes each one of these entities running

blockchain has the exact same power as

anybody else right so the way that we

can tell very easily which blockchain is

correct or which ones are correct are by

looking at this end hash here right by

looking at where we are uh in the

blockchain because again remember


because again remember this this hash

that this this in this last block here

is going to Encompass all of the blocks

from before right because this last hash

is going to have the previous hash here

which includes the previous hash here

which this hash includes the previous

hash here and which so this last hash is

encompasses everything in here right and

we can look we can look at the hash of

Pier C

which is 4 zos and then e4b we can look

at the latest hash of Pier B which is 4

zos e4b and then Pier a which is 4 Z e4b

so all of these peers all of these nodes

all of these decentralized you know

these independent um all these

independent users running this

blockchain software they're all matched

up it's very easy for their nodes to

look at each other and say hey great we

are all matched up now what let's say

that a decides that you know something

happened on the blockchain that they

didn't like and they wanted to go back

and change something right so let's say

they change here you know obviously uh

the rest of their blockchain is

invalidated and they have to spend a lot

of computational power to catch up to


speed so let's go ahead and humor it

let's say that they they did they ended

up catching up uh they ended up catching

up you know they ended up mining

everything and now they have a valid

blockchain right it solves the equation

awesome however in block number three

there's something new right this is here

and it shouldn't have been here this is

something that per a put in by

themselves all that happens now is we

look at all the blockchains that are

running the software and we're looking

at all the hashes at hash at block

number five so Pier a has this new hash

now 009 BC but Pier B has a different

hash 00 e4b right so who's right is it

is it Pier a with their new stuff or is

it Pier B well that where the

decentralized comes in because then we

can look at Pier C and Pier C also has

e4b so Pier B and Pier C both say hey P

A you're wrong get out right and P A

will stop being able to participate in

the mining rewards because they have

essentially forked uh the blockchain and

started their own little blockchain

right with their own history because

they're the only ones with this this


piece of data in block three whereas

Pier B and Pier C have nothing in there

so that really shows why uh in these

blockchain worlds in this decentralized

world there really is no centralized

entity you know perer a you know might

have been maliciously motivated to

change you know this this block number

three however democracy rules right the

majority rules in the blockchain pier B

and Pier C both say Hey you know that

that's cute and all per a but you're

wrong right that that's not right now it

might be a little abstract that you just

look at data and you know us typing kind

of random stuff in here and think okay

yeah that's that's data right that makes

sense you know just kind of r random

strings in here doesn't really do

anything for us so if we actually go

over to the Token section here this is

where everything really starts to make a

lot of sense so we have the exact same

setup here uh with Pier a pier B Pier C

except the difference is instead of

having kind of this this data section we

have this uh TX this transaction section

right and this represents all the

transactions that are happening in this

block right so we're we're sending $25


from Darcy to Bingle or to bingly

uh four uh

$427 here 1922 right and it's the exact

same thing so this all these

transactions are going to get hashed in

the exact same way uh that the data is

going to get hashed and and this is why

it's so powerful because again you know

if I want to be malicious right if uh if

I wanted to say hey I I really wanted to

give Jane a lot more money from

Elizabeth so I'm p and I go back and I

change it to 100 well now you know not

only do I does my whole blockchain uh

get invalided because that was so far so

long ago but I'm not going to match any

of these other chains right and so my

blockchain is going to be excluded from

the overall blockchain so and let's

let's go ahead and fix this and it's the

same thing if down here if I become

malicious and I want to send you know I

want uh Miss Audrey to have less money

maybe I want to send a dollar and I go

ahead and mind it the same thing here

this hash now this 2a1 is not going to

match tob's

pb's hash of BBA and it's not going to

match Pi C's hash of BBA as well so the


two of them are going to say hey this

your blockchain is invalid it's not

matching the majority you know you're

out right so that's really how uh these

blockchains work at a low level and it

all goes back to this this understanding

this hash idea and using it in this very

sophisticated manner uh to kind of

cryptographically prove um you know

where where stuff lies now the way the

blockchain works yeah instead of random

stuff put in this data section it's

actually going to be solidity code in

here to finding ways to interact with

different blocks and different protocols

that are on chain or as we've said

before different smart

contracts now the next question that you

might be asking is okay well how do I

know how can I be sure that I'm the one

uh you know let's say this is let's say

I'm Darcy right how can I be sure that I

was that Darcy was the one to actually

send this money here how do we know that

Darcy sent 225

to uh Bingley well this is where we get

into private keys and public keys and

that's what we're going to go into now

let's just do a quick recap of what

we've learned in this section so far


right we've learned that ethereum

actually runs on this kit check 256 but

you know we used sha 256 for this demo

it doesn't really matter we're just

talking about hashing algorithms so

again a hash is a unique fixed length

string meant to identify any piece of

data data a hash algorithm or a hash

function is a function or algorithm that

computes any type of data into a unique

hash mining is going to be the process

of finding the solution to the

blockchain problem in our example the

problem was finding a hash that's starts

with four zeros nodes get paid for

mining different blocks and the problem

is going to be different blockchain to

blockchain a block in a blockchain is

basically a combination of a block nuns

transaction and a previous hash to

create this unique cash for this block

and again depending on the blockchain

implementation this might have a couple

other fields or might have different

fields but this is essentially what's

going on blockchains are decentralized

and distributed because many independent

users are going to run this blockchain

software and they will check and they


will compare against each other to see

which blockchains are acting honestly

and which ones are acting maliciously in

the blockchain world majority rules the

nuns here is the answer used or the

number used to get this hash now nuns is

kind of an overloaded term it's actually

used for a number of different reasons

in this case we're using it to solve

this problem of getting you know four or

5 zos at the stop of the hash however in

ethereum it'll also be often used as the

number of transactions from a given

address so now we're going to talk a

little bit about signing these

transactions and and private keys and

and some other cryptography pieces right

because in this blockchain demo here we

can see we have all these these

fantastic transactions right all these

things went through but how do we know

that it was Darcy who was the one to

send $25 uh to Bingley right how do we

know that actually happened and this is

where all those pieces that we just

learned about uh in our our test net in

our metamask account are really going to

start to to come to life here a little

bit here so here we have an example of

public and private Keys okay at the top


we have this private key right that was

that was randomly generated uh a private

key is is you know as it kind of States

is key that you really want to keep

secret because you're going to be using

this uh as kind of your your secret

password for all your transactions right

I can really pick you know any any any

private key anything that I want and

with it uh this algorithm uh they're

going to use an algorithm you know for

ethereum and Bitcoin they both use this

elliptic curve digital signature uh

algorithm it's it's a variant of just a

digital signature algorithm and it's

going to create this this public key

right I'm really not going to go at all

into kind of this digal signature

algorithm but just know it does use some

of these uh some of the hash uh

knowledge that we just learned combined

with some other pieces uh to kind of get

this this public key here so I'm not

going to go too deep into it but we have

this private key that we create and we

get this public key now this public key

we want everybody to have access to

right this is yeah whole world can see

this this private key we really want it


to be uh private we don't want people to

see this we're going to use this private

key as like a password to quote unquote

digitally signed transactions and then

people can verify them with this public

key so let's let's see what this

actually looks like let's pick a a

random key a more secure key right

because the longer it is the the more

secure it's going to be and if we go to

signatures now right um let's say we

have this uh this message that we want

right we's say high world right we want

this to be the message what's going to

happen is this private key that we've

created we can use to sign this data

right remember how in the blockchain

chain demo you know we were kind of we

were hashing stuff right we were we're

using this shade 256 hash to to get this

hash well we're doing something similar

but instead of hashing we're we're using

this digital signature algorithm to

create this message signature now what's

really powerful about how this uh this

algorithm works is that you can create

this message signature with your private

key but somebody else can't derive your

private key from the message signature

and that's what makes this really really


powerful ful however if we go to verify

using this public key right uh and so

this is the this is that 0403 this is

that same public key using this uh using

this public key anybody can verify oh

let's go ahead and sign it again anybody

can verify that this signature is yours

right so you have a public a private key

just for you so you can sign things and

a public key so that anybody can verify

something right so anybody can verify

this and let's say somebody tries to

fake a transaction from you they say Hey

you know this is this is this is their

transaction um all they have to do is

verify that this signature against your

uh public key and very easily this whole

thing turns red because uh it isn't

verified right the the algorithm says

Hey uhuh that's wrong so we can go ahead

and take that into transactions in this

exact same way so if I want to send

money you know if I want to send $400

from you know my address to another

address using my private key I can sign

that transaction and anybody else in the

world can then verify this transaction

right and this is why when people say

hide your keys you know protect your


keys this is what we're talking about in

our accounts here right if we go to uh

settings and again the only reason that

I'm showing you guys my pneumonic and my

private key is because this is a uh this

is a dumpster account I'm going to throw

this away at the this video or I'm just

not going to put any real money in it um

but when we look at our our our metamask

here we have this pneumonic phrase which

allows us to easily get these different

private keys right so uh pneumonic

phrase combined uh with you know uh

whatever account number will get us a

private key so pneumonic phrase combined

with one we're going to get this private

key and this is when we look at Account

Details export private key

password confirm this is going to be the

private key that we're going to use to

sign our transactions right this if

anybody else gets access to this private

key they then can sign transactions for

us and they can send transactions for us

and that's why we want to keep these

private so uh it works the exact same

way right so this is why it's so

important to hide your private keys and

hide your pneumonics now your ethereum

address is actually uh a piece


uh is actually a piece of your public he

now to get our address in ethereum all

we have to do is take this public key

that we've created with our private key

hash it using that same ethereum hashing

algorithm and then take the last 20

bytes and that's how we'll actually

derive to our um to our address here now

knowing the exact methodology of how to

get the address doesn't really matter

because it could change blockchain to

blockchain and could even change e two

um but just know that that is

essentially how kind of these addresses

are derived right there's some

derivative of the public key right

because the public key is public and you

know uh using the public key in kind of

any public way is is totally fine um but

not the private key so that is how we

sign our transactions note though this

isn't how we send the transactions so so

this is just going to sign it create a

transaction for us to send uh we'll

learn later on how to send these

transactions so that was a lot of

information there too let's do a quick

recap your public key is derived by

using a digital signature algorithm on


your private key right and you want to

keep your private key private at all

times because you're going to use your

private key to sign transactions signing

transactions with your private key you

are the only one who can actually do

this because you can't get the private

key from a message signature however

using your public key you can anybody

can very easily verify that a signature

that's signed by you is in fact signed

by you in our metamask our private key

are located in this Account Details

section you just hit uh show Private

keys and type in your password and it'll

get your your private key here and the

address of your account is derived from

this private key uh it's derived from

this public key so if you think about it

your private key creates your public key

which then can create your address and

there's a little barrier

here or a big barrier here because your

private key you want to keep private and

your public key and your address can all

be public information now remember how

in our metamask we were able to actually

create new accounts mine says account

six cuz I've created actually a few but

how was it actually creating those


accounts well now that we know all this

if we go back to our blockchain demo

here what are metamask is doing is

essentially taking our pneumonic or or

that multi-word secret phrase and then

just hashing it with some number so

secret phrase plus 0 gets this and it'll

set this as your private key and for our

account one that'll be the private key

or maybe it's plus one the exact

algorithm that it's using doesn't matter

but if you want to create a new private

key where you just hit this create

account button the way it actually picks

this account is by taking this secret

phrase and then just changing this

number so if I go if I'm in my metamask

I do create account this right now I'm

on account six because like I said I

made a whole bunch if I make account six

right it's as if we just did the secret

phrase plus 6 and created this new hash

or this new private key and created this

new hash and it uses this to make a

private key and this is why in your

metamask if you share that secret phrase

if you share that pneumonic device they

will have access to all the accounts

that you ever created however if you


share your private key it will just give

them access to that single account

secret phrase has access to all the

accounts created in your metamask or

your wallet your private key is access

to that single account and then the

public key or address anybody can have

access to and it's cool for anybody to

have access to so when I'm thinking

about the security of my metamask or my

wallet this is kind of the order that I

think of it in the seed phrase or ponic

or secret phrase is incredibly important

protect this at all costs because if

somebody else gets access to this they

will have access to all of your accounts

the second most important is the private

key because if somebody gets access to

that they will get access to a single

account and then your public key or

address which whatever it's public

now that we know a little bit more about

what's going on underneath the hood of

these blockchains let's go back in our

transactions and look at this gas thing

again and we'll look to see what's

actually happening here gas in

particular can be a little bit tricky to

wrap your head around so if you don't

get it right away don't worry as we go


through examples it'll start to make

more sense so before I was saying let's

just look at this transaction fee bit

which is the cost associated with

running this transaction if I scroll

over this on ether scan I can see this

thing that says Block Base fee per gas

plus Max party fee per gas times the gas

use which might be a little bit

confusing here let's actually break down

what's going on on ethereum with EIP

1559 in place and again this is going to

be specific to ethereum as every

blockchain might do it a little bit

differently but if we click to see more

we can see a number of useful values

here we can see gas limit is 21,000 and

usage is

21,000 so this transaction used 21,000

gas and we sent 21,000 gas along with it

sometimes when sending a transaction

depending on when it's sent and

depending on what these Specific

Instructions are it might actually use

way more gas than what you want it to

use so with your transactions you can

actually set a limit hey I don't want to

use more than x amount of gas I don't

want to do more than x computational


units and in fact if we go to our

metamask and we click send to transfer

between accounts again and we pick you

know 0.01 eth or something next you can

actually hit this little button here go

to Advanced and we can actually edit

some specifics of this transaction one

of them is going to be the gas limit we

can change this gas limit to maybe 2200

2300 or more or even less since sending

ethereum takes exactly 21,000 gas metam

Mas just defaults to setting to that but

we also see these other interesting

things we see a priority fee and a Max

Base

fee let's reject this transaction and

let's look back at ether scan to talk

about these So currently in ethereum

according to e EIP 1559 every

transaction on ethereum comes with

something called the base fee this is

the minimum gas price you need to set to

include your transaction and you'll

notice that these are priced in

something called guay so what is a guay

if we come to the site ethon converter

and again there's a link to this in the

GitHub repository we scroll down we can

see whey guay and ether if I put one

ether in here I can see how much one


ether is in terms of guay and in terms

of whey one ether is equal to 1 2 3 4 5

6 7 8 nine nine zeros so that's that's

one billion guay is going to be one

ether and then 1 2 3 4 5 6 7 8 9 10 11

12 13 14 15 16 17 18 and then 18 zeros

is away these are just easier ways of

referring to really really small amounts

of ethereum so if we look at our gas

fees we see that the base fee is

0.00000000 004 gay and this obviously

would be an even smaller number if this

was in units of we so if we take this

number and we put it into our calculator

we can see that this is equal to 40 way

or 0. a whole bunch of zeros for ether

the max fee here refers to the maximum

gas fee that we're willing to pay for

this transaction and you can actually

see that our Max fee is a little bit

higher than what we actually ended up

paying our Max fee was 2.21 32 something

something and the gas price we actually

paid was up here now your transaction

might of course be a little bit

different then additionally we have a

Max priority fee this is going to be the

max gas fee that we're willing to pay

plus the max tip that we're willing to


give to miners now currently in ethereum

this base fee ends up getting burnt and

we can see on ether scan exactly how

much is getting burnt here and if we

pull up our calculator again we can grab

this gas fee multiply it by the amount

of gas we used and we can see that this

is indeed how much ethereum we actually

ended up burning we go back to ethereum

converter paste it in we can see that

these two numbers

are indeed equal this means whenever you

send a transaction a little bit of

ethereum is removed from circulation

forever or it's considered burnt So

currently in ethereum part of your

ethereum part of your transaction fee

actually gets burnt and then the other

part goes directly to minors so to

figure out exactly how much went to

minors we could do this number minus the

burnt amount and this is how much

ethereum was paid to in ethereum minor

for this transaction you'll see down

here transaction type 2 EIP 1559 this is

the EIP 1559 version of these

transactions like I said every

blockchain is going to have a different

fee burning and and fee and gas process

and they're all going to be a little bit


different but the sum of it is

blockchains have limited block space for

transactions the gas price that costs

for your transaction to be included in

one of these blocks changes based off

how much demand there is the base gas

fee for eum will go up and down

depending on how many people are sending

transactions and how many people want to

be included in a block if a ton of

people want to be included in a block

that means a ton of gas is obviously

going to get burnt we've left a link to

a video in the GitHub repository with

this section from this YouTuber who does

an amazing job breaking down this EIP

15559 and more about how this gas model

actually works I highly recommend you

pause this video and watch that video to

understand more the Bas fee gets

programmatically algorithmically

adjusted to try to Target for all the

blocks to be 50% full if they're more

than 50% full this base fee

automatically goes up if they're less

than 50% full this base fee goes down

now this is a lot of the basics of how

this transaction works and it can be a

little confusing so let's do a quick


refresher of everything in here there's

a unique transaction hash that uniquely

identifies this transaction

on this blockchain we can see the status

we can see the block number that it's

confirmed on one other thing we want to

look at if we scroll up we see block

number and block confirmations this is

how many blocks have been mined since

this block was included like we saw with

our blockchain demo the longer the

blockchain gets the harder it is to

tamper with and the more secure it is

typically you'll see some processes say

they'll only do something after 20 block

confirmations 30 block confirmations or

or Etc the reason that they wait for

these block confirmations is because

they want to make sure that that

transaction is actually included and we

can actually see the block that our

transaction was included in and all the

other transactions with it different

details about how much gas was used the

gas limit Etc time stamp is when the

transaction happened we can see from and

to we can see the value and then we can

see the transaction fee which we see

right here is Block Base fee fee per gas

plus the max priority fee per gas times


the gas used and we see all the details

of the gas down here gas price is the

cost of one unit of gas gas limit is the

max amount of units of gas that we're

willing to pay in this transaction the

usage is how many actually got used the

base fee is going to be the base Network

fee per gas so 40 way per one gas used

the max gas is the max gas price we're

willing to pay and Max priority is going

to be the max gas price plus the tip

that we give to Miners and then we can

see how much is burnt and then we see

transaction savings which which is the

difference between how much was actually

used or paid for and then returned so

for example in this transaction the gas

price we ended up picking was a little

less than our Max gas price here so the

gas price we ended up using was a little

less than our Max priority fee here so

we had some savings compared to that we

can also see that this was an EIP 1559

transaction we can see our NS here which

was nuns zero because the transaction

that I'm showing is our first nuns and

then of course we can see the input data

for transactions that are just sending

ethereum the input data is going to be


blank but you'll see that when we get to

Smart contracts the input data is not

going to be blank and it's going to be

one of the most important features of

these transactions you'll also notice

that there's a state tab this is an

advanced Tab and it shows the different

states that are changed based off of

this transaction we're going to ignore

this one for now now that we know how

the blockchain itself Works under the

hood let's talk about some blockchain

fundamentals and we actually covered all

these topics in a previous free code

Camp video so let's go to

that if the first time you listen to

this some of these Concepts seem a

little bit hard to grasp don't worry

about it as we continue and as we move

on with this course they'll start to

make more sense when you see them used

in real examples I definitely would

recommend going back and rewatching and

Rel listening to the parts that you

don't quite get and asking questions in

the discussions tab of the GitHub

repository awesome so now that we know

all the cryptography pieces and all the

little nitty-gritties of how the

blockchain actually works and how our


signatures work and how everything

sticks together let's talk a little bit

about how this works in actuality and

what's really going on now for a lot of

this each different blockchain has

slightly different algorithms and

slightly different metrics in criteria

for doing a lot of this stuff so when

we're talking about these specific

implementations keep in mind the exact

algorithm might be a little bit

different but the concepts are all still

going to be exactly the same hashing and

hash function is going to be the same no

matter where you look a decentralized

blockchain it's going to be the same no

matter where you look how it's actually

implemented is going to be a little bit

different now traditionally when you run

an application you know be it a website

or something that connects to some

server you are interacting with a

central calized entity and unlike how we

saw with the blockchain with multiple

different peers it's going to be run by

a single centralized group now it still

could be run on many different servers

but all those servers are still going to

be controlled by the same centralized


group blockchains as we saw run on a

network of different independent nodes

when we saw Pier a pier B Pier C those

were different examples of different

independent users running the blockchain

technology on their own node now when I

use the term node I'm usually referring

to a single instance of a decentralized

system so when I say a single node when

I'm talking about a blockchain I'm

talking about one of those perer A's

Pier B's Pier C's running that

blockchain software I'm talking about

one server running this technology and

again it's this network it's this

combination of these nodes interacting

with each other that creates this entire

blockchain what makes these so potent

too is that anybody can join the network

and that's why there's decentralized the

barrier to entry is a little bit of

Hardware requirements you getting the

correct materials to run the software

and then you running the software

anybody can join these networks and

participate and that's what makes it

truly decentralized in fact you can go

to GitHub right now and run your own

ethereum node in a few seconds now in

the traditional World applications are


run by centralized entities and if that

entity goes down or is maliciously

bribed or decides that they want to shut

off they just can because they're the

ones that control everything blockchains

by contrast don't have this problem if

one node or one entity that runs several

nodes goes down since there are so many

other independent nodes running that it

doesn't matter the blockchain and the

system will persist so long as there is

at least one node always running and

luckily for us most of the most popular

chains like Bitcoin and ethereum have

thousands and thousands of nodes and as

we showed in our demo if one node acts

maliciously all the other nodes will

ignore that node and kick that out or or

even punish it in some systems because

they can easily check everybody else's

note and see okay this one is out of

sync with the majority and yes majority

rules when it comes to the blockchain

each blockchain keeps a full list of

every transaction and interaction that's

happened on that blockchain and we saw

if a no tries to act maliciously then

all their hashes are going to be way out

of whack and they're not going to match


everybody else this gives blockchains

this incredibly potent a mutability

trait where nothing can be changed or

corrupted so in essence we can think of

a blockchain as a decentralized database

and with ethereum it has an extra

additional feature where it also can do

computation in a decentralized manner

now let's talk consensus proof of work

and proof of stake because you've

probably heard these before and they're

really important to how these

blockchains actually work when we went

through that blockchain example and we

did that mining feature this is what's

known as proof of work proof of work and

proof of stake fall under this umbrella

of consensus and consensus is a really

important topic when it comes to

blockchains consensus is defined as the

mechanism used to reach an agreement on

the state or a single value on the

blockchain especially in a decentralized

system I briefly alluded to this

consensus mechanism in our blockchain

example when I said if one changes

something and the other two don't then

majority Will Rule and kick that one out

this is part of that consensus mechanism

now very roughly a consensus protocol in


a blockchain or decentralized system can

be broken down into two pieces a

selection algorithm and a Cil resistance

mechanism that mining piece that we were

doing or or the proof of work algorithm

is what's known as a civil resistance

mechanism and this is what ethereum and

Bitcoin currently use please note that

depending on when you're watching this

if E2 is out then it's no longer proof

of

work now one of the other reasons that I

absolutely love working in this industry

is that we are changing things and we

are building things and we are growing

this Network all the time and as of

September of 2022 ethereum chain

actually migrated from proof of work to

proof of stake in an event called the

merge and I actually stayed up till 3:00

a.m. to watch this event it was a ton of

fun watching watching all the little

nodes work together and do this change

and actually go live but in any case

ethereum actually moved from proof of

work to a proof of State

Network now proof of work is known as a

civil resistance mechanism because it

defines way to figure out who is the


block author which node is going to be

the node who did the work to find that

mine and be the author of that block so

all the other nodes can verify that it's

accurate civil resistance is a

blockchain's ability to defend against

users creating a large number of pseudo

Anonymous identities to gain a

disproportionately advantageous

influence over said system and in

layman's terms it's basically a way for

a blockchain to defend against somebody

making a bunch of fake blockchains so

that they can get more and more Rewards

now there are two types of civil

resistance mechanisms that we're going

to talk about here namely proof of work

and proof of stake let's talk about

proof of work a little bit more in depth

first in proof of work this is silver

resistant because a single node has to

go through a very computationally

expensive uh process called mining which

we demonstrated earlier to figure out

the answer to the blockchain's riddle of

finding that correct nuns or or whatever

the blockchain system has in place in

proof of work this works because no

matter how many pseudo Anonymous

accounts you make each one's still has


to undergo this very computationally

expensive activity of finding the answer

to the proof of work problem or the

proof of work riddle which again in our

demonstration it was finding a Nuns with

that first four zeros but again each

blockchain might change the riddle or or

change the problem to be a little bit

different in fact some of these

blockchains make this riddle

intentionally hard or intentionally easy

to change What's called the block time

the block time is how long it takes

between blocks being published and it's

proportional to how hard these

algorithms are so these problems

actually can change depending on how

long they want the block time to be if a

system wants the block time to be very

very long they just make the problem

very very hard if they want it to be

very short they make the problem a lot

easier we'll talk about Cil attacks in a

little bit and how they can affect the

system but with proof of work it's a

verifiable way to figure out who the

block author is and be civil resistant

now you need to combine this with a

chain selection rule create this


consensus now there's some consensus

protocols that have more features but

very very roughly these are the two

pieces that we're going to look at the

second piece is going to be a chain

selection rule how do we know which

blockchain is actually the real

blockchain and the true blockchain now

Bitcoin uses a consensus algorithm

called Nakamoto consensus which uses a

combination of proof of work Cil

resistance and the longest chain rule

which is their chain selection Rule now

I do want to point out that when you go

out and you leave this course and you

leave the curriculum a lot of people

will just say bitcoin's consensus

algorithm is proof of work and this is

technically a little bit inaccurate

proof of work is just a piece of

bitcoin's consensus algorithm where the

actual consensus algorithm is called

Nakamoto consensus which includes that

combination of the longest chain Rule

and the proof of work civil resistance I

just want to give you the heads up that

in the real world a lot of people will

use them interchangeably it's not

exactly correct but we'll give them a

pass the decentralized network decides


that whichever blockchain has the

longest chain or the most number of

blocks on it is going to be the chain

that they use this makes a lot of sense

because every additional block that a

chain is behind it's going to take more

and more computation for it to come up

that's why when we saw in our

transaction we actually saw

confirmations the number of

confirmations is the number of

additional blocks added on after our

transaction went through in a block so

if we see confirmations as two it means

that the block that our transaction was

in has two blocks ahead of it in the

longest chain now now I do want to point

out that a lot of people use proof of

work as a consensus protocol and I do

want to say that this is a little bit

inaccurate but sometimes people use it

interchangeably proof of work is a piece

of the overall consensus protocol which

in Bitcoin and ethereum 1's current case

is Nakamoto consensus Nakamoto consensus

is a combination of proof of work and

the longest chain rule both equally and

very very important now proof of work

also tells us where these transaction


fees and the block rewards go to

remember how when we made this

transaction we had to talk about gas and

a transaction fee so who's getting paid

who is getting this transaction and this

transaction fee is going to the miners

or the validators in a proof of work

Network they're called Miners And in the

proof of stake Network they're called

validators they are a little bit

different and we'll get into that when

we talk about proof of stake in this

proof of Works system all these nodes

are competing against each other to find

the answer to the blockchain riddle

remember in our example it was to find a

hash that has four zeros at the start

and again depending on the blockchain

implementation that riddle is going to

be a little bit different but all the

nodes are trying as many as possible to

try to get this answer first why because

the first node to figure out the answer

to the blockchain Reel is going to get

that transaction fee they're going to

get paid from that now when a node gets

paid they actually get paid in two

different ways one is going to be with a

transaction fee and another piece is

going to be the block reward remember


how we talked about alternating the gas

price or the gay on our transaction well

that's the transaction fee that we're

going to pay to these blockchain nodes

for including our transaction the block

reward is given to these nodes from the

protocol from the blockchain itself

you've probably heard of the Bitcoin

having before the having is referring to

this block reward getting cut in half

and it's supposed to be cut in half

roughly every four years this block

reward increases the circulating amount

of whatever cryptocurrency that is being

rewarded for example on ethereum the

block reward is giving out ethereum and

on bitcoin the block reward is giving

out Bitcoin so these nodes are competing

against each other to be the first one

to find this transaction to be the first

one to find the answer to this problem

so that they can be the ones to win both

this block reward and your transaction

fee some blockchains like Bitcoin for

example have a set time when they're no

longer going to give out block rewards

and the miners or the nodes are only

going to get paid from transaction fees

now this gas fee again is paid by


whoever initialized the transaction when

we got our funds from the faucet there

was some server and somebody else was

paying the transaction fee for us

however when we sent ether from one

account to another our first account

actually paid some transaction fee to

send that ether in proof of stake

there's also a gas fee but it's paid out

to validators instead of Miners and

we'll talk about that in a little bit

now let's talk about two types of

attacks that can happen in these

blockchain worlds let's talk about the

first one being the cibil attack the

simple attack is when a user creates a

whole bunch of pseudo Anonymous accounts

to try to influence a network now

obviously on bitcoin and ethereum this

is really really difficult because a

user needs to do all this work in proof

of work or have a ton of collateral in

proof of stake which again we'll talk

about in a bit the other more prevalent

attack is what's known as a 51% attack

now as we saw as part of our consensus

protocol these blockchains are going to

agree that the longest chain is the one

that they're going to go with so long as

it matches up with 51% of the rest of


the network this means that if you have

the longest chain and you have more than

51% of the rest of the network you can

do what's called a fork in the network

and bring the network onto your now

longest chain now cibil attacks

obviously are when a single node or

single entity tries to affect the

decentral of the network by pretending

to be multiple different people although

they're just the same person or entity

and like I said it's really difficult to

do in proof of work and proof of stake

so you can see now that blockchains are

very democratic whichever blockchain has

the most Buy in and is the longest is

the blockchain that the whole system is

going to corroborate when nodes produce

a new block and add it to the longest

chain the other nodes will follow this

longest chain that the rest of the

network is agreeing with ADD those

blocks to their chain and follow up so

very small reorganizations are actually

pretty common when a blockchain picks a

block from a different longest chain

puts it on and then has to swap it out

for another block and and continue with

a different blockchain however if a


group of nodes had enough nodes or

enough power they could essentially be

51% of the network and influence the

network in whatever direction that they

wanted this is what's known as a 51%

attack and it's happened on blockchains

like ethereum classic which is not

ethereum this is why the bigger a

blockchain is the more decentralized and

the more secure it becomes so after you

watch this video and you become a

blockchain engineering expert I

definitely recommend you run a note as

well because you are going to increase

the security of the network as a whole

by running a node so proof of work is

fantastic because it allows us to very

easily protect against these Cil attacks

and keep our blockchains decentralized

and secure however it has some drawbacks

as well proof of work costs a lot of

electricity because every single node is

running as fast as they can to win this

race to get the rewards this leads to

obviously an environmental impact now

since proof of work in Nakamoto

consensus a lot of other protocols have

taken this idea and gone in a different

direction with a different civil

resistance protocol a lot of them with


the intention to be a lot more

environmentally friendly and the most

popular one right now is proof of stake

there are some chains that are already

using this proof of stake protocol and

that are live and thriving some of them

are like Avalanche salana polygon polka

dot so let's talk about proof of Stak

now again this is a different civil

resistance mechanism instead of solving

this difficult problem proof of stake

nodes put up some collateral that

they're going to behave honestly AKA

they stake in the example of ethereum 2

nodes put up some ethereum as a stake

that they're going to behave honestly in

the network if they misbehave in the

network they are going to be slashed or

removed some of their stake obviously

this is a very good civil resistance

mechanism because if you try to create a

whole bunch of anonymous accounts then

each one of those accounts you have to

put up some stake and if you misbehave

you're going to run the risk of losing

all the money that you put up as

collateral in this system miners are

actually called validators because

they're no longer binding anything


they're actually just validating other

nodes now unlike proof of work which

every node is racing to be the first one

to find the Block in proof of stake

nodes are actually randomly chosen to

propose the new block and then the rest

of the validators will validate if that

node has proposed the block honestly as

we saw with our cryptography lesson it's

usually very easy for other noes to

verify if a proposal or a transaction is

honest now proof of stake obviously has

some pros and cons as well Pros are that

again it is a great civil resistance

mechanism and a great way to figure out

who who the author of a block should be

the other Pros are that it's way less

computationally expensive to figure out

the new block because instead of every

single node on the network trying to do

this only one node needs to do this and

then the rest of the nodes just need to

validate it the cons are that it's

usually considered a slightly less

decentralized Network due to The Upfront

staking costs it costs to participate

now this gets into a little bit of a

philosophical battle on how

decentralized is decentralized enough

and I think that's up to the community


to decide and as we ress I think we'll

learn more and more about how

decentralized is decentralized enough

the general consensus amongst blockchain

Engineers though is that proof of stake

is very very decentralized and very

secure now there's another term that

might be the first time you heard it a

layer one we're going to talk about

layer ones and layer twos in terms of

scalability really quickly as well a

layer one refers to any Bas layer

blockchain implementation bitcoin's a

layer one ethereum's a layer one

Avalanche is a layer one these are the

base layer blockchain Solutions a layer

two is any application that is added on

top of a layer one added on top of a

blockchain some examples of layer twos

are going to be chain link arbitrum or

optimism arbitrum and optimism are very

interesting because they are layer twos

that also look to solve this scalability

issue arbitrum and optimism are what's

known as rollups and they roll up their

transactions into a layer one like

ethereum we're not going to go too deep

into rollups and how they actually work

but all you really need to know is that


they solve some of the scalability

issues by being another blockchain that

people can make transactions on still on

kind of this base ethereum layer now

they're different from side chains

because side chains derive their

security from their own protocols

rollups derive their security from the

Bas layers so arbitrum and optimism for

example is going to be just about as

secure as ethereum we're going to let

Kira go deeper into these layer ones and

these layer twos and these rollups and

all the differences between these in a

later lesson all right so we just talked

about a lot of stuff so let's do a quick

recap before moving on civil attacks are

prevented due to protocols like proof of

work and proof of stake 51% attacks grow

increasingly harder with the size of

blockchain so you should run a node

consensus is the mechanism that allows a

blockchain to agree upon what the state

of the blockchain is sharding and

rollups are solutions to scalability

issues on layer ones a layer one is any

base blockchain implementation like

Bitcoin or ethereum a blockchain

scalability problem is that there's not

always enough block space for the amount


of transactions that want to get in them

this leads to very high gas prices and

again gas prices are how much it costs

to interact with a

blockchain so that's it for the

blockchain basics and the blockchain

explainers with just this information

you now can go off into the world and

start working with blockchains and

interacting with blockchains with at

least some level of knowledge as to

what's going on you should be incredibly

proud of yourself for just making it

this far definitely be sure to give

yourself a pat on the back and a round

of applause now that we've gotten a lot

of the basics and the fundamentals out

of the way let's start jumping into the

coding aspect this is where you're going

to learn how to actually build these

smart contracts how to build these trust

minimized agreements in these

blockchains and in these smart contract

platforms this next section this

solidity Basics the solidity

fundamentals section will give you all

the skills to start actually coding

solidity and understanding how these

smart contracts work underneath the hood


so at this point absolutely give

yourself a high five maybe say hi in the

GitHub discussions maybe say hi in the

community on Twitter on Reddit Etc and

be proud of just making it this far the

journey has really only just begun but

you've already learned so much let's

begin the next section and let's jump

into the code

throughout this course so far we've

briefly mentioned a couple of terms

layer 1 or L1 layer 2 or L2 and rollup

so Patrick mentioned earlier that we'll

be working on sepolia to deploy our

smart contracts and interact with them

throughout this course but we will also

be deploying to and interacting with our

contracts on ZK sync sepolia sepolia is

a layer one or L1 test net and ZK sync

Folia is a layer 2 or L2 roller but what

do these terms actually

mean so a layer one or L1 is a

blockchain in its purest form where

there are nodes that contribute to Cil

resistance and help the chain reach

consensus as Patrick was describing

earlier the L1 is the base layer of the

blockchain ecosystem that works without

any additional plugins it's often

referred to as the settlement layer


because it's the layer of a blockchain

ecosystem that all plugins layers or

additional components eventually right

back to examples of L1 chains include

Bitcoin BNB chain salana Avalanche

ethereum is the chain that we be most

commonly working with throughout this

course and when we talk about layer ones

or l1s we're most often referring to

ethereum you can think of this L1 as

like the Hub of the ecosystem for

example in the evm OR ethereum ecosystem

The ethereum Manor is that Hub of the

ecosystem and anything that hooks back

into ethereum is known as a layer two or

L2 so a layer 2 is anything that is

built on top of the L1 makes sense right

the first layer of the ecosystem is the

layer one the second layer of the

ecosystem is the layer two it's

important to note here that apps

deployed to the L1 are not considered

l2s for example the popular

decentralized exchange Unis swap is not

considered to be an L2 but an app

deployed on ethereum this means that its

smart contracts are directly deployed on

ethereum a layer 2 or L2 is any

application that is built outside of the


L1 and then hooks back into it there are

different types of l2s such as L2

applications for example chain link like

Patrick was describing earlier chain

link is a decentralized Oracle Network

that brings offchain data onchain in a

decentralized way another type of L2 is

event indexing networks like the graph

which enables applications to access

onchain data but the most popular type

of L2 is an L2 chain or rollup and when

people mention l2s or layer tws they are

most often referring to rollups but what

actually is a rollup apart from the

fruit snack for you Americans out

there blockchain rollups are an L2

scaling solution that increase the

number of transactions on ethereum

without increasing the gas costs this is

achieved by rolling up multiple

transactions into one hence the name

rollup we'll explain a bit more about

how this actually works in a second but

first it's important to understand why

we need L2 chains or rollups so in an

Ideal World we need blockchain systems

to have three properties we need them to

be decentralized I.E not controlled by a

single centralized entity we need them

to be secure so the system is protected


against security vulnerabilities like

51% attacks where a malicious actor has

control over a majority of the network

over 51% cibil attacks where a malicious

actor creates multiple nodes to gain

control again by having a majority both

both of these attacks mean that the

malicious actor can control the network

to pass through any transactions they

like or reorder transactions and also

replay attacks where the same

transactions are sent more than once if

you don't understand how these

vulnerabilities work do not worry but we

will leave some resources in the GitHub

associated with this course if you would

like to know more and finally scalable

meaning that the system can grow without

sacrificing speed or running costs this

is known as the blockchain trilemma the

blockchain trilemma states that a BL

blockchain system can only ever have two

out of three of these properties for

example if the system is secure and

decentralized then scalability will be

sacrificed as is the case with ethereum

ethereum inherently has a scalability

problem it can only process

approximately 15 transactions per second


and as ethereum is gaining in popularity

the number of transaction requests is

increasing the gas cost to pay for these

transactions is increasing to jump the

queue and avoid long wait times if

blockchain system are to reach

mainstream adoption gas prices need to

be reduced even in the face of high

transaction volumes enter rollups

rollups aim to solve the trilemma

problem by increasing the throughput of

ethereum without sacrificing either the

decentralization or the security of the

system this is achieved by processing

the transactions off of the L1

blockchain and how does this work when a

user submits a transaction to a rollup

such as ZK sync an operator picks up

this transaction an an operator is a

general term and it can refer to a node

a set of components or entity

responsible for processing the

transactions this operator's job is to

pick up the transactions order them with

other people's transactions and then

bundle them together compress them and

then submit them back to the L1 such as

ethereum and so if ethereum rolls back

so does the rollup therefore they have

the security of ethereum by bundling the


transactions together this enables

rollups to handle transactions

efficiently because the gap cost

associated with the transaction is split

among all of the users all of the

transactions in the transaction batch

the validity of this transaction is then

checked on the L1 and this can work a

little differently depending on the type

of rollup there are two main types of

rollup and the difference between these

two lies in how the rollup checks the

validity of the transaction how they

check it is legitimate rather than

fraudulent the two main types of rollup

are optimistic rollups and zero

knowledge or ZK rollups

let's start with optimistic Roll-Ups

optimistic Roll-Ups assume that the

offchain transactions are valid by

default they're pretty optimistic

operators can propose what they believe

to be the valid state of the rollup

chain after this there is a time period

known as The Challenge period during

which operators can you guessed it

challenge the rollup transaction

operators can send a challenge by

Computing a fraud proof if they notice a


potentially fraudulent transaction this

fraud proof involves the operator

playing a call and response game with

another operator until they narrow down

the dispute to a single computational

step this computational step is then

executed on the L1 and if executing this

Step results in a different outcome the

state of the blockchain is different the

challenging or disputing operator wins

The Challenge and the fraud proof

succeeds if the proof succeeds the

rollup will re-execute the batch of

transactions and the operator

responsible for the incorrect

transaction inclusion will be penalized

this is usually done using some kind of

staking mechanism where operators send

tokens to a Smart contract that are held

to say yep I'm going to act honestly and

then if they don't their tokens are

taken away from them this is known as

slashing which Patrick has mentioned

previously and this works the same on

optimistic rollups if the transaction

proposals are not invalidated during

that challenge period Then the proposals

are assumed to be correct so now let's

move on to zero knowledge or ZK rollups

zero knowledge or ZK rollup solution


prove each transaction batch to be

correct using validity proofs or ZK

proofs ZK proofs in this context are a

complex mathematical cryptographic

problem and at this stage we do not need

to understand how they work we can just

think of them purely as some math magic

that just works ZK proofs involve two

participants the prover which is the

entity that is trying to prove that they

know something and the verifier which is

the entity that is verifying that the

prover does in fact know the answer to

to the problem the answer to the problem

is often referred to in ZK proof world

as the witness in the context of ZK

rollups the prover is an operator and

the verifier is just an L1 contract so

for each transaction batch that is

submitted to the L1 a validity or ZK

proof is computed by approver and

verified by the verifier or the L1

contract this ZK proof then confirms the

transaction validity as we said this is

just some maths magic but if you like to

understand a little bit more about how

that works we will leave some references

in the GitHub repo but essentially what

happens the problem is boiled down to a


single mathematical equation meaning

that the prover can then prove that

their input satisfi this problem and

then the verifier can say yes the output

is as expected and the proof succeeds

but again you don't need to understand

how that works at this time you can

literally just think of it as some math

magic and so to summarize rollups help

scale ethereum by processing

transactions off chain bundling them

together and then submitting them back

to to ethereum with some kind of proof

which is different depending on whether

it is an optimistic rollup or a ZK

rollup one of the types of operators

associated with rollups is a sequencer

the sequencer usually refers to the

operator which is ordering transactions

and sometimes bundling them together now

in some rollups this sequencer is in

fact centralized so it's controlled by a

centralized entity this can be

problematic because it can lead to

things like censorship where the

centralized entity is stopp stopping

some users transactions from being

passed or it can manipulate the order of

transactions for their own gain so

something like you being unable to


withdraw because they're blocking your

withdrawal transaction could occur the

other issue is that if the sequencer is

centralized then if the sequencer goes

down then no one will be able to pass

through any transactions at all

withdrawals can't happen and this can be

extremely problematic because what if

withdrawals are halted for a day a week

a year forever are the funds then worth

anything if you can't with draw them and

these are just a few problems with

sequences being centralized and this is

why projects like ZK sync are working

right now to decentralize their

sequences L2 chains or rollups are

graded based on certain properties and

given a stage now for this section we

are going to be going through the L2

beat website which you can see at L2

beat.com scalings summary and here you

can see all of the different chains

there stages and lots of different

information that we will be going

through in a second so the stage of a

rollup is a categorization framework

based on vitalic proposed Milestones it

is an opinionated assessment on the

maturity of the rollup by the l2b team


and its purpose to create an incentive

for projects to work towards

decentralization and they have proposed

three stages stage zero full training

wheels in stage Zero The Operators and a

security Council prominantly manage the

rollup this is like a committee of

members who can make decisions in the

case of bug bugs or problems or upgrades

and so in stage zero the management of

the rollup is pretty centralized what

about data availability data

availability refers to the confidence a

user can have that the data required to

verify a block really is available to

all Network participants so in terms of

rollups this transaction data needs to

be available in order to be able to

verify the transactions so for stage

zero rollups there needs to be

open-source software to enable State

reconstruction of the L1 data to ensure

both trans transparency and also the

verification and finally in stage zero

in the case of an unwanted upgrade users

have less than 7 days to exit the system

exiting in this context refers to the

users withdrawing their funds from the

system and in stage zero this usually

requires some kind of operator


coordination so some entity is going to

have to help them exit the second stage

is stage one bit confusing with the two

but it's called stage one enhanced

rollup governance so in stage one the

rollup is starting to be governed by

smart contracts the Security Council is

probably still in place for things like

bug resolution but it is starting to

become more decentralized in stage one

the rollup has a fully functional proof

system with a decentralized fraud or

validity proof submission system now in

stage one a user can exit without

coordination from an operator in the

case of these unwanted upgrades now the

final stage stage two is no training

wheels smart contracts now fully manage

the roll up it's pretty decentralized at

this point and so the fraud or validity

proof system is completely

permissionless and users are now given

ample time to exit in case of unwanted

upgrades there usually is some kind of

Security Council where its role is

strictly confined to addressing errors

that can be adjudicated on chain meaning

that users are now protected against

governance attacks and so if we look


through this l2b nice little table here

then we can see what stage all of the

different rollups are at so for instance

ZK sync era is a stage zero rollup so if

we click into this then we can see a

summary of this rollup and you'll notice

here this pretty little pie chart let's

go through what this means this pie

chart is a nice little visualization of

the risk analysis for this rollup so

let's go through all of these little

pizza slices so First Data availability

so can the L2 State be reconstructed

from the data that ZK sync submits to L1

and because it's green yes it can so the

difference in state before and after the

bundle of transactions is submitted is

published on chain so the proof can be

constructed State validation so have we

checked that these bundle of

transactions is legitimate rather than

fraudulent has the state or the state

differences been validated to be correct

and in the case of ZK sync yes because

they use ZK proofs they use a plonk zero

knowledge system which is just the fancy

algorithm with kzg commitments this is

all just like the mathematical magic

that happens but yes it's proved to be

correct so it's green zoom out of touch


so we can see the text box but sequencer

failure so first of all what's a

sequencer a sequencer is a type of these

operators that we were talking about

earlier and it usually refers to the

operator that is ordering the

transactions and sometimes a sequencer

can bundle the transactions together as

well but in general it's talking about

the ordering of the transactions so what

happens if this sequencer goes down can

I a user get my money out so users can

submit transactions to the queue but you

can't force them through through they

still need the sequencer there to get

their transactions through the sequencer

can't pick and choose transactions and

selectively skip them but it could stop

processing any transactions at all so if

it's down then no one can get any

transactions through and no one can

withdraw their funds move their funds or

do anything no transactions can go

through so it's yellow because they can

submit them to the l1q but they can't

force them through essentially so that's

why it's yellow proposer failure so the

proposer is another type of operator and

it's operator responsible for proposing


the new state of the rollup so what

happens if this goes down what if we

can't propose new state so because they

have a whitelisting system on ZK sync

only whitelisted proposers can publish

State Roots so new state of the

blockchain on the L1 so in the event of

a failure then no one can get their

money out withdrawals can't happen no

transactions can happen so this is

obviously a big problem so it's red and

finally exit window so like we were

saying earlier the exit window is how

long does a user have to withdraw their

funds to exit from the system to not be

using the chain anymore and so for ZK

sync in the case of unwanted upgrades

the contracts are instantly upgraded and

so there's no window for users to exit

so it's red so if we zoom out again and

we look at this page then we can see a

nice summary of the rollup so we can see

the total value locked the activity on

the chain on chain costs so like the gas

costs the Milestones so for instance on

the 13th of March ZK sync era started

using blobs you don't need to know what

blobs are at this point but they're

super cool so I'm going to give you a

quick teaser we will be covering blobs


in a later part of this course so stay

tuned for that but essentially blobs are

like massive massive chunks of data

which aren't submitted to ethereum

they're like a side card to the

transaction they tag along but they're

not stored on chain forever because

they're massive instead a hash of all of

the data is submitted to ethereum to

compute the proofs so you can see for

rollups how useful this is because if

you've got a massive bundle of

transactions then you can have all of

that information without having to store

it all on chain introduction of the bjam

prover this is just their prover the

code and they had their Alpha launch of

the chain which is cool and then you can

see the risk summary and the risk

analysis that we were going through

earlier now if we scroll down to rollup

stage we can see that it's a stage zero

rollup and so you can click in and see

what requirements they have met and what

they need to do to move to a stage one

so we were saying with those

permissioned operators earlier

so they can censor withdrawals so that

needs to be fixed and then also in the


case of upgrades they're not given any

time to exit the system like we're

talking about earlier now the final

thing to say about rollup stages and l2b

is that these stages do not reflect the

security of the rollup it is purely an

opinionated assessment of the maturity

in order to push these protocols towards

decentralization now because the batches

of transactions are submitted and proven

on ethereum and so that is everything

you need to know about L1 l2s and

rollups that was a lot of information

for you all so now is probably time for

you guys to take a break and try and

digest some of that information because

I know there are a lot of new terms here

if you need to watch again go ahead

because there is a lot of information

here that is pretty complex and so as

Patrick says and will say a lot of times

throughout this course go get yourself a

snack go get yourself a drink a coffee

some ice cream take yourself on a little

walk and have a break and then come back

when you're all refreshed and we can

continue because it is time for us to

make our very first transaction on ZK

sync testet and I'm super excited about

it so I will see you in a second for


that the final section oh no second to

last and now it's time to make our very

first transaction on ZK sync testnet the

ZK sync testnet is sometimes called ZK

sync sepolia ZK sync era testet I'll

probably use the terms interchangeably

but ZK inoo ZK SN testnet they're all

the same thing some of the things that

we're doing here are going to be

repeated from earlier in the course but

repetition is key in order to get this

information drilled into your brain so

first let's go ahead and add ZK sync

aoia to our metamask so that we can see

the transaction summaries see our

balance and things like that from inside

metamask okie dokie the very first thing

that we need to do is we need to add ZK

sync superia to our metamask so that we

can see all of our transactions and

everything that's going on inside our

wallet including our balance so what

we're going to do is we're going to head

to chain list.org and make sure that we

have got this include test Nets box

checked and then we need to search for

ZK ZK sync and here we can see ZK sync

saoo testnet which has got the chain ID

of 300 so if you click in here and then


we're going to connect our wallet and

we're going to confirm that the site can

have permissions to our wallet and then

we can click approved to allow this site

to add a network so this is going to add

the network to our metamask and then we

are going to switch over to ZK sync

ofoia when we click inside our wallet

you'll be able to see a summary of the

balance and all of the tokens nfts and

activity going on inside our wallet and

it's that easy that simple now the

second thing we want to do is we want to

be able to see transactions and

contracts in more detail like we did on

sepolia with ether scan so the block

Explorer equivalent to Ether scan on ZK

sync and ZK sync aoia can be found at

explorer. ZK sync. for mainnet and then

if we switch over in this little drop

down to ZK sync era seia then it's sea.

explorer. ZK sync. for zync sepolia and

if we grab our wallet address then we

can paste that in the search here and

we'll be able to see a summary of our

account so when we send our first

transaction it will come up here so now

what we need to do to send our first

transaction is get some funds and this

is going to be our first transaction is


getting funds so there are two ways that

we can get test net funds on ZK sync

sepolia the first is a bit like sapoia

and we can use a faucet directly faucet

fet I never know how to pronounce it but

these can be a little bit temperamental

the one that's recommended on the ZK

sync documentation here requires an API

key and there's another one that

requires us to sign in with GitHub both

things that we don't really want to do

so we're actually going to use a

different method which is bridging but

Cara what is bridging let me tell you

right

now so what we're going to is we're

going to get some funds from sepolia

we're going to get some seoa eth in the

same method that we did so before and

don't worry I'm going to take you

through step by step how to do it again

and then what we're going to do is we're

going to bridge those funds over to ZK

sync ofoia but I still haven't explained

to you what bridging is let me do that

now bridging means taking the funds from

one chain and then getting them on the

other chain now we not actually taking

those funds and literally moving them


we're using a mechanism now there's two

main types of bridging mechanisms the

first is a locking and unlocking method

and what happens here is that the tokens

are locked on the source chain so

they're locked inside a smart contract

and then they're unlocked on the

destination chain they are released from

a smart contract and sent to your wallet

from the destination chain now you might

imagine that this could be a bit of a

security concern because what if the

smart contract is hacked and my tokens

that are locked on the source chain

contract are taken now this can happen

but you just have to make sure that the

protocol you're using is heavily audited

and tested now the second method is a

minting and Burning Bridge and what

happens here is on the source chain the

tokens are burned so they are sent to

the zero address they're taken out of

circulation they're destroyed they are

no longer and then tokens are minted on

the destination chain they're given to

the user on the destination chain

they're created they're brought into

existence and if you don't understand

what I mean by burning and minting don't

worry this will be covered extensively


in a future course we go through ERC

20's minting and burning and all of

these different things and tokens later

down the line so you don't need to know

100% how it works all you need to know

is that the tokens are actually removed

on the source chain and then created on

the destination chain now here the

bridge protocol needs to have control

over the supply of the tokens in order

to be able to burn them and mint them so

for instance an example of this is cctp

created by the circle team where usdc is

burned and minted in order to create a

bridge in which their Bridge implements

a burn and mint Bridge mechanism and

this can occur because the circle team

have control of the usdc supply but

enough about bridges for now and so

let's continue and actually Bridge our

funds from sepolia to ZK sync sapoia and

what we're going to do is we're going to

get some sepolia eth from a faucet and

then we're going to bridge it to ZK syn

sepolia to get some ZK sync sepolia eth

that's a lot of words let's do that now

so like I said the first thing we need

to do is we need to use a faucet what

we're going to do is we're going to use


the Google Cloud theola faucet as of

recording this this is the best faucet

to use but if you check the GitHub repo

associated with this course we will keep

it updated with the best faucet on spia

for you guys to use so head there if you

want to check what the current best one

is as I said this is the best one for

right now so we're going to select the

network as seia and then I'm going to go

into my metamask and I'm going to click

this little button to copy my address

associated with my wallet and I'm going

to paste it in here and then I'm going

to click this button that says received

0.05 sepolia eth so you may have had a

little flag come up that says you need

.01 eth on Main net and what you need to

do is just wait around 10 to 20 minutes

and then come back and try again and

this is to prevent some kind of like Cil

attack where people are creating

multiple multiple accounts and then just

draining the faucet by using newly

created wallets instantly to try and get

funds so now our test net tokens are on

the way and we're actually doing a

transaction on sepolia as before so

these are all the steps that we've

already done and so now we've sent the


tokens and we can check inside our

wallet and what we'll have to do is

switch over to sepolia testnet and you

can see amazing we now have 0.05 sepolia

eth and now we need to take those tokens

and we need to transfer them to ZK sync

ofoia to get some ZK sync ofoia E how do

we do that we need to use a bridge so

we're going to head to portal. ZK sync.

ibridge to bridge our funds and this is

going to be a lock and unlock method

thir Bridge up in this right hand corner

we're going to click this little down

arrow and then switch it to ZK sync

sepolia testnet Okie doie we are going

from ethereum sepolia testnet to ZK sync

seoa testnet I'm going to transfer

0.025 sepolia eth to ZK syn ofoia first

of all I need to connect my wallet so

you can connect so click connect your

wallet confirm that you'd like to

connect okay so now that we've connected

our wallet we can click continue and

then we're going to click I understand

proceed to bridge because we have made

sure that our wallet does support ZK

sync aolia test net because it's

metamask it does so I understand now we

can just confirm the transactions it's


good practice to read through so yes

this is the amount I wanted to send from

my sepolia testnet account to my ZK sync

aoia testnet account by the way notice

here the addresses are the same so we'll

click bridge now then we can confirm

this transaction in metamask and now we

can see a nice little visual of this

transaction occurring okay so now that

it says the transaction is complete

we're going to head back over to the ZK

sync sepolia block Explorer and we're

going to paste our wallet address into

the search bar and we can see that we

have in fact done our very first

transaction amazing so we can see here

it's proess on ZK sync and we can see

that we've gone from our L1 address on

sepolia to our L2 address on ZK sync

with a value of 0.025 eth with a fee a

very very small fee and so we're going

to click into the transaction hash and

you can see here the information about

the transaction including the hash the

status which we're going to go through

in a second the block number the batch

so that's like the bundle of

transactions from to our addresses on

the different chains the tokens

transferred the input data the value


which was the amount that we sent the

fees gas limits nons and when it

happened so four minutes ago so what

does this status mean it says on ZK sync

error it's processed but then on

ethereum it says this weird thing or

it's like sending validating executing

how come

I have the funds in my metamask and it's

processed on ZN K but on ethereum like

this doesn't make any sense K what is

going on I'm confused well let me

explain to

you so if we head back over to the ZK

sync documentation and we head to zync

stack Concepts finality and that will

explain to you what these two little

sections mean so finality in a

blockchain system as it says here refers

to the time taken from sending the

transaction to when the transaction is

considered settled so therefore it can't

be altered reversed cancelled and so on

ethereum this is approximately 13

minutes now what about on ZK sync era or

ZK sync sepolia so finality is tied to

ethereum finality as we were explaining

a little earlier so from the time taken

to sending a transaction to when the L1


smart contract updates the L2 State what

is this time frame and so this has a

couple of steps that it's breaking down

here so first of all after the users

submit the transactions they need to

fill up the batch that takes a few

minutes that batch of transactions needs

to be committed to ethereum then a proof

needs to be generated and submitted and

verified by the ethereum smart contract

and then finally the batch is finalized

and this can take approximately 24 hours

and these steps correlate to these

sending validating the proof and then

executing and finally achieving finality

that's what these steps are referring to

is this breakdown here now you may say

to me K that makes sense it makes sense

to me that it takes approximately 24

hours for all of this to happen so how

come it says it's processed on ZK sync

era and you still haven't really

explained to me how come I can see a

balance in here you just told me that it

was going to be 24 hours and yeah that

sounds super confusing and the answer is

again in the ZK sync documentation this

instant confirmation section so even

though the finality is around 24 hours

you can consider your transactions


submitted as having instant confirmation

so that they can be instantly displayed

in the UI even though they're kind of

unconfirmed and you can consider these

assets is immediately transferred and

you can make further transfers but you

should be cautious and wait for full

finality because things can be rolled

back and you shouldn't consider them

fully received until you have full

finality and so that's why here we have

this instant confirmations where we have

the funds it says it's processed on ZK

sync era but it's not fully final the

transactions haven't been validated

using the ZK proof and so that's what

these steps are referring to here so now

you have sent your very first

transaction on ZK syn OFA that is

amazing now there is a lot of

information to digest here but the very

last thing that I want to explain to you

is why we are doing this why are we

interacting with ZK syncs ofoia why are

we going to be deploying our contracts

to ZK syncs ofoia throughout this

course now I just want to make a brief

disclaimer to say that ZK sync are

kindly sponsoring updraft in order to


bring you the highest quality most

amazing content to become the best smart

contract developers in the world now

here at cyphon we would only ever

recommend to you tools and chains and

applications that we think are the best

and that we ourselves would use and so

there is a number of reasons that we

will be using ZK sync and ZK sync ofoia

to deploy and interact with our smart

contracts and working with throughout

this course let's give a little

breakdown of this right now because I

don't expect you to just take our word

for it you can make your own judgment

we'll give what you are reasons why and

then you can understand the reasons why

we're going to be doing this so as we

have discussed ZK sync era is a layer to

ZK rollup and there are four main

reasons that we think that you guys

should be using ZK sync eror first of

all security so as we were saying

earlier the security of ZK sync error is

directly inherited from ethereum if

ethereum detects an issue and rolls back

so does ZK sync error the transactions

are verifiably legitimate as ZK sync

uses cryptographic validity proofs to

prove that the transaction is legitimate


secondly it's evm compatible now when

you compile your smart contract it

doesn't compile to evm B code which you

don't really know need to know what this

means but instead it compiles down to ER

VM bik code which is like a ZK sync

special version the ZK sync compiler K

Suk can compile and understand solidity

and this means that you can take your

smart contracts that you've written in

solidity and deploy them to ZK sync era

without really making any adjustments

there are a couple of really tiny

nuances here but we will be walking

through them so you don't need to worry

about that at all thirdly ZK sync

supports ethereum wallets out of the box

so no need to create a special wallet

what does this mean for you it just

means that you don't need to create

anything special you can just use your

metamask as we were earlier and your

address will be exactly the same which

again we saw earlier the address on

ethereum will be the same as on ZK sync

era your address on saoo will be the

same on ZK sync sepolio and there's

nothing you to do it happens

automatically now the fourth reason and


in my opinion the best reason is that it

is low cost and scalable as we were

talking about earlier due to the trans

transactions being bundled up together

the gas costs are split among all of the

transactions in the bundle meaning that

is super low cost and what does this

mean for you it means that users

interacting with your protocol don't

have to pay really high transaction fees

as the network grows you're not going to

have issues so when everyone else is

deploying their protocols to ethereum

and then down the line as the system

grows like we want it to and we're

gaining more and more users they're

going to have to Port their users over

to a rollup solution which hopefully is

also verifiable like ZK sync using ZK

proofs now you because you guys are

clued in because you're here at updraft

won't have to do that cuz you guys are

already on ZK sync so as the system

grows you're not going to have any

problems your users are not going to be

faced with really high transaction fees

you're not going to have really high

transaction fees in order to interact

with your contracts or upgrade them and

this is the true power of ZK sync and


that's why ZK sync are our recommended

chain and thank you again for ZK sync

for sponsoring if you'd like you can

also deploy to your own favorite rollup

whether that's arbitrum optimism or

scroll or any of the other rollups that

are evm compatible out there and so now

you have everything that you need to

know about l2s and rollups and ZK sync

era and why we will be using it

throughout this course and so that was a

lot of information again you can go

ahead and take a break in order to

digest this information but I will pass

you back over now to Patrick and I'll

will see you again later in this course

so that's it for the blockchain basics

and the blockchain explainers with just

this information you you now can go off

into the world and start working with

blockchains and interacting with

blockchains with at least some level of

knowledge as to what's going on you

should be incredibly proud of yourself

for just making it this far definitely

be sure to give yourself a pat on the

back and a round of applause now that

we've gotten a lot of the basics and the

fundamentals out of the way let's start


jumping into the coding aspect this is

where you're going to learn how to

actually build these smart contracts how

to build these trust minimized

agreements

in these blockchains and in these smart

contract platforms this next section

this solidity Basics the solidity

fundamental section will give you all

the skills to start actually coding

solidity and understanding how these

smart contracts work underneath the hood

so at this point absolutely give

yourself a high five maybe say hi in the

GitHub discussions maybe say hi in the

community on Twitter on Reddit Etc and

be proud of just making it this far the

journey has really only just begun but

you've already learned so much let's

begin the next section and let's jump

into the

code welcome to the ultimate smart

contract developer security researcher

full course and platform python Edition

now this course is especially exciting

to me because this is the python and

Viper Edition something that we haven't

done before in the past in the past 5

years that we've been doing this we've

done python but never Viper now python


is positioning itself to be one of the

most important languages to learn in the

coming years in the age of AI when it

comes to financial technology companies

like hedge funds or asset managers all

the portfolio managers or Traders

they're using python why because python

is very easy to read easy to script and

it's a production language to build very

powerful applications with and

additionally looking at the AI landscape

python is dominant there as well with

tools like pytorch and tensorflow and

all these libraries and packages built

specifically around the AI landscape I'm

also looking forward to advancements in

languages like Mojo which are going to

be languages literally built to run in

the AI environment so you who is

watching this video right now you are

setting yourself up to have an edge over

all these waves of people coming in

because you are learning this technology

of the future with python and

specifically with Viper now we'll learn

more about Viper in the coming videos

but basically Viper is a smart contract

development language so we're actually

going to learn Viper and learning Viper


you will learn python along the way

which is very nice so if you have zero

python experience us teaching you Viper

here will also teach you some python now

there are some differences between the

languages between Viper and python

however a lot of the syntax is going to

be very similar so whether you're brand

new to python whether you're brand new

to Viper this is the course for you now

it would be beneficial if you had a

little bit of python experience before

jumping into this that's going to make

your life a lot easier you're going to

move a lot quicker there are plenty of

courses on free code camp that will

teach you these things along the way

however I'm going to assume that you

know nothing about python I'm going to

assume that you're a beginner python

developer that way you can follow along

and you can learn production

professional python code as well in this

curriculum too now that being said if

you do already know python which that's

great as well you can skip over some of

the sections where we teach you Python

and at the beginning of those videos I

will label them saying hey we're going

to teach some python skills in this


lesson feel free to skip now a question

that you're probably asking is why Viper

why would I learn Viper over solidity

looking at this chart here as of

recording Viper has around three % of

the total tvl of smart contracts

basically what this means is not a whole

lot of money is in Viper Smart contracts

however the reason you would want to do

this is because there are a couple

applications that have a ton of money in

Viper Smart contracts curve one of the

largest dexes out there is built

exclusively on viper Lido one of the

largest staking platforms is built with

a lot of Viper urine Finance as well has

a lot of Viper Viper by its nature is

meant to be easy to learn easy to read

easy to write and very easy for AIS to

understand and importantly very easy for

security researchers to understand so

that your smart contracts have fewer

bugs in them which in the smart contract

space is incredibly important because a

single bug can mean you lose millions of

dollars and additionally because Viper

is in this python tooling world you are

going to step in to the AI to the

finance to the fintech world and have


all these powerful pythonic Tools in

library

at your disposal already so jumping into

the python and Viper landscape will set

you up for this future of AI and finance

so I am incredibly excited for you to be

on this journey with us here learning

Viper learning smart contract

development because we've got a lot in

store for you welcome to Viper

fundamentals at the end of Viper

fundamentals you will understand the

basics of Viper you'll even learn a

little bit of python without even

knowing it you'll learn some tools and

techniques for interacting with AI to

help you write your smart contracts help

you write your code you will have

deployed your first three smart

contracts yourself and you'll be ready

to move into a more professional

environment and just by you being here

just by you writing your first line of

code you are a smart contract developer

and welcome to web 3 and if you missed

this section during blockchain Basics

let's go ahead and get started with some

best practices so that we can set you up

for success for learning here

now if you're watching this on cyphon


updraft you can go ahead to the course

resources here which will bring you to

this moccasin full course CU which is

known as a GitHub repository and in here

any single time in any of the sections

throughout this entire course you can

scroll down in here there's a little

table of contents let's go down uh

section zero welcome to the course uh

here we go welcome to remix favor list

at all of these different sections are

going to have a code base associated

with it so if you click on section one

here welome to remix remix favorites CU

you'll get this little repository here

which is going to have some code in this

favorites.i and this will be the full

code that we will learn throughout this

section and if you're watching this on

YouTube this of course will be in the

description so again if you're in

Moccasin full course CU you can scroll

down you can even probably click on the

table of contents go to section one

welcome to remix favorites list the

final code will be in here and instead

of making any issues or poll requests on

this if you have any discussion points

just one more time again come back to


the mckas and full course see you and go

to the discussions tab in here now

throughout this course when it comes to

asking questions we're both going to

teach you how to ask questions so that

you can have the best chance of success

when working with other humans but also

obviously with AI AKA artificial

intelligence I highly recommend that you

pause the video right now and make a

account for at least GitHub GitHub is

going to be something that is crucial to

the success GitHub is something that's

going to be crucial to your success as a

smart contract developer or just

technical person in web 3 and then

additionally if you want to work with

AIS we will be working with AI

throughout the course as of recording

our favorites are Claude and cursor but

you'll see that we actually use chat

quite often in this as well

typically in each section I'll give you

a brief rundown of the final code that

we're going to be working with in this

section and in this section you're going

to deploy your first smart contract ever

yes you're actually going to deploy it

this is the final smart contract that

you're going to deploy yourself we're


going to be using this site remix.ogg

aka the remix IDE to be building our

code base here and I highly recommend

that you follow along coding with me and

even try to do some coding yourself as

we go on here remember both on Cypher

updraft and on YouTube you can change

the speed that I'm talking so that I go

the correct pace for you if you write

out the code with me as I'm talking as

I'm coding it it'll ingrain that

knowledge in you and that knowledge is

crucial for you to understand how to

build these systems and how to build

Advanced systems and then how to correct

AI as well repetition is the mother of

skill and I want to make sure you come

out the other side with skill and there

will of course be a link to this in the

remix favorites CU GitHub repository you

can just click go to remix here and

you'll pop up over in the remix Link at

the end of this you'll have written your

first smart contract you'll have written

your first bit of Viper and we are very

excited for you to get through this

first

part welcome to the remix IDE or

integrated development environment for


the next several sections this is where

we're going to be living because this is

a phenomenal tool to really help us

visualize these smart contracts along

the way we're going to be working with

the co-instructor of this course smart

contract programmer or at smart contract

programmer on YouTube who's also a

member of the cyphon team he's going to

be teaching us a lot of the Viper syntax

and then we're going to go use what he

teaches us in our smart contracts that

we actually build so if you're getting

started here just go ahead and type

learning discovering web development and

let's go ahead we actually get opened up

with a welcome to the remix IDE tutorial

if you'd like to go through that gives

us some helpful tips like looking at the

solidity compiler the deployer tab and

others

additionally remix comes with this remix

AI now as I've been saying AI is

incredibly helpful for us building our

smart contracts and we should be using

AI tools as we learn and as we grow it's

phenomenal to take Ai and ask a

questions if you don't understand things

now what's important though is you still

need to understand everything at the


core because because the more advanced

you get the harder of a Time AI has so

you need to understand all the

fundamentals so that so that when AI

gets gets things wrong which it does you

actually know how to fact check and

correct your AI now to get started we're

going to click this little file explore

button which when we click it you'll see

a group of files and folders here the

left- hand side over here is where we're

going to start beginning with our coding

and all these folders and files over

here are example solidity and JavaScript

files and folders however we're not

going to be working with solidity we're

going to be working with Viper again

we're trying to be pythonic here so I'm

going to go ahead and I'm going to click

each one of these and either right click

and select delete hit okay or just click

and then hit the little Trash delete

icon here to actually start deleting

these and I'll zoom in a little bit so

that we can do that delete and then

we'll click delete here and we'll click

delete here and then we'll click delete

here this way we have a little blank

section on the left hand side here now


additionally this little remix AI is

kind of in my way here so I'm going to

zoom out a little bit and I'm going to

hit this little drop down so that it's

out of the way going to zoom back in and

you can see if anytime you want to ask a

question you can go ahead and click the

little the little icon I'm not really

sure how to minimize it at the moment

without zooming out minimizing it and

then zooming back in I'm sure they'll

fix that soon but if you want to give it

a try you could even say how do I create

create a

minimal Viper Smart contract smart

contract and deploy it in remix and

it'll give us an output like this it

even has a little copy text button and

you can see this is where AI starts to

show a little bit of its flaws it says

Hey to create a simple Viper Smart

contract using remix ID go to remix

click new file choose Viper as the file

type and name your contract minimal

contract dead by and then add this code

and if you're just learning you might

look in this and you go oh okay cool I'm

going to copy paste that but this is

actually solidity code so we need to

understand how all this code works so


that when AI gets it wrong we know how

to correct it so now though let's go

ahead and let's create our first smart

contract let's go ahead and close out of

this remix home here we'll hit this

create new file again in our file

explorer section create new file and

we'll call this

favorites. VI we're going to make a very

simple minimal smart contract The Vi at

the end is what known as the extension

of this file and it's how remix and

other tools are going to know that this

is a Viper Smart contract and we're

going to be writing Viper inside of this

file which again Viper is one of the top

smart contract programming languages if

we click this favorites. VI on the right

hand side here we get this little area

to start typing where we can you know

type some stuff in here and this is

where I want you to type along with me

right below the file explorer is a

little search and files section where if

I were to type hello in favorites.i and

I we're look for hello and files to

include our star. soul star. JS and

star. VI and I hit enter we see there's

one result in one file in favorites. VI


we have this line here hello it says one

result if I were to do like hello hello

and now go back we hit enter oops hello

hello we now see showing three results

in one file and it shows us the

different lines that

this is found on let's go ahead and just

delete all of that I'm doing a little

keyboard shortcut right below that is

the solidity compiler now this is not

what we're going to be working with in

this course if you would like to learn

solidity we have a solidity course on

Cypher updraft but instead what we're

going to actually do is scroll all the

way down to the bottom here to this

little plug-in manager button and we'll

click this and we'll look up Viper and

we see there's inactive modules Viper

compiler we're going to go ahead and

activate this and now if I zoom out a

little bit more we now see this Viper

compiler on the left hand side here you

zoom in and if you're zoomed in you'll

have like a little button which if you

click it it'll drop you into the Viper

compiler this is what we're going to

need to compile our smart contracts here

and additionally we could see even more

advanced configurations if you had this


Advanced compiler settings you could set

up your own local Viper compiler but

we're just going to use the remote

compiler for now let's go ahead and

we'll just double click this little

Viper compiler button so that we just

see our favorite St VI and let's go

ahead and click this little hide

terminal button as

well now the first thing that you're

going to need to do in any smart

contract whether it's Viper solidity or

anything like that is you're going to

need to type the version if you're

familiar with python you'll actually be

familiar with this syntax we're going to

do a little hashtag or pound symbol here

to start a comment this is incredibly

important so that we know we're working

with a certain version of Viper where

some features are supported to tell

remix what version of Viper we're going

to be working with we need to type

pragma version

0.4.0 for most of this course we're

going to be using

0.4.0 and there's a couple ways for us

to do this we can do # pragma version

0.4.0 we can just do version


0.4.0 we can do pragma version with this

little carrot here little carrot symbol

which means

0.4.0 and up so any version after 0.4.0

0 AKA

0.4.1

2.3 51 1 51 Etc as of recording there's

not very many versions after 0.4.0 so

we're just going to stay with

0.4.0 there's a couple other ways to

write this including like ad version but

for now let's just do # pragma version

0.4.0 there's a lot of code out in the

world right now on

0.310 but the versional Viper that we're

we're going to be working with 0.4.0 has

so many cool features that most of the

code that we're going to write here

probably won't be compatible with 0.310

and Below now with this pragma version

0.4.0 we're telling our compiler we're

only going to use 0.4.0 so anotherone of

this little hat stuff none of that only

0.4.0 when you're writing production

code it's good to pick a very specific

version so that you know exactly what

your compiler is going to do and again

that'll start to make sense later as we

learned

more now this little hashtag Here is


known or or pound symbol makes this

whole line here what's known as a

comment and typically a comment is a

line in your code where you can write

pretty much whatever you want and the

compiler will ignore it the compiler

doesn't ignore these lines if it sees a

comment and this pragma word or the a

comment and this version word so these

are some key words with comments but

every other line you can type pretty

much whatever you want and in Python

these are also comments so again like I

said if you don't know python learning

Viper you'll also Learn Python I highly

recommend that as you're typing and

going along with me you use these

comments to leave yourself notes so

maybe you say this is how we tell the

Viper

compiler what version to use like this

this way you can leave yourself little

notes and then you can also maybe copy

right click and hit copy all this maybe

open up a file locally and save your

code locally as well like on your actual

computer so copy paste it into like a

text edit or a Notes app or something

just that you have this that you can


look at later because additionally maybe

your cash refreshes or you lose your you

forget to save or something and you

close out of your tab here you lose all

of your text so you don't want to do

that now the next thing that we

typically want to see in our codebase

here is we want to do a little another

comment at licens MIT now this tells the

world and the compiler what license your

code is under there's many different

types of code licenses out there and a

lot of the code in the smart contract

blockchain world is open source to some

degree AKA they're MIT licensed it's not

really important you understand licenses

right now but just know that in most

code bases you'll see you will see this

at licens MIT and this means the code is

open source if you don't give your code

a license it means means it's unlicensed

AKA it's proprietary and the reason it's

a good idea to include it is because it

just makes any legal stuff with your

smart contracts a lot easier if you're

more explicit so we'll do at licens MIT

here keep going and some compilers will

complain if you don't have a license

here so it's not really important but we

don't want to deal with any complaints


so MIT is known as one of the most

permissive licenses it basically means

anybody can use or redistribute the code

that we're going to write here and this

is a very minimal basic smart contract

so we don't really

care now even with just this little

contract here we have no code all we

have is a version and a license really

we could go ahead and compile this so if

we go back over to this Viper compiler

click the button I can go ahead and

click compile favorite stui and we get a

little output that looks like this we

see this compilation details button

we'll go ahead and click it and we'll

see B code runtime bite code ABI we'll

see all these different stats about what

our compiler has outputed us so this is

where we actually learn what this

compile button even does so in order for

us to deploy our contracts we actually

need to compile them first when we write

our code when we program when we do our

software engineering stuff we write

things in more human readable ways right

pragma version these are words these are

English words that we understand however

when we go back to the Viper compilation


details if we go over to the bite code

and the runtime bite code this is what

we send to the blockchain because the

blockchain actually only understands raw

bite code it understands like zeros and

ones and hex and it doesn't understand

what pragma version means so whenever we

compile our code it's basically saying

we're going to transform our human

readable code and I know these are

mainly just comments it's going to

transform our human readable code into

machine readable code and anytime a

compilation fails it means we have some

mistake somewhere in our code so if we

go back to favorites. BU and if I were

to type you know some absolute nonsense

in order to try to compile this we

should get a little air uh and we sure

do we get semicolon statements not

allowed which I I guess that makes sense

this is kind of a a complete gibberish

line we get rid of it we'll compile

again and boom we have this little green

check mark means that it successfully

compiled now granted there's actually no

contract in here this is just kind of

boilerplate comp a details but teaches

us more about how compilers work

Additionally you can hit command s or


control s if you're on a Windows command

s if you're on a Mac which is the

keyboard shortcut of hitting this

compile button and as you get used to

coding you'll get pretty used to hitting

command s all the time or controls and

now you're probably itching to actually

get coding but it's important you

understand all these fundamentals so

that when things break later on you know

how to fix

them so let's final actually start

making a contract before we make any

project we usually want to have a good

idea of what the project it is that

we're going to make for this project

we're going to make a very minimal

Favorite Things list we want to store

favorite numbers and favorite people

with their with their favorite number so

this is what we want to build a favorite

things list a smart contract that just

stores and holds favorite numbers and

different people on their favorite

numbers how do we go about doing them

so to help us get started we're going to

need a way to know how to store

different things in this smart contract

and we're going to need to learn about


different value types of Viper and this

is where we get introduced to the

concept of types if we go to the Viper

documentation at docs. Viper lang. org

and we scroll down to Types on the Le

hand side here you can see all the

different types of things that you can

create in a smart contract so in order

for us to store different values like a

favorite number or different people we

have to specify everything we want to

store anything we want to hold as a type

and then assign it to a variable so in

Viper we have a lot of different types

with some of the main ones being booer

with some of the main ones being

booleans signed integers unsigned

integers decimals address by array and a

number of other ones as well we can use

these different types to Define

different variables for example I could

type in here has favorite number and I

could set it to being a Boolean which

would mean this has favorite number

could either be true or false since it's

Boolean now if you were to try to

compile this right now by hitting

command s or compile this You' get a

little error saying storage variables

cannot have an initial value so for now


we can't actually give it a value here

but this line will say has fa number is

going to be of type Boolean which means

it'll either be true or false we could

also say my favorite number number do

this little colon and say uent 256 this

U 256 is saying that my favorite number

is an unsigned integer this means my

favorite number is going to be an

unsigned integer of 256 bits don't worry

too much about the bits part for now

we've left a link in the GitHub

resources to teach you a little bit

about more about bits and bytes and

it'll be helpful for much later on in

the course but unsigned just means that

this can only be a positive number like

one 2 3 you know something crazy like

this if we had an integer 256 then this

could be NE 1 -2 -3 Etc negative this

huge number so we have ins and unsigned

ins as well and we could even compile

this and this will compile saying we

have two variables here that are

essentially assigned to nothing we can

also have an address my

address an address is going to be an

address in the blockchain space for

example in our metamask if we click this


little copy button in our

metamask we go back to remix and we're

to type my address address and set it

equal to the value that we copied this

would work again we're not going to set

it equal to them because that's not

valid syntax my address can can be of

type address so we've done booleans

signed integers unsigned integers we can

also do decimals which decimals are a

more advanced value that we won't be

using for quite some time but you could

say my decimal say decimal like this and

decimals are a way to store a decimal

fixed point value and you also have to

add enable decimals to the compiler so

we're actually going to comment this

line out for now and we'll learn more

about decimals later you can also have

an M bytes wide fixed size B array which

we could do something like my BTE

instead of to or my bytes instead of two

bytes 32 like this we'll learn more

about bytes much later in the course and

there are several other more advanced

types that we can use to store different

things in our smart contract but those

are some of the

basics so now that we've learned a

little bit more about just some of the


different types of values something can

hold we should really see or feel this

in practice so what I'm going to do is

I'm actually going to delete all of this

and we'll just start with my favorite

number and this will be a uent 256 or

unsigned integer

256 now this syntax of variable and type

to the right side is actually the exact

same as python so python has something

called type hints where you have the

variable a little colon and then the

type to the right so again just by you

learning Viper you're also learning

python now when we declare a variable

like this just kind of at the top of our

codebase this is known as a state

variable or a storage variable and this

will get initialized to the default

value so our variable my favorite number

will get initialized to zero so this

will start off at zero so I obviously

want to check this I want to see okay

well what is my favorite number is it

actually zero Patrick you're telling me

that but like I don't know if I believe

you so what we can do is we can

deploy the smart contract inside the

remix IDE to actually see and feel what


it looks like so we can go back to the

vibrant compiler be sure to compile it

to the latest version then we'll go to

this deploy and run transactions tab

we'll click this we'll see that we're on

environment remix VM we'll see some

dummy accounts with some dummy gases and

we can actually deploy this inside of

this fake remix environment so this

remix VM is like a it's like a fake

blockchain essentially running inside of

remix and we can deploy our favorite

stui by hitting this deploy button and

we scroll down we see in this deployed

contract section we see a little

favorites contract we hit the little

drop down in here we could see how to

interact with it and right now there's

only low-level interactions so there's

no way for us to see what my favorite

number actually looks like so what we

can do is we can change what's known as

the visibility of our variable here in

the Viper docs we can see if we take a

storage variable or state variable and

we add this word public around it it'll

be turned into a public variable so if I

do public and I wrap it around this un

256 I hit command s or contr s or I go

and compile we go back to run and deploy


scroll down to the bottom we'll hit this

little x button to delete that contract

that we deployed before and remember we

can only delete contracts in our fake VM

in the real blockchain world you can't

just delete contracts but if we to

redeploy this now and I scroll down hit

this little drop down we now have this

blue button where if we hover over it

says my favorite number if we click it

we see 0 un 256 0 this is telling us

that the value of my favorite number is

going to be start off at zero like we

said the reason that we can see it the

reason we can click that button is

because we wrapped this un 256 with this

public keyword meaning that this

variable is actually going to be public

so variables when they don't have this

public keyword they're created

implicitly as what's called internal

meaning that only things inside of the

contract can actually call that function

or read that value so if you want a

state variable to be readable by people

in the real world you have to wrap it

with this public keyword now you read

later on that anyone can read this

variable as long as they're pretty


clever with their engineering skills but

for most people this is going to be how

you're going to teach them how to read a

variable so let's leave this as public

and we might be thinking okay cool my

favorite number it's public Patrick

great but like how do I change this I

don't want my favorite number to be zero

I want to store my favorite number well

this is where we can actually move on to

finally doing some cool stuff with

functions or methods functions or

methods are very small subsections of

code that when called or invoked or

clicked will execute

some subset of code from our codebase if

you're familiar with JavaScript or

python or anything else the concept is

exactly the same and we're going to

create a function so that we can

actually save a value to my favorite

number in Viper and in Python actually

the way to declare a function is use the

def keyword DF which you can think of

stand for definition or function

definition so we're going to create a

function called store so this is the

name of the function then you'll add

these two parentheses inside these two

parentheses we will put in whatever


parameters this store function is going

to take for example we need to tell our

store function what number to update my

favorite number with so we're going to

tell our store function we want to

update my favorite number to some new

number so we'll say new number which

will be of Type U into 256 as well then

we'll put this little colon here to say

the next lines will be the subset of

code we'll hit enter and you'll notice

that we immediately get this like tab so

Viper and python are tab based languages

where if I were to type over here the

compiler would have a hard time saying

that this code is part of this function

so we actually need to have this old tab

which tells our compiler that this line

is associated with this function but all

we're going to do is we're going to say

okay

self. my favorite number

equals or is set to new number now this

self is a very specific keyword in Viper

and self refers to this contract or the

contract that we're writing so when we

say self.y favorite number we're saying

point to the storage variable or the

state variable my favorite number if we


didn't have self the compiler would get

a little confused because it it would

say okay well what are you referring to

is it my is this my favorite number a

new variable or is it a state variable

when we put the self in here the capila

goes Ah that's a state variable you're

dealing with got it makes sense so what

this function is going to do is we're

going to pass in a number like seven and

we're going to save it to my favorite

number now similar to how we need this

public keyword up here so that we can

actually get that blue button we can

actually read this my favorite number

functions have the same concept if you

don't give them some type of visibility

it'll be automatically considered

internal so we need to do a little at

external right above our function

definition this is known as a decorator

and once again these exist in python as

well this external keyword means that

this function can be called by us can be

called by people outside of this smart

contract which doesn't quite make sense

yet but just ignore it for now we'll

explain it deeper as we go on but what

we can do now that we have this kind of

Boiler playay code here once again we


can make sure to compile this and we can

deploy this let's go ahead and remove

that other contract let's go ahead rehit

deploy let's hit the little drop down

here and now you'll see we have two

buttons we have my favorite number and

we have store which is kind of grayed

out a little bit the reason it's grayed

out is because we need to give it an

input so if we hit my favorite number

now remember it's a public variable so

we get this blue

button we add the number seven in here

and then I hit store it'll actually send

a transaction to store the number seven

at my favorite number we hit the little

drop down in the little terminal section

here you can actually see when I click

this store button these different little

statements show up and these are

transactions so storing seven or their

simulated transactions in this little

fake remix environment so storing the

number seven it's actually updating the

state of the smart contract and to

update State you actually have to send a

transaction so my favorite number being

populated with well it's getting started

as zero but then it's getting set to


seven and when we call my favorite

number now we now get the number seven

here I know it's really really tiny but

we get a seven back if I were to add you

know some crazy number like this hit the

store button and then it hit my favorite

number we see it's been updated

here so we have our public my favorite

number and we have our external store

function now similarly when we don't

have the public keyword on our state

variable or storage variable my favorite

number if we don't have the visibility

decorator and we compile this this will

implicitly be set to at internal which

is another keyword that we can use here

if we were to compile this with the at

internal keyword we go back we remove

our old contract we deploy this we hit

the little dropdown we now see we can't

see my favorite number and we also can't

call the store function when a function

is internal it means it can only be

called by other functions inside of the

contract so for example if I had like

def store other or something like that I

could call self. store 7 like like this

if this was at external and this

function would call this function right

so if we have an internal function


function it can only be called by other

functions inside of the contract and

external means it can only be called by

people outside of the contract so this

internal store can't call self. store

other like this right if we were to

compile this you'll see why we'll get a

compilation error cannot call external

functions via self or via Library since

store other is external our store can't

call it so that's a little bit more

about how the visibility of these work

and the more we do these the better

you'll get at them so let's change this

back let's make this

external let's make this public as well

we'll go back we'll compile this and

we're looking

good additionally we can make a function

that Returns value so if I were to say

at external def

retrieve if I do this little arrow here

and I say U into 256 that means this

retrieve function is actually going to

return a u 256 similar to how when you

know let me comment this out for now I'm

going to save let's redeploy this scroll

down similar to how when we click my

favorite number in blue here we get


returned a value right we're given this

number zero and when I type seven in

here we call store we call this again we

are returned this value seven I can

similarly create a function that return

returns us a value by saying by adding

this to the function definition this

little arrow and U 256 and I can just

say return self dot copy this paste it

here my favorite number so now we have a

function that returns a un26 and just

returns whatever my favorite number is

so it's kind of similar to just clicking

this blue button however if we compile

this and then we go ahead and go to run

and deploy let's delete that old

contract let's hit deploy if I'm going

too fast feel free to pause me so you

can do this we now see we have my

favorite number in blue I can put seven

in here call store hit my favorite

number again now we see the seven if I

hit retrieve I don't get the little the

little thing on on the bottom right like

when I hit my favorite number you know

I'll do one two three store my favorite

number I get this little one two3 when I

hit retrieve I don't get the little you

know one 123 underneath it huh well why

is that well you'll notice that two of


these buttons are orange and one of them

is blue so unless you explicitly tell

the Viper compiler that a button is not

a transaction it'll always assume you're

meaning to send a transaction so if we

go back to this run and deploy Tab and

we pull up this little show terminal

button here when I hit store you know

I'll do 45 45 six I hit store here

you'll see the screen kind of flickered

for a quick second and we got this

little transaction piece here if we hit

the little drop down we can see all this

data associated with this transaction we

can see a status transaction hash block

hash block number from to gas Etc since

we're updating the state we're updating

the storage of the blockchain we're

updating something on chain we have to

spend gas to do so remember everything

that we do anytime we change something

we have to spend gas right you can see

some of the transaction costs and

execution costs and Y yada y all that

stuff in here however let's keep this

terminal up here and we'll hit my

favorite number you'll see we get

another little update here but it looks

a little bit different it says call if


we scroll up we see this little VM this

little check mark it's looks a little

bit different this one just says call so

let's hit the drop down here well we see

a from 2 x execution costs oh so is

there is there gas well there's this

weird thing that says cost only applies

When Calls by a contract what input

output what so this looks a little bit

different right there's no transaction

information right if we scroll up this

has a transaction hash when we called

store but when we called this my

favorite number there's no transaction

hash so this is the difference between a

view AKA static call and a x regular

call when we click that blue my favorite

number button the reason it's blue is

because we're not actually sending a

transaction we're just reading some

state from the blockchain we don't need

to we're not updating the state of the

blockchain so we don't need to actually

spend any gas however when we call store

we are updating the state of the

blockchain we have to spend gas to

actually update the state of the

blockchain so that's why store is orange

to signify hey this is going to spend

gas and this is blue to signify hey this


isn't going to spend any gas you're just

reading offchain well retrieve though

our retrieve function it doesn't look

like we're updating anything we're just

returning my favorite number so wait if

I press retrieve here well I get a

transaction let's go ahead and click it

huh this looks similar to the

transaction but yeah we get a

transaction hash and everything why why

is clicking retrieve a

transaction well because we didn't tell

Viper that this shouldn't send a

transaction so funnily enough we

actually send a transaction we actually

spend gas to do nothing so it's

basically a waste of gas here now if we

want to tell our compiler hey this isn't

a function to send a transaction to we

can just do at view change this to

what's called a view function and

that'll tell the compiler hey this isn't

going to be something that we're trying

to spend gas on so if we add this view

decorator this view piece here we

recompile we go to deploy we delete the

old contract we scroll up we hit deploy

we scroll down oops delete the old

contract hit the dropdown now if I hit


retrieve I now see Zero similar to my

favorite number I can update this with

you know one 123 Hit store my favorite

number as we've seen returns 123 and

then retrieve also returns 1 two 3 and

you can see now they're both blue so we

have a state variable AKA a storage

variable which starts off as zero when

we deploy the smart contract we have an

external function called store where we

can store a new number to our favorite

number and then we also have an external

view function which returns a un 256

which essentially does the same thing as

kind of this public bit here but this is

this would be a more explicit way to

show what's going on under the Hood now

you'll notice too one more thing if I

hit this show terminal I call retrieve

again now we see it kind of look like it

should look right there's no transaction

hash it's this blue button but if we

scroll down here we do see this

execution cost

2,242 gas cost only applies when called

by a contract so when a transaction

calls a view function it does spend gas

so if I were to change this to internal

internal and I were to just do you know

a bunch of useless retrieves in here I


were to go compile this oh sorry self.

retrieve self. retrieve self. retrieve

like this compile this and then deploy

this let's delete that old contract

let's redeploy click the little drop

down if I hit 1 2 3 store pull up the

terminal look at the gas cost of this or

the EXT or the transaction cost so we

see the transaction cost this much and

the execution cost basically how much it

took to execute our function cost this

much so if I copy this and I'll I'll

leave like a little note with

extra extra

retrieves now we can see it costs

22796 gas let's get rid of these

retrieves and let's delete this contract

let's compile redeploy drop down 1 2 3

hit store pull up let's click this let's

go down to the execution cost copy this

drop down get rid of this without

extra

23,28 so it was significantly cheaper

gas wise right this is more than this

number for us to call store without

those extra retrieves so to spell it out

for you here A View function can be be

called by a human for free no gas right

anytime we get this blue button we could


call this a million times we'll never

spend any money but when a transaction

calls a view function it costs gas so

let's make this external again external

so we can call this retrieve function

but this is an important distinction

when building our smart contracts that's

good to know for later on so that we

don't create very complex view functions

because we go oh it's free but if other

transactions are calling that function

the cost

gas now in Viper there's a couple other

function decorators and a couple other

special types of functions one of the

most important types of functions is

called The Constructor I'm going to have

Taz explain what the Constructor is and

how it works and then we're going to

come back to this contract so feel free

to just watch this next section leave

your code AS is watch this next section

with Taz once we learn what a construct

is we'll come back and then we'll

implement it in our favorites list

inside a biper smart contract you can

define a Constructor a Constructor is a

special function that is called only

once when the contract is deployed the

main use of a Constructor is to set some


State variables or to call other

functions that are needed to set up the

contract one of the most common things

that are done inside the Constructor is

to set the owner of the contract for

example let's say that we have a state

variable called owner I'll make this

public click and this will be a address

okay and to define a Constructor we

start with ADD deploy and then we need

to define a special function and it has

to be this exact name Deathcore uncore

init uncore uncore parenthesis inside

this parenthesis you can also pass in

some parameters that you want to pass to

the Constructor for now we'll leave it

empty let's come back to this later so

to set the owner State variable let's

say self. owner is is equal to message.

Sender here message. sender refers to

the account that deployed this contract

so by setting the owner State variable

to message. Sender we're saying that

this contract the owner of this contract

is the deployer of this contract this is

probably the most common use case of a

Constructor to set a state variable that

stores the owner of the contract next

I'm going to show you some examples of


passing parameters into the Constructor

so for example let's first create a

state variable called name this will be

public string max length 100 let's pass

a parameter into the Constructor for the

input I'll type name this will be again

be a string of length 100 and to use

this input let's say self. name is equal

to name from the input and how about one

more example let's say that we have some

time stamp let's call this expires at

this will be public un 250 56 and for

the second input to the Constructor

let's pass in say let's call this

duration un 256 and say self. expires at

is equal to the current block. timestamp

time stamp plus the duration from the

input okay let's try compiling this

contract and then deploying it I'll

click on the Viper plugin and then click

compile once the contract is compiled

let's deploy this okay and notice that

we're going to be deploying The

constructor. Bu file and we'll need to

pass in inputs to be able to deploy this

contract the inputs will be the inputs

to the Constructor name and duration for

the name let's say biper and for

duration let's just put 10 then call

transact okay and once the contract is


deployed let's look at the state

variables owner is an address this

address is equal to the account that you

see over here okay name Viper expires at

this time St all right welcome back so

now that we've know what a Constructor

is and how it works let's actually

create a Constructor for our favorites

list so that my favorite number will

start off as seven so let's go ahead and

do at deploy just like Taz and then

we'll do deore uncore init uncore uncore

we'll do our little parentheses here we

won't do any parameters in here and then

under here we'll just do self Dot double

click this copy it paste equals 7 so now

we have a Constructor saying the instant

we deploy this smart contract call this

a nit function the instant we deploy

this set my favorite number equal to 7

so if we command or contrl S this or

just compile this go to run and deploy

delete the old one now let's hit deploy

now let's hit the drop down remember

every single time before when we called

my favorite number this would return

what it would return zero if we call it

now what do you think it'll return if

you get seven you're correct so now we


have a Constructor which actually can

return seven great

work now we've gone over some of the

basic different types of functions here

but there's a lot of other functions as

well for those of you who want to go to

the extra mile Taz will actually go

ahead and teach you about some of the

other Advanced types of functions so

let's go ahead and and watch Taz walk

through the other types of functions

feel free to either code along with him

or just watch and enjoy in this video

I'll show you some examples of functions

in bper all of the examples that I'll

show you here are called external

functions which means that after we

deploy the contract you'll be able to

call these functions so declare as

external now there's another keyword

called internal which I will explain in

another video and then I'll put another

keyword called Pure I'll also explain

this in another video here I'm just want

to to show you some Syntax for how to

write functions in biper Def let's call

this function multiply and as the name

implies it will multiply two un 256 x un

256 and Y un 256 and we want to return

the product of X and Y to do this we'll


say put an arrow and then say we're

going to return un 256 un 256 and then

call it okay and to multiply two numbers

we say return x * y so that's an example

of a simple function that takes in two

inputs and then Returns the product of

the two numbers let me show you another

example I'm going to copy this again

we'll start with external pier and then

I'll call this function deide going to

divide X by Y and it's going to return

you into 56 now you would think that to

divide two numbers you just have to put

a stash in bper when you're dividing two

integers then you need to do double

slash for the next example sometimes you

want to declare a function but don't

want to implement the code yet you just

want to make sure that the contract

compiles in this case you can use the

keyword pass so for example let's say

that we have a function external Def and

I'll call this let's say to-do to-do

later and we're not going to return any

outputs it's also not going to take any

inputs what we want to say is we're

going to implement the code inside here

later what you can do is type pass

basically this function will do nothing


okay and the last example I'll show you

is how do you return multiple outputs so

let's say external again and I'll use

Pier again for this example and say def

return many for the input we'll keep it

simple it's not going to take any inputs

and for the output how would we return

multiple outputs to do this you'll need

to put the type of the output inside the

parenthesis for example let's say we

wanted to return U 256 and some boian

boot

say return for the first output we need

to return un 256 so let's return 1 2 3

and for the second output we'll need to

return a Boolean let's say true okay so

these are some examples of how to write

functions in Piper let's try compiling

again deploying the

contract hit compile then let's deploy

this

contract and then call the functions to

do obviously does nothing and if you

check the transactions the transaction

still goes through return manyu returns

one to three and Bly and true let's try

calling the function divide put in one

and two and we get a zero back this is

because integers round down and if we

put 3 / two the answer is 1.5 however we


get a one and obviously if we divide

four divide by two we get a two okay

next let's call multiply two 2 by three

and we get a

six all right so our smart contract is

really shaping up it's pretty minimal by

Nature all it really does is store our

favorite number nobody else's we only

care about us here it would be nice

though to give this smart contract

functionality to store data about other

people other people and their favorite

numbers and as we create more people we

could create you know Sam's favorite

number number you 256 we copy this whole

line do like Mark's favorite number copy

this line do like uh hans's favorite

number but we probably want our smart

contract to be clever enough and dynamic

enough to be able to take different

amounts on the Fly Right what if Sam

decides he's not going to be friends

with us anymore or what if Sam decides

he doesn't have a favorite number

anymore and he wants to be taken off

well we probably need a way to update

that and we want to be more clever with

our data structures rather than just

setting everything in a single variable


this is where arrays and structs and

different reference types come into play

and same thing we're going to go over to

Taz now who's going to explain reference

types including fixed size lists Dynamic

arrays mappings and structs and then

we're going to come back here and apply

and use those Concepts in our smart

contract here so here's Tas reference

data types are data types that are

passed by their reference compare this

with a value type when you assign a

value type or use it as function inputs

or as outputs the value will be copied

for reference type the data will not be

copied instead a pointer to where the

data actually is stored will be passed

around reference data type that are

available in biper are fixed size list

Dynamic arrays mappings and strs now I

don't want to overload you with too much

information in one video so what I'm

going to do is in this video I'll

explain about fixed size list mappings

and strs in the next video I'll explain

about Dynamics M so let's begin with

some examples let's start with a fix

size list let's create a list of un 256

having the size 10 call this nums and

I'll make this a public State variable


public to declare that this will be a

fix size list of Type U 256 we'll start

with the type declaration U 256 and then

to declare that this is a list we'll

need to put a bracket and to declare

that it is a fix size list here we'll

need to put in the size of this list for

this example let's create a list of size

10 okay so how do we read and write into

a fixed size list in bper I'm going to

show you how to read and write from a

fixed size list inside the Constructor

so type de devcore uncore init uncore

uncore parenthesis okay and as a review

to reference a state variable we'll need

to say self and then follow by the name

of the state variable nums let's say

that we wanted to get the value that is

stored in index Zer then what we do is

bracket zero if you wanted to get the

value stored in index one then we'll say

one and to store a different value at

index zero we'll say equals and then

assign some value for example let's say

1 to three as another example let's

store the value 456 at index one so say

self. Noms at index one store 456 okay

so that's fixed size list next let's

take a look at a mapping mapping is a


data type that is built off of two other

Val types the first valy type will

represent the key of A mapping and the

other Val type will represent the value

of the mapping let's create a mapping

called my map again this will be a

public State variable and to create a

mapping we'll call Hash map and then

brackets and inside here we'll need to

declare the two value types let's say

that we wanted to create a mapping that

maps from an address type to U 256 so

the first type will be in an address and

the next type will be un 256 okay and to

access a mapping so let's also write

some code inside the Constructor say

self. my map the key type for the

mapping is an address so let's say

message. sender and this is how you get

the value for a mapping stored at this

address to store different value for

this my map at this address let's say

equals to one okay as another example

let's say self. my map again let's say

message. sender so we want to update the

value that is stored in my map at this

key message sender let's put 11 okay so

this is an example of mapping for the

last example let's take a look at

structs let's begin by declaring a


struct to declare a struct we'll say

struct and let's call this person the

person struct will hold two data the

First Data we'll call this name and this

will be a string having the length 10

and then let's also put in an age for

this person let's say un 256 okay next

let's create a state variable of type

struct let's name this person this will

be public and the data type that we're

going to store is person the struct

person okay let's now put some data into

this person struct so say self. person

dot name let's call this Viper and self.

person. AG let's say 33 now we can also

load this state variable person into

memory the way we will do this is say

let's call this P declare the type of

this data this will be a struck of

person and all we have to do to load it

into memory from State variable is to

say self. person this will copy the

state variable so so this will copy the

data of name and age from State variable

into memory into a variable called p and

if you wanted to now modify this data we

can say p. name let's say is equal to

solidity and let's say p. AG is equal to

22 now why am i showing you this well


the reason is the data here it's

updating the state variable so this data

will be stored over here it's making a

copy into memory if and then modifying

the data that is stored in memory so let

me deploy this contract this update will

not be reflected okay so let's now

compile the contract click on the bper

icon click compile okay our contract

compiled let's now deploy this inside

the deployment tab the name of the file

is called ref. by I'll click deploy

scroll down then open the contract and

let's call some getter functions let's

start with nums so for nums zero let's

try call this and we get the value 1 2 3

how about NZ 1 we get the value 456 how

about n two notice over here that we

didn't set any value for nomz 2 so what

will we get calling this we get a zero

can you guess what's going on here we

didn't set any values for NS at index 2

but when we called it it returned to

zero the reason is All State variables

come with a default value so when we

decare the fixed size array of size 10

we initialize the fixed size L where all

of the elements are set to zero and over

here we updated the value 2 1 2 3 and 4

5 6 so the value store that nums at two


is still equal to zero so this is why

it's equal to zero over here next move

on to the example of my map this

contract was deployed by message sender

and here is the address for message

sender I'm going to copy this account

address and then paste it here and then

call my map and the value that is

returned is 11 since this is the latest

update that stores 11 for the key

message sender okay and finally let's

look at the example for person call this

and we get that it returns name equals

to biper and age is equal to 33 this is

because it updates the state variable

here and over here it copies the state

variable into memory so the update that

is made is not to State variable but to

a data that is stored in memory once the

contract is deployed this memory is

clear so we don't see this

update now at this point you might be

getting a little flustered you might

already starting to get confused and

this is where you should 100% be working

with AI agents now some of them are

going to be worse than others at the

moment Claude 3.5 is one of my favorite

ones chat gbt 4.0 is another one of my


favorite ones to ask questions on

especially this beginner stuff once we

get more advanced AI starts to break

down some more but maybe we ask a

question like what is this line

representing in Viper and then we'll do

these three back ticks and then hit

shift enter the three back ticks tell

Claude to enter a code block then we'll

hit paste and I'll just hit enter and

we'll see what Claude gives us and this

is Claude 3.5 which at the moment is one

of my favorite AI agents it says in

Viper the line this line declares a

public State variable

nums is an array of 10 unsigned integers

oh okay so it's an array public means

the array can be read externally and and

a getter function is automatically

generated the array has a fixed length

of 10 elements each element can store a

value of this crazy big number this is a

typical way to define a statically sized

array in Viper Smart contract that can

be accessed by anyone maybe you read

this and you go what what what are you

talking about Claude what even is an

array I don't even know what an array is

and Cloud will give us more information

an array is a data structure that stores


multiple elements of the same type in a

continuous memory location it allows you

to blah blah blah do all this stuff for

example an array of 35 an array for

example an array of five numbers might

look like this and it gives an example

here and then maybe we go one step

further we go okay what's an example of

an array of 10 like in the Viper above

let enter here's an example and they

give us a little example of an array of

10 different elements or a list of 10

elements so different AIS have different

superpowers some AIS are better than

others some are pretty terrible to be

honest and you should play around with

some AIS to get a good feel for which

AIS that you like the best these are

phenomenal tutors to help assist you

along with your Learning Journey at the

moment I Don't Love the remix AI but

Claude 3.5 find that's pH IND and ct4 or

o1 are all decent models in my opinion

also gith hope co-pilot is fantastic as

well some are paid some are free some

have free trials at the moment I think

the free trial of Claude 3.5 is

fantastic so now that we've learned more

about these different reference types


let's actually start adding some of

these to our smart contract here let's

get started with adding a just a minimal

list of favorite numbers so let's create

a new variable called list of numbers

and this will be that array or list that

task spoke about so we'll say We'll

create this variable list of numbers

which will be of Type U 256 array of

five so adding this number five in here

means that this list of number will be

five elements long do a little comment

so it's all going to be 0 0 0 0 0 as of

now and let's even make this public and

look at it here so let's compile this

let's deploy this let's delete our old

one let's go ahead and hit deploy scroll

down and click this we now have this

list of numbers Blue Button because this

is a a public bit here and if we do zero

here we'll get zero if we do one we get

zero if we do two we get zero we do

three we get zero and if we do four we

get zero so arrays or lists are zero

indexed so if I say okay I want the

value of the zerith index that's going

to be this zero here the first index is

going to be this Z zero here the second

is going to be this here I know it's a

little bit confusing but so this is 0 1


2 3 4 so if this is the list here these

are the indexes of each element or each

number in this list so when we create

this array list of numbers everything

inside just gets defaulted to zero so

all five of them if we were to set this

to being six we would get another zero

in here obviously in this one would be

at the fifth position right so you'll

see though when this is set to five as

it is here if I were to type in five or

six list of numbers P the terminal we

get this like revert because the array

is only five numbers long so we can't

access the fifth aka the 6th index here

so we now have this array AKA this list

that we can read from we should probably

have a way to update this so let's go

ahead we'll scroll down we'll create a

new function we'll do at external we're

going to be updating the state of the

blockchain so we're not going to want

this to be view it's going to have to

actually send a transaction action to

update this so add external we're going

to do def add person we could also do

like add person's number or something

like that or just for now we're I'm

going to say add number for parameters


we'll do uint 256 excuse me for

parameters we be we'll do

added or we'll do favorite number of

Type U and

256 and then we'll just do list of

numbers of zero equals favorite number

this means that oop excuse me self self.

list of numbers of Z equals favorite

number this means anytime we call add

number the element at index0 is going to

be set to favorite number so for example

if here is our list of like again zero

uh 0o 0 0 0 we're saying whatever a

favorite number is is going to be set to

the zerith index so it could be 1 it

could be 25 it could be 777 whatever

right so let's go ahead and try this out

let's go compile this and let's go ahead

deploy this with the drop down add

number or first off list of numbers

we'll do zero obviously we see the zero

we'll do one we see the zero etc for add

number We'll add 777 we'll click this

which sent a transaction here now list

of number one one will still be zero

list of number zero will be 777 if I

call add number again what do you think

will happen if I call add number again

go ahead pause the video pause the video

right now if I call add number again


what do you think will happen call add

number again Lista number zero is still

777 Lista number one is still zero right

because we're only doing Lista number at

index Zer here so this probably isn't

great we probably want to like add it to

the next Index right so we probably want

to do we probably want to set this up so

that every time we call add number it'll

be like 0 0 0 0 0 so the first time we

call AD number with seven this gets

updated seven the second time we call AD

number with seven this gets updated with

seven the third time we call it had

number was s Etc so we're probably going

to want to keep some index or some

number to keep track of what was the

last number we set up so up at the top

we could say index index un 256 we'll

make this public as well and what we'll

do is every time we update our list of

numbers instead of hardcoding it to zero

we could say self. index and index gets

defaulted to zero we can even be

explicit we could say self. index equals

z in our Constructor AKA R deploy AKA R

init and then after we update this inex

after we update our list we could say

self. index equals self. index + 1 right


so let's see what this looks like in

practice so let's go ahead we'll compile

this we'll now go ahead we'll delete

this old contract I know our contract is

getting pretty pretty intense now let's

go ahead and redeploy this we'll scroll

down we'll hit the drop down here so

list of numbers at zero starts off as

zero list of numbers one starts off as

zero the index is also zero if I do add

number seven click this now listed

number zero is going to be seven list

number one is going to be zero still but

if I hit add number again because now

index is one right index started off at

zero now it's one our array currently

looks like 7 0 0 0 0 and our index is

one so I'll say our list list of numbers

is 70 0 index is one if I call add

number again right this has just been

updated to seven and our index is now

two AKA pointed to this one so index is

now two list of numbers of one is now

seven Etc so we've found a way to kind

of incrementally add numbers to this

list and zero is a default what's cool

is if I do add number zero add number

here this is set to zero this is now

three we can see the index is three list

of number two is zero and if I hit seven


again add number index is now four a

list of numbers three now shows seven

and we have a seven here right so we

could even just add a zero here because

the index this index variable that we

created is kind of keeping track of that

pointer now what'll happen if we hit add

number two more times we actually get

this little X here right so if I added

seven here now this is full now our

index is pointed to five right index is

pointing to five if we try to add you

know an element here it reverts because

our list is only five items long so we

were trying to add an element at this

index of five AKA a Sixth Element so the

transaction reverts right this is

because again this is a fixed size list

this little notation means that this is

a list of un

256s where the maximum number in this

list can be five so that's why we get

this little error here because we're

trying to add more we'll learn more

later about Dynamic arrays and how those

can help us but for now it's much safer

in your smart contracts to use these

fixed size arrays as much as

possible but all right so our smart


contract is getting pretty cool we're

doing a lot of really cool stuff in here

right we have a way to add numbers

retrieve numbers store numbers for so

basically these two functions do stuff

for our favorite number right and then

we have this add number which allows us

to add other people's numbers but we

probably want a way to assign these

numbers that assign these numbers to

different people right this is not

really our favorite numbers this is

these are this is a favorites list of

other people's numbers so we want to be

able to store those people's Nam names

now T's actually already explained strs

to us and that's what we're going to use

to keep track of other people we're

going to have an array of strs in here

which is pretty Advanced because arrays

are kind of a complex data structure and

then strs are as well but stick with me

you're going to do great here so what we

can do in order for other people in

order for us to store other people's

favorite numbers is we'll create a new

type and technically we should do that

at the top here called struct

person typically you do capitals for

structs like this in this little colon


and we'll say a person struct is just

going to contain two things it's going

to have their favorite number

favorite number which will be a un

256 and it's going to have their name

which is going to be a string 100 so

strings are a variable that we haven't

gone over yet strings are a typing that

we haven't gone over yet if we go back

to the Viper documentation we go to

types we hit this little pop out here we

can scroll down to Strings strings are

pretty cool because they're secretly an

array of characters or an array of

bittes but we don't need to worry about

that right now basically when you see

string 100 this means that we can have a

variable with a 100 or less characters

on the right hand side so for example

back in here I could create like a like

a my name variable I could say

string 100 and then down in the deploy I

could say self. my name equals Patrick

with an exclamation mark right and let's

make this string 100 public as well

let's go ahead and save this contrl s or

command s let's go ahead and delete this

contract deploy a new one hit the drop

down scroll down my name it returns


Patrick right right so my name String

100 can have a 100 or fewer characters

but let's make different people able to

have their own name and then we'll save

that in a list of people so we're going

to create this complex person type and

use this as kind of a new typing so down

here we have list of numbers we'll also

do list of people and it'll be type

public person

five and here's where we're getting

pretty kind of advanced right so this is

going to be a list of

persons so basically you can almost

think of it as like you know how this is

0 0 0 Z 0 right it's going to be five

numbers this is going to be five persons

who are a favorite number and a name so

this could be like 7 Patrick comma uh 16

Chelsea uh 15 Mariah Etc so this would

be index one this would be index excuse

me this would be index zero this would

be index one this would be index 2 all

the way up to index 4 aka the fifth spot

right so this is a little bit more

advanced we're getting with here but

we're going to have this list of people

and we're going to update our add number

of functionality to add a new person to

our list of people arest


so we're going to scroll down to this

add number and let's change this to add

person and it's going to take a favorite

number un 256 and additionally it'll

take a name at the beginning which will

be a type string 100 so we're going to

add we're going to add the favorite

number to the list of numbers and we'll

even do like a little comment add

favorite number to the numbers list and

additionally we're going to add the

person to the person's list so exactly

how we're doing variable name type we

can use this person kind of as a new

type so down here we'll say new person

which is going to be the variable name

of type person equals and since this is

like a custom type since this struct is

a struct as a keyword to give a custom

type back down here we have to say

person

do a little parentheses like this and

we'll say

favorite number equals favorite number

oops excuse me no brackets here we'll

say favorite number equals favorite

number and then we'll

say name equals name what do I have

first favorite number and name perfect


favorite number and name so this syntax

is a little confusing here but what

we're saying is we're going to say we're

going to create a new person and the

favorite number that's getting passed to

add person is going to be set to the

favorite number of the person actually

I'm just going to copy this and paste it

down here comment it out a little

keyboard shortcut that I do a lot is if

you highlight a number of lines and hit

command forward slash or control forward

slash it'll automatically comment out

those lines and then it sets the name to

name so if we pass in Mark 7 it'll

create a new variable called new person

which has favorite number be seven and

the name be Mark right so it' be like 7

comma Mark and you can almost think of

it as like just this right and so we're

saying the favorite number that we pass

to add person is going to be the

favorite number of new person and the

name that we add to add person is going

to be set in new person I know there's

kind of being a lot being thrown at you

right now but don't worry you're doing

great it's this will be a little bit

tricky to digest the first time but as

you play with it more you'll start to


understand it better and I actually do

recommend you pause and like add some

random people and try to do some really

weird funky stuff and view the the

values which we'll we'll do in a second

so so just just stick with me and then

I'll I'll give you time to to explore we

have this new person here and now we're

going to put it inside of this list of

people so now we're going to say list of

people at self. index X right kind of

exactly as we did with our list of

numbers equals new person like this so

now I've hit command or contrl S AKA

compile oh list of O list this should be

self list of people command controls AKA

compile let's go deploy this bad lay

let's xess out let's hit deploy let's

scroll down hit the drop down scroll on

down here look at how fast we're getting

there's so many functions now now we'll

add a person We'll add Mark or your name

seven but before we hit this button if

we go to list of people I type zero here

I click this I see this Tuple thing and

I get zero comma blank it's because a

person who hasn't been initialized yet

because a blank person is zero and an

empty string but once to do Mark in


seven let's go ahead and hit add person

let's just check to see yep it passed

here now if we hit list of people at

zero we now see seven Mark right and so

list of numbers at zero will be what

it'll be seven

great now at this point already we've

gone over a ton of stuff and now is

actually a great time to pause this and

I'm going to give you a challenge can

you get this list of numbers of can you

get this list of people at three to

return

eight Chris or8 Mark or eight Wong or

whatever you want to put in here that's

your challenge pause the video to try to

get this to return eight and Wong list

of people at index 3 to return eight and

Wong instead of zero pause the video and

then come

back so if your strategy was just to do

wong8 and just click this a ton of times

that sure would work so well done uh I

clicked it too many times here just kind

of spam clicking it and now the array is

full now the index is too much now it's

just eight long for every single person

um that's one way to do it and that

works great so if you were able to get

eight long at the bottom here great


job all right great so now we have a way

to add people to our list and we can

actually look them up so I can go ahead

and I can deploy and run let's go and

deploy

and I'm going to add Patrick and I'm

going to say 16 we'll add that as a

person Now list of people zero will show

16 Patrick and list of numbers zero will

also show 16 now this is kind of

annoying though right if I want to see

what Patrick's favorite number is I have

to look it up by index and if I add you

know and if I add Mariah and I say her

favorite number is 30 I hit add person

list of people one is 30 Mariah but

again that's kind of annoying I have to

know that per index Mariah's index is

one and that's not something I want to

do it would be much better if I could

just look up Mariah like this and have

it return 30 obviously if you try doing

that it'll revert right and this is

something that Tas went over with hash

Maps or mappings and these mappings are

incredibly powerful because they allow

us to do exactly that so in our smart

contract we're going to create one more

storage variable for us to do this so


we're going to create one more variable

called name to

favorite number and this is going to be

a type hashmap of

string 100 and uint

256 and then we'll make this public as

well so this hashmap bit this hashmap

keyword over here means that if we give

this name to favorite number a string

it'll output us a un 256 you can kind of

think of this hashmap object as a

dictionary where the key is going to be

some string and then the value is going

to be a un6 for example this would allow

us to input Mariah and get back like and

get back like 1 2 3 or 1 2 1 2 3 1 2 3

or 30 you can think of this like a

dictionary you know for example if this

was like asmap string 100 string 100

right you could think of this as like

you know cat a fuzzy cute creature right

this string would be the cat and then

this string would be a fuzzy cute

creature so our hashmap is going to

enable us to very quickly look that up

as opposed to kind of iterating through

this list and these are two of the most

important data structures in your smart

contract programming career this hashmap

or this mapping and these arrays AKA


these lists and as you get better coding

you'll start to understand the

trade-offs of each and and when to use

each one a lot of the more advanced AIS

these days are pretty good at giving you

a good understanding of which one to use

when so now that we have this name to

favorite number storage variable AKA

State variable if we scroll down now to

our add person function down here what

we could do is we're assigning this

person to this of people let's also add

the person to the hashmap we can say

self. name to favorite

number

name equals

favorite number we'll save this and

that's it so we'll go ahead we'll

compile this go to the deploy tab we'll

delete the old one scroll down deploy

hit this now if we look up name to

favorite number Mariah we get nothing

cuz it just starts with the default the

default un 256 is zero but if we do add

person

Mariah 30 we hit that check to see if it

was successful it was hi the terminal

now named your favorite number Mariah is

30 and now we don't have to remember her


index we just say what's Mariah's

favorite number boom it's 30 and we

immediately get it

back so now that we've added all this

functionality our smart contract is

looking pretty good remember we set out

to create a smart contract that allows

us to store our favorite numbers as well

as favorite numbers of other people

we've got a whole bunch of stuff in here

let's do a quick little refresher on all

the things we've learned so far and then

let's actually deploy this to a real

Network very exciting this will be your

first smart contract that you actually

deploy so quick refresher so number one

one we created a new type called a

struct of person which had a favorite

number and a name we created several

storage AKA State variables such as my

name my favorite number list of number

list of people an index for both of

those lists and a name to favorite

number hashmap or mapping we have our

special anit AKA deploy function AKA our

Constructor where we set my favorite

number to be defaulted to seven we set

our index to zero which we know it

actually gets defaulted to zero anyways

and we set my name to Patrick we have a


store and a retrieve function where we

can grab where we can set our favorite

number and a retrieve function where we

can get that favorite number back as a

view function and then we have our

massive ad person function as well where

we add a favorite number to our list of

numbers we add a person to our list of

people and then in our mapping we set

name to favorite number to that favorite

number and then we increase the index as

well so this is looking pretty good but

let's actually deploy it

right so I'm going to show you a few

different ways to actually deploy this

we're first going to learn how to deploy

it to the sapoia test net so the sapoia

chain is exactly like a real blockchain

except for there's no real money

involved now the issue with this one is

you've probably seen getting testnet

seoa to send transactions can be a huge

pain in the butt so we're going to show

you two other ways to deploy this as

well now in the future we're pretty much

never going to deploy to a test net

because you should always be testing

locally you really shouldn't rely on a

test nut to deploy your smart contract


until that's like the last step maybe

before you get audited which you'll

learn about auditing much later but just

rule of thumb try to deploy to a test

that as as little as possible it's kind

of a bad habit so but we're going to do

it now just so you can really see and

really feel like the true experience of

deploying a smart contract and then

after you do this you should 100% go to

Twitter or X I guess tag cyphon up drag

tag cyphon and just talk about how

excited you are that you deployed your

first smart contract because this is

really your first step into your career

of being a Force for good in the web 3

space it's important to celebrate the

small wins so let's go back to over here

let's go ahead and compile this make

sure it actually compiles and it sure

does okay great so let's go ahead and go

back over to this deploy tab we'll

delete this kind of fake mock contract

that we deployed and we'll scroll up to

this environment section and we're going

to change this so we're going to change

from remix VM Cancun to we're going to

choose we're going to click this and we

want to switch this to our metamask

wallet since I have my metamask


installed here I can click this

environment button and I get this

injected provider metamask now if you

don't have metamask installed you're

going to want to install the metamask

app and then come back to remix and then

just hit refresh and then once you

refreshed this should be in here so

we're going to go ahead and click

injected provider metamask you'll get a

little pop up like this saying hey are

you sure you want to connect we're going

to hit connect and boom we are now

connected now in our metamask here we

want to click the little metam mask and

remember you want to have it like little

pinned here if you don't already have a

pinned now in our metam mask we want to

go ahead and switch switch the network

from ethereum mainnet to sepolia so if

you haven't done it scroll down to the

bottom turn on show test networks scroll

down and we'll go ahead and ins select

sepolia here if you don't have spolia

eth remember you can click on your

address here we'll go to the moccasin

full course cipon updraft we'll scroll

down in here and there should be a

section about testnet faucets we're


going to use the sepolia gcp faucet here

paste our wallet address in here receive

0.05 something went wrong try again

later okay let's try a different one now

getting test net funds can be kind of a

struggle right you've probably clicked

all of these links in the past to try to

get some test net funds and hasn't

worked so well so what we're going to do

actually instead of deploying to sapoia

here we're actually going to deploy to

something called a virtual testnet and

we're going to use a service called

tenderly to do so now to sign up for

tenderly you should 100% go to the

moccasin full course or the GitHub repo

associated with this course and let's

scroll down and we should find a link

for tenderly and you should click the

link there to sign up for tenderly

because the tenderly team has agreed to

give Cypher updraft students an

additional several couple of weeks of a

free trial once you sign up through

clicking any of the tenderly links on

the getto repo be sure to click the link

once you go ahead and sign up open up

the chat and just say into the chat just

say cyphon

2024 and Tenderly will give you a whole


month of a free trial of tenderly so big

thanks to tenderly for giving a free

trial to cypher up draft students but in

order to get that free trial be sure to

click the link in the GitHub repo

associated with this course and text

them in their little chat box cyphon

2024 so big thanks to tenderly so let's

go ahead we'll sign up for tenderly

let's go ahead and log in here I'm going

to log in with Google but you can log in

however you want and this is going to be

a service that we use to get some fake

test net some a virtual test net which

you'll see what I mean in a minute here

so I'm going to go ahead going to sign

in with Google and if you want to walk

through the tenderly onboarding go ahead

and do that I'm actually going to skip

it because I know exactly what I'm

looking

for project name is cyphon updraft first

contract and let's go ahead and finish

and it's going to set up a project for

us now once you've signed up with that

link remember be sure to use this

tenderly link here then back in tenderly

what I want you to do is click this

little intercom thing and we're going to


send a message just say cyphon 2024 hit

enter and they probably won't respond

but this just sending them this code

into tenderly will give you an extended

2 weeks of free tenderly so use cyphon

2024 to extend your free trial so you

you can keep using all these cool

features that we're going to teach you

in cyphon updraft so big thanks to

tenderly for the extended free trial be

sure be sure to click this link in the

GitHub repo associated with this course

so that that code will give you the

extended free trial and in here what

we're going to do is we're going to go

to the virtual test Nets section and

what we're going to do is we're actually

going to create our own fake sapoia

chain that we're going to deploy to and

we're going to get a ether scan like

Explorer to actually view our contracts

so we're going to go ahead and hit

create virtual Network now this is going

to make us our own fake virtual test net

that we can deploy our smart contract to

and see it on an ether scan like

interface without having to go through

the pain of dealing with getting test

net tokens or test net ethereum so

parent Network I'm going to do spolia


we're going to use spolia as our parent

Network to make it more obvious that

this is a test setup so don't worry

about that for now just let's just use

seoa here but whatever you want to do

for the name of this I'm going to say

our fake chain and for chain ID we do

want to use a custom chain ID just so

that it's easier to work with metamask

and other tools where they are looking

for specific chain IDs so this apoia

Chan ID is 111

55111 I'm just going to add another five

in here and then we can double check

that this isn't taken by looking up 1

one one 5

55111 okay cool I don't see this on

chain list so it sounds pretty good to

me that this probably isn't taken great

that's the chain idea we're going to use

I'm going to turn the public Explorer on

if you leave this off you actually will

be able to view the Explorer remember

the Explorer is kind of like your ether

scan right the thing that we use to

learn about gas and all that stuff so

I'm going to turn it on and I'm going to

have Smart contract visibility full this

will allow us to verify our smart


contracts if we want want we'll learn

more about that later State sync we're

going to leave this off basically the

main things we want just we need a

custom chain ID for our fake chain and

we'll go ahead and hit create and this

will create a fake chain a fake sapoia

for us just like that and it's already

done very similar to how in remix when

we're using injected Prov or when we're

using remix VM it gives us kind of like

a fake simulated chain this also gives

us a fake simulated chain but we can

actually see what it's like to use

metamask to deploy a smart contract to

it now that we have this we want to

actually add this into our metamask we

want to we have to add this network

right because if I go to my metamask

right now and I try to switch to that

Network it's obviously not in here right

because it's kind of a custom chain if

you if you have show test networks

that's off be sure to turn this on so

you can actually see the aoia chain

right so if I scroll down right you want

to make sure this is toggled on so you

can see sapoia if you have test net

sapoia great just go ahead with test net

suia but so scroll down to the bottom in


here and hit add a custom Network we're

going to call this our fake chain let's

add an RPC URL paste that RPC URL in

here I'm going to call it tenderly bake

chain you don't have to give it a name

but if you want to go for it give it

that chain ID that we just added 111

currency symbol is going to be eth and

explore URL we're going to skip that for

now but we'll hit save now in this

little networks button we can go to our

fake chain great and there's obviously

nothing in here but we can finally copy

this address go to fund account hit this

fund Account button paste our address in

here which will give us a th000 eth

we'll hit fund says completed we scroll

down we get these little check marks

here we go back to our metamask oh my

goodness we're rich we have $3 million

in USD on our fake chain which uh which

uh is great and if we go to tokens and

we click on eth we can see we've been

given a thousand eth on our fake chain

excellent okay cool we finally have some

tesna tokens on our fake chain here and

we have this kind of Explorer section on

our tenderly where if we scroll down we

can see all the


basically fake transactions that happen

on our chain here see these little two

check marks because this is the fake

transaction that we just made to fund

our wallets but in any case we now have

our fake chain here so we can finally

now go back over to remix and we can

actually deploy to this fake chain

actually with our metamasks the exact

way we would deploy to ethereum mainnet

or ZK sync or any other chain that we

want to deploy to so in remix now what

I'm going to do is I'm going to switch

over to our fake chain in the remix tab

we're going to do injected provider

menam mask I'm going to hit this little

little button if we're connected for

Network's connected I'm going to edit

this we're going to uncheck all of these

we're going to disconnect for now

disconnect uh I'm actually going to

reconnect here by re hitting that

ejected provider metamask going to go

ahead hit connect user enabled networks

edit our fake chain okay update great

connect so we're connected to our fake

chain it says we're connected to spolia

111 55111 because we forked from sapoia

so it says we're connected to sapoia


here because sapoia was our parent

network but you can see if you go in

here and you switch over to main net it

swaps to main one network and then go

back to R fake chain swaps back to

spolia AKA R fake chain so it's it's

smart enough to know what's going on

here now as of recording and hopefully

this changes by the time that you take

this course there's a little bit of a

bug where remix has a hard time working

with this fake chain and Viper and a lot

of oddities so what we want to do is

let's go to our file explorer we'll

rightclick high. Soul just go ahead and

copy paste what I'm going to do pragma

solidity

0.818 semicolon contract high and then

go to the solidity compiler compile this

go back back to the file explorer close

this up go back to favorites. VI make

sure to compile favorites. VI and then

go to deploy and run

transactions make sure in our metamask

we're on our fake chain our tenderly

Network here now we can scroll to deploy

and metamask will pop up remix as of

today if it doesn't see a solidity

contract that's compiled it doesn't work

with deploying so because we only have a


Viper contract it's like oh I don't know

what you're talking about but we want to

deploy the Viper contract so let's go

ahead we'll do deploy a contract this

site wants to deploy a contract request

from here Network fee is this much

because we're on our fake chain which

has gas fee of nothing and this is

exactly what it would look like to send

this kind of transaction on a real S

network we could even click this little

button and we could see the exact data

that this is sending so us compiling and

deploying the smart contract sends this

massive hex object to the blockchain

which gets converted into this smart

contract so this is the actual data

that's being sent now if we hit confirm

and we pull up our little terminal here

we'll see confirmed if you hit this view

on ether scan it'll get it'll be

confused because we're we're actually

not on suppo we're on our fake chain but

if we go to our tenderly Network oh hi

um if we go to our tenderly Network and

we're on the Explorer tab we scroll down

we refresh here scroll down we now see

we have this new transaction that just

went through if we click on this this


was actually the contract that we just

deployed if we go to contracts it says

no contracts but this is the transaction

this is all the data with the

transaction that we deployed to our fake

blockchain in tenderly it says if we go

to contracts it says there's this

unverified contract here which we can

click on it so great we've actually

deployed our smart contract to a realish

SL fake Network so if we go back to

remix now and we scroll down we can

actually see this deployed contract

section and we have all the exact same

buttons that we had in remix all the

exact same values are here we have my

name we have retrieve we have the index

is zero and I can add a person we'll say

Mariah 30 add person and since again

this is sending a transaction we get

mamass popping up saying hey are you

sure you want to send this transaction

we can see the hex data associated with

this transaction and we would go ahead

and confirm this remember cuz on the

real blockchain updating the state like

that requires you actually send a

transaction you actually spend gas so we

went ahead confirmed that if we look in

our terminal here it shows that we


actually did deploy or we actually did

send that transaction we go back to

tenderly we'll do a little Refresh on

this Explorer tab we scroll down and we

see there's another transaction that

went through it's not sure the function

because we didn't verify the contract

but this is actually the transaction

that was sent if we go back to remix

same thing we'll hit index index has now

been updated to one and if I hit name to

favorite number I'll look up Mariah name

to favorite number her favorite number

is 30 now I want you to take a second

and just recognize the significance of

what you just did metamask popped up you

hit confirm and through your metamask

you sent a transaction to deploy a real

smart contract you should be incredibly

proud of yourself because at this point

you are a smart contract developer now

if you ran into some struggles if you

had some issues actually deploying this

be sure to use your AI friends be sure

to use the discussions and ask questions

to get unstuck thousands of developers

have gone through this journey with you

and I'm sure they've run into similar

problems so now is a great time give


yourself a pat on the back go grab a

coffee go to the gym go for a walk

because you just deployed a smart

contract this is incredibly exciting

that setup that we just did for

deploying a smart contract with metamask

works for every singled network if you

had real money in here for example on

ethereum mainnet you would do that exact

same process same thing with any of

these other chains that are in

metamask now if you go to the plug-in

manager and remix and you look up ZK

sync you'll see there's an inactive

module ZK sync you can go ahead and

activate that but as of recording the ZK

sync plug-in only works with solidity so

it doesn't work with Viper at the moment

so we're not going to be deploying this

to ZK sync through remix however when we

switch over to python when we switch

over to moccasin and Titanoboa and

python we will be deploying to ZK

sync this is incredibly exciting a lot

has just happened now if you've gone

this far and I know you have because

you're listening to me talk right now we

want to hear from you this is your

chance to start jumping in and start

trying to interact with the community a


ton of the web3 community is on Twitter

AKA X and we absolutely love hearing

from developers especially developers

who just deployed their first smart

contracts so what you can do is if we go

back over to the moccasin full course

repo aka the Viper full course and we

scroll down we can go down to our Viper

101 section one welcome to remix

favorite list you can click this tweet

me button and if you're signed in you'll

get something called a tweet intent

which will say I just deployed a smart

contract thanks Patrick AL C ZK SDS and

cphon updraft so send this tweet be sure

to say hi and be so so stoked about you

deploying your first smart contract you

can even thank tenderly if you want to

as well for helping make the getting

testet eth a lot easier we absolutely

love to hear from you all so be sure to

click that button send that tweet say hi

you are becom a pro so quickly you are

doing phenomenally getting this

far now when we actually compile this

when we hit this compile button on our

smart contract we compile this down to

machine readable code and I haven't

really been saying this but we compile


this down to What's called the evm or

the ethereum virtual machine now this is

kind of an abstract concept the evm and

what it actually is but it's essentially

just kind of this set of rules a set of

standards of what compiled smart

contract code should look like in

machine readable code and if you're a

chain that follows this set of rules

this set of op codes which we'll learn

about much later you're known as evm

compatible some examples of ethereum

compatible chains are obviously going to

be ethereum arbitrum optimism polygon ZK

sync and more ZK sync is known as

ethereum compatible whereas ethereum is

ethereum equivalent s SN has some

differences there's kind of a gradient

of how ethereum compatible each one of

these chains actually are which each of

them having slightly different

properties these three arbitrum optimism

ZK sync all being rollups or layer twos

of ethereum while polyon being its own

chain it's really important before

deploying your smart contract to double

check that your code is compatible with

the chain that you're deploying to this

is important and we'll go over this more

much later because certain keywords for


example with ZK sync actually don't work

now all the code we have here works

great works perfect with ZK sync and the

ZK sync compiler but as we progress

we'll start to see where those

differences actually are so I just

wanted to drop this and say that this is

important as we continue on now let's do

a quick recap and then we'll actually be

done with this

section now we're going to look at a

couple other bits of functionality that

Taz is going to go over with us in the

Viper I highly recommend you code along

with Taz so that you get the feel of

what he's doing AKA programmer smart

because these will be helpful in the

future we saw two keywords pier and VI

what's the difference both the keyword

pier and VI indicates that the function

is read only it's not going to write

anything to the blockchain the

difference between pier and view

functions is that Pier functions do not

read any state or Global variables on

the other hand view functions are also

read only but they can still read States

and Global variables so for example

let's say that we have a perer function


I'll make this external and make it

perer let's call this function n takes s

two inputs U 256 and Y U 256 and return

U 256 and say return x + y why this

function appear function well because it

does not read any state or Global

variables and also it is readon and what

would a function that is not read only

look like for example let's say that we

have a state variable let's call this

count public un 256 so we have have a

state variable called count and if you

were to update this state variable by

saying self. count plus equals 1 then

now this function is not readon it's

trying to make a update to the state

variable count so this will not be

readon so that's what it means for a

function to be read only how about what

does it mean for the function to not

read any state or Global variables

currently this function does not read

any state variables so it is pure

however if we were to say something like

x + y + self. count now it is reading

from a state variable so this function

will no longer become per since it's

reading from a state and the other part

Global variables for example let's say

block. timestamp now it's reading a


global variable called block. timestamp

so again this function will no longer be

here okay in Contra let's take a look at

example of a view function again

remember that the view functions allow

us to read state variabl and Global

variables say external and say view def

let's call this at to count X un 256 and

it will return un 256 and then let's say

return X Plus self. count here it is

taking the input X and then adding it to

the current value of the count State

variable which is declared over here

this function is still readon since

we're not making any updates however

this function is not a pure function

since it's reading a value from a state

variable you can also read from a global

variable by that's saying block.

timestamp okay let's try compiling this

contract okay the contract compile let's

try deploying

it and then call the

function add two and three get a five

and then if we add to count let's say

one one what you're going to get is a

big number since we're adding one with

the current value of the state variable

count which is equal to zero with the


current time

stamp let's go through an example of if

else conditional statement in Viper so

I'll create an external

function I'll call this function if else

it's going to take a single input U 256

and it will return our U

256 to write a if else conditional

statement in Viper we would type if

condition so let's say if the input X is

less than or equal to 10 then we will

return one and then else we will return

that's say zero if you wanted another

conditional statement in between you

want to say else if but in Viper you

would Type L if so L if x is less than

equal to 20 then let's return two so

this is a example of if else statement

in Viper for this example I forgot to

make this a pure function so let's do

that now okay and let's try compile the

contract click on the Viper icon compile

the contract once the contract is

compiled click on the deployment tab

deploy the contract and then let's call

this function so if we put one for x and

then call we get a one back so this part

of the code executed if we put a

20 then we get a two back so this part

of the code executed and lastly let's


put something like 100 call the function

and then returns a zero since this part

of the code

executed all right congratulations on

finishing the welcome to remix favorites

list well done now before we jump off

and before we wrap up here I have a

little bit of a workshop for you and on

every single section moving forward at

the end we're going to have a little

workshop for you to practice and drill

in some of the things that we taught you

and here's where AI is incredibly

helpful because AI will very often be

able to give you the right answer so you

can so I don't even have to give you a

solution you can just work with AI and

figure out a solution that you like

because often times there actually might

be multiple Solutions there's more than

one solution to doing a lot of these

workshops here so for all these

workshops there will be like a little

prompt here and what what I want you to

do is I I I want you to spend at most 25

minutes on these three prompts at most

if you spend you can even set yourself a

timer if you spend more than 25 minutes

stop take a break and then come back and


work with an AI that you like to help

solve these or if an AI is giving you

trouble you can always jump into the

discussions jump to the Discord Etc but

here are the three prompts that I want

you to do number one create a function

called add that adds one to whatever is

in self. favorite number so back in

remix we have a function store which

stores which updates our favorite number

I want you to create a new function

called add which just adds one to

whatever is in favorite number that's

the first one the second one have the

starting favorite number be different

from seven and check to make sure that

it's the number that you set so right

here we have our deploy function which I

guess I'm kind of giving you a hint

right here where it says the starting

number is seven how do we change the

starting number and how can we make sure

how can we check that the starting

number has changed and then finally and

this is going to be the hardest one here

create a new type using the struct

keyword and create a function that will

save a new variable of that type to a

state SL storage variable so way up at

the top we have our struct person I want


you to create a new type of struct

whatever you want it to be and we have

you know my favorite number is a unit

256 you would have your name of type you

know your struct here and I want you to

have a function that's going to save

this value for extra credit you can also

try to view that as well so that's going

to be the hardest one but here are here

is your prompts here is your workshop

for this first section to test out what

you have learned repetition is the

mother's skill and I want to make you

incredibly skillful so pause the video

get cracking on some of these Workshop

problems spend at most 25 minutes on

them and then when you're done if you

still run into issues work with an

AI excellent so what did we learn so

first off we learned about pragma

version or at version where we can

actually specify the version of our

Viper code directly in our contract we

deployed and we compiled and we worked

with the remix ethereum IDE the online

integrated development environment which

is incredibly power powerful for

Learning and seeing and deploying smart

contracts in fact to this day a lot of


top security researchers still use remix

as a testing ground for ideas and a way

to make sure that their ideas actually

make sense so we've created this struct

person which is our way of creating a

new type we've given a favorite number

and a name to this new type we've got a

whole bunch of State variables and we've

set them all to public visibility so

that we can have that blue button for

them so we can actually call them and

actually see what these are when we

actually deploy this contract we've got

several different types in here we've

got a string a fixed sized string we've

got a un 256 AKA a number we've got a un

256 array which similar to the string

this array or this list is saying hey

there can be a total of five numbers in

this list of numbers our string up here

my name is a string where there can be a

total of 100 characters in this string

we've got a list of people we can even

have a list or an array of our custom

struct our custom type person we can

have up to five people in this list of

people we also have an index which is

just a number to keep track of hey what

number are we on here and then finally

we have this very Advanced data


structure called a hashmap or a mapping

where it takes a key of a string and a

value of a number we we have a

Constructor where we have this deploy

section where we set my favorite number

to seven so that once the instant this

contract is deployed my favorite number

gets initialized to 7 we set self. index

to zero if we didn't set it it would

still be zero but we're explicitly

setting it to zero we have self. my name

we're sending it to Patrick with an

exclamation mark in here but you should

do your name instead of Patrick we've

got a and we've got a function that we

learned with the defa keyword and the

external decorator saying anyone outside

of this contract can call this store

function if we didn't have this external

keyword it would be internal meaning

only other functions inside this

contract can actually call it we're

setting my favorite number to the new

number that we passing into store we

know that this is a state variable

because we can see the self keyword here

whenever we see the self keyword we know

we're referring to properties of the

contract itself whereas this new number


is just this temporary number that exist

just for the duration of this function

call this self.y favorite number will

persist outside of this function call we

have a view function which allows us to

just view some number instead of it

means we don't have to send a

transaction to call this function and

then we have our monstrosity function

called add person where it takes a name

of typ string 100 a favorite number

which is a un 256 and it adds this

person to our list of numbers using the

index creates a new person using this

wonderful struct syntax it adds that

person to our list of people and then it

adds that person to our hashmap as well

and increments the index and last but

not least congratulations on your first

contract here Now's the Time to go grab

a coffee go grab an ice cream go to the

gym go for a walk and take a break

because your mind needs it to digest all

this wonderful information you just

learned take that break and we'll see

you soon

all right everybody welcome back hope

you all took some time to get some ice

cream get a coffee go to the gym maybe

go for a run we are now moving into the


buy me a coffee portion of this course

and of course all of the code for this

is available on the GitHub repo listed

with this course you can find this in

the description or in the course

resources on cphon updraft and this is

what we're going to be looking at here

all the code associated with this will

be available in the gith up repo here

now let's do a quick walkr of the code

here I've added a nice little Link in

here that you can actually just click

here and it'll actually open up in remix

with all the code already populated in

here you can also copy paste if you

prefer but this is what we're going to

be building so before we start building

this I'm going to give you a walkr of

what we're going to be building here

because we're going to be building one

of the best dummy projects that you can

make in your entire software development

career this is going to be a classic buy

me a coffee type smart contract with a

couple of really cool add-ons here so

what we're going to allow people to do

is they can fund you they can send you

some money based off of some price that

we set we're going to tell users they


have to send us at least $50 worth of

ethereum to fund us in order to buy us a

coffee yes a very expensive coffee you

can make it whatever you want and we're

going to be doing some really cool novel

stuff such as getting the value of the

ethereum that's sent yes we're getting

pricing information for our smart

contract then we're going to have some

functionality to withdraw the money out

as well so if this is our code base here

let me show you what this looks like at

the end so we're going to be able to

compile it obviously same as before

we're going to be able to deploy it I'm

going to go ahead and just test

deploying it with men ask to the sapoia

test Network now you're not going to

deploy it to sapoia unless you really

want to again because getting tested

funds is kind of a pain in the butt

we'll be using the tenderly virtual

networks we can deploy this contract we

can deploy this contract go ahead and

hit confirm once the buy me a coffee

contract is deployed we can actually see

all the different functionality in it

including see who the owner is see where

we're getting our pricing information

seeing the value of how much they need


to send us and yes this is a crazy

number but it just means $50 getting the

version that we're working with and what

we can do is users can actually fund us

they can actually send us money so we

can go buy a coffee we're going to learn

what this way thing is and what ether is

and how does this mean 0.02 etherium

we're going to go ahead and fund with

this amount which again will get

prompted for a transaction which we will

confirm and if you are using sooo you'll

be able to see the balance 0.02 eth on

spolia ether scan since we're going to

be working with tenderly you will see

this on your tenderly virtual Network

dashboard and you can also actually see

it right in remix after a brief delay we

can see a list of who actually funded

this who are the addresses that send

this fun to you can there's a get fun

function we also have a funders function

as well there's an address to amount

fund we have a lot of cool values here

and then finally we can actually

withdraw the amount that we sent so you

can see right here in metamask we get

this plus 0.02 SPO e because we're

withdrawing the money out and you'll see


in this withdraw function we have this

self. only owner which is some access

controls meaning that only we only us

only the owners only the people who are

going to go buy the coffee can actually

do the with draw here so after this

transaction goes through you we can

actually go back to the sooa ether scan

and we can see the balance has been

reduced back to zero and You' be able to

see the balance back in our metamask

here now we're going to be going over a

lot of advanced Viper and advanc

advanced evm concepts in this section so

if you get lost if you get confused be

sure to of course go to the support

discussions and use your AI friends when

possible here because they're going to

be very helpful in helping you

understand this journey remember in

order for you to build incredibly

powerful applications you have to

understand these Concepts at the

fundamental level so that when AI gets

it wrong you can go ahead and correct it

so that's what we're going to be

building we got a lot to learn in this

section let's jump in

so as we've done before I'm going to go

ahead and get started by deleting


everything in our remix here so you're

probably a little bit familiar with

remix at this point which is great so

I'm going to go ahead and delete

everything in my remix here and I'm

going to create again this high. Soul

contract here oh it came back sorry

about that and I'm going to create this

high. Soul contract because again remix

assumes you're going to be working with

solidity and is always looking for

solidity so we have to at least make a

solidity file

so we're going to go ahead we go to the

solidity compiler we'll compile high.

Soul so that we don't have to worry

about this in the future and then we'll

also do

spdx

license identifier MIT again don't need

to worry about the solidity stuff for

now just know that as of recording remix

has this bug where it needs to see a

solidity file in order for it to deploy

anything but so let's go back to to our

file explorer here and let's create a

new file called bu me a

cy. by now right on the naming

convention here you see we're using


underscores for spaces between the names

here this is known as snake case and

there's a bit of a disagreement in the

Viper Community as a recording if this

is better or something called camel case

is better which looks like which looks

like this where it's like every start of

a new word just has a capitalized letter

at the beginning python by nature is

typically what's called snake case with

these underscores like this but I want

to point out that for the names of files

you might see it both ways in the python

in the Viper code itself we'll

definitely be using snake case with the

underscores but for the names a file it

might go either way now before we

actually begin coding anything let's

write down what we want to do here it's

usually a good idea to write down what

you want your codebase to do before you

even get started coding so that you have

a design spec of what it should be doing

and this is a really good step for

anybody who is building smart contracts

or building any type of code so what do

we want this to do well we want this

application to do three things allow us

to get funds from users so that people

can buy us coffee we want to be able to


withdraw those funds so that we can

actually go off and buy the coffee and

then finally set a minimum funding value

in USD now originally I said $50 we

might make it five we might make it two

because now that I'm thinking about it

$50 coffee is ridiculous but you know

you can set your coffee price to

whatever you want it to be so let's go

ahead let's get started here of course

with fragma version

0.4.0 and we'll say at license it's

going to be MIT like so and then if you

want you can also do at author and put

your name here there's a couple other

different types of tags that you'll see

people use pretty often and pretty soon

we'll actually learn a nicer way to

format this than with these hashtags

here but we'll get to that in a bit

now let's actually build a little bit of

skeleton for our smart contract here

let's just build the names of the

functions that we want this to have so

we probably want a defa fund some type

of fund function here and what you can

do that's quite nice in Viper is that if

you want to just name a function but not

have it do anything quite yet you can


just type this pass in the function

definition so this contract right here

even though it doesn't really do

anything is actually valid Viper so I

can even go ahead and compile this and

you'll see that it compiles successfully

so this pass keyword is valid Viper here

so we want def fund what else we

probably want def withdraw we want to be

able to withdraw the money that is

funded to us and that's pretty much it

now these two functions are going to be

the main functionality of the contract

however we are obviously going to be

adding other functions in here as well

because well in order to fund and

withdraw we probably need some other

functionality including getting price

and Etc so this fun function we want

anybody outside of this contract to be

able to call so let's give it a

visibility of at external so now anybody

can call this same thing we want humans

to actually be able to call withdraw so

we'll do at external we probably only

want us to call this but we'll fix that

in a

bit for our fun function let's actually

create what's called a doc string in

here so another way to make comments in


Viper is do this triple quotes and

you'll notice that this is actually the

same syntax of python these triple

quotes mean comment so kind of similar

to how the hashtag works up here you can

do triple quotes and you can write stuff

in here can write pretty much whatever

you want and this will also be ignored

it's this triple quotes system that a

lot of people use to actually make

what's called a doc string for their

functions so we could say okay well what

do we want this fund function to do we

could say allows users to send money to

this contract we also probably want to

have a minimum

minimum dollar amount

sent probably the first question that

will come up is this question well how

do we send eth to this contract well the

answer to this is that in every single

transaction that you send no matter what

if you scroll up to the deploy and run

transactions there is this value field

every single transaction in the evm and

the eth and the zos sync optimism

arbitrum Etc ecosystem has this value

field where you can send a certain

amount of eth even in your metamask when


you hit the little send button sending

to some address when you type in a in an

amount here this is populating that that

value field in your transactions every

single transaction can have a value

field however not all functions can read

from this this value field so what we

need to do to tell this function that I

can read from this value field is this

at payable this is

the this is the Viper keyword which

means that hey this function can work

with the message. value aka the value

just like how wallets can hold funds

contracts themselves can actually hold

funds so you saw earlier in the demo

that we actually sent money to this

contract so just like a wallet a smart

contract address can hold any type of

funds you can access this value amount

using something called a global value

the Viper documentation has this page

called environment variables and

constants where it has a ton of

different variables that you can use in

your viper that is globally available

one of those is this message. value

which is the number of way sent with the

message AKA how much eth is sent with

the message we'll understand what we is


in a little bit we also have message.

sender who's the sender of the current

message which we will definitely be

using in this codebase here so in order

for us to require that whoever calls

this fun function sent at least one

whole ethereum we could use the assert

function so we would say assert message.

Val remember this is that globally

available environment variable assert

message. Val equals equals 1 2 3 4 5 6 7

8 9 10 1 2 3 4 5 6 7

8 wait Patrick what so you're what is

this giant number so we're say assert

message. value equals one ethereum now

this is kind of a confusing concept here

so if you go to this site ethon

converter.com you can see there are some

different units for ethereum if you type

one ether in here you can see how much

one ether is in way wayy is the smallest

divisible unit of account in an evm

ecosystem so one ether which as of

recording has a price of

$3,241 is 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5

6 7 8 has 18 zeros so one ether in terms

of way is this giant number here with 1

2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 10 with

18 zeros so if we want to say that our


message. value we want to say that

somebody has sent exactly one ethereum

with this fund function we need to put

this giant number in here and this is

saying the message. value the amount of

eat that they sent was one now this is

obviously really annoying and not very

readable at all this is very difficult

to read Because what what you telling me

every single time I see a number I have

to like do 1 2 3 4 5 6 7 8 9 10 1 2

that's super annoying and I don't want

to have to do that Viper has some

amazing built-in utilities which allow

us to convert between whey and ether

very easily so instead of doing that

giant number we can instead just put

this one in here and get its way value

so anytime you send a transaction

anytime you're working with amounts in

ethereum you're always working in units

of way always always working in units of

way so what we can do here is we can use

this Viper built-in function called as

way value and we can

say 1 comma ether so this is equivalent

to doing this we're saying hey let's get

the value let's get the way value of one

ether and return it as way so those two

are exactly the same another way you


might see this is you might see 1 * 10 *

* 18 this double times is also known as

a power so raised to the power of 18 but

this is what we're going to want to do

because this is the most readable and

this is the most direct if you want you

can also add a little RT message here we

could do like didn't or you must spend

or or eth and this is a helpful message

where if somebody doesn't send enough

eth this will be the response this

function call will say hey you need to

spend more eth if you don't have this in

here the transaction just will break and

it won't give you an error as to why and

that's very annoying so we know that we

have this little dock string here we're

sending at least one eth right now we're

going to change this in a little bit but

this is how you can check for that using

this assert functionality assert

message. value equals equals add W value

one ether otherwise give this revert

message this equals equals is very

different from equals and this will be

one of the things if you're a new

developer this will trip you up so you

want to read this as set and you want to

read this as equals so if I were to say


like my num U into 256 is set to 7 that

has a single equals that means 7 if you

do equals equals you're saying minum

mu256 is equivalent to 7 so these are

these are slightly different this

returns a Boolean and this sets like

this line doesn't make any sense in the

same sense that this line doesn't make

any sense so if that's a little

confusing don't worry about it too much

for now as you practice more it'll start

to make more

sense now if we were actually to compile

this and then deploy this I should be on

the remix

F uh deploy this down here you'll now

see there's a red button and a orange

button here so withdraw which doesn't do

anything but we see fund is now a red

button the reason it's red is because

it's payable so you see this at payable

keyword the remix VM goes hey this is

payable function we must make this red

now up here we see we have like a little

fake account that were given in the

remix VM with

99.999999 ether you can also choose any

other fake account that it gives us with

some ether in it and what we can do is

we can actually call this fund function


we can call this red button by placing

some value in the value section now if I

just leave this as zero and I pull the

terminal up and I call the fund function

it's actually going to get reverted and

we see this little revert message the

transaction has been reverted to the

initial State reason provided by the

contract you must spend more eth so a

transaction revert means that anything

you did in the transaction is reverted

anything is is removed and we we'll talk

about reverts a little bit more in a

second but anyways now if we go back to

this section we pull up the terminal we

scroll up here we change the units to

Ether we put one in here and now we

scroll down we hit fund now the

transaction goes through right because

we're doing this assert saying hey the

message out value you send must be equal

to one we set it to one by changing it

in our transaction up here we called it

and it went through if I scroll up maybe

I'll change this to two hold the

terminal up again scroll down hit fund

again it reverts with the same error

message you must spend more

eth so now let's talk a little bit more


about reverts because reverts are

incredibly important so what is a revert

well a revert undoes any actions that

have been done and sends the remaining

gas back hm okay so but what does that

mean well let's say for example I had a

state variable in here right I'll call

it my num it's going to be a u into

256 and I were to do self. my num is set

to two and then I have this assert here

or actually better yet we'll do self. my

num equals self.y num plus 2 so

basically anytime we call fund we're

going to be incrementing my num we're

going to be adding two to it now let's

test this out right and then let's also

make this public so we can see what my

num is at all times so let's go ahead

let's deploy this and now we have my num

which starts as zero if we call fund

with value of one ether with our dummy

account of course we call fund now we

call my num my num is now two right

because we did self. minum equals self.

minum plus two it's because it went

through now if I leave it as zero right

with this assert going to be triggered

and causing this revert to happen if I

call fund now I pull up the terminal we

can see that it did indeed fail what do


you think minum is going to be well it

hit this line when we called fund it

called this line and it did self minum

equals self minum plus 2 and then it

reverted well let's click my num oh myum

is still two so anytime you see a revert

anytime you see an assert like this that

gets reverted it means it undoes any

actions that happened before so again if

we scroll up we'll put one in here we'll

call fund again pull up the terminal

great the transaction went through

successfully we'll scroll down we'll hit

my num my num is now four but again

we'll scroll up we'll put this to zero

scroll down we'll call fund minum is

what you said four you are correct minum

is still four because this line reverts

anytime an assert gets triggered that

causes a revert with this and in this

case this is the revert error message it

undoes any actions that have been done

and sends the remaining gas back so what

what do wean by this and sends the

remaining gas back well when we call the

fund function let's say there was like

some crazy complex math like uh after

this reverse self minum equals self

minum + 2 / 7 * 43 you know plus blah


blah blah like whatever there's some

crazy math that happened or some very

complex or a whole bunch of lines after

this in order to call this function

whenever we call the fund function we

have to send it a certain amount of gas

we have to send it an estimate ated

amount of gas for how much work we think

the call is going to do if we hit a

revert statement basically it says you

know if we hit a revert statement all

that extra gas that would have been sent

to execute this next line gets sent back

and in the beginning this concept of

like sending the remaining gas back will

probably be a little confusing for you

don't let that stop you it's it it won't

be a blocker it'll it'll make more sense

the more that you work with it so if

that's blocking you don't worry too much

about it now a question that I do get

asked a lot though is hey Patrick if I

send a transaction and it fails does

that still cost me gas well the answer

there is yes so let's do this one more

time uh value is at zero we'll call fund

we'll pull this up we'll see that this

transaction did fail and if we look in

here we can still see there was a

transaction cost so in the blockchain


world if you send a transaction and it

reverts essentially you've updated

nothing right cuz every and your

transaction reverted you've updated

nothing but you've spent money so we

want to do everything in our power to

not send transactions that are going to

revert and you'll notice with a lot of

applications in the blockchain space

they actually will check to see if

something will revert if I were to try

to call this fund function with a real

Network remix would give me a popup that

says hey this will probably fail are you

sure you want to send this metamask will

also give me a popup saying hey this

will probably revert are you sure you

want to send this the reason that you

still spend gas is because well

computers is because well the ethereum

nodes that are running this transaction

well they did have to do work to execute

this line and then they did have to do

work to execute this line and revert all

the state in the transaction so just

remember when any time that ethereum

nodes or nodes or computers have to do

work you have to spend gas somebody has

to spend money so reverts incredibly


important you'll work with them a lot if

we were to assign this I'm going to go

ahead and delete this line delete this

line but in any case now we know how to

send money to the contract we also know

how to make sure a certain amount of

money is sent and if they don't send

that amount of money we will revert the

transaction so right now our contract

does almost something right and let's

actually delete some of this these

comments here contract does almost

nothing and this is probably too

stringent as well we probably want

people to be able to fund us with any

amount of money so we can buy very

expensive coffees if they like so we'll

change this equals equals to this

greater than sign which means that

message. value must be greater than this

value here but remember this is also the

also saying the ethereum amount that we

send must be greater than this amount

well let's say we wanted to set this as

a dollar amount maybe we want to set

this as $5 well what we could do is at

the top we could say a minimum USD value

we could say minimum USD D will be a

uint

256 and in our


Constructor we can say at deploy F

uncore uncore init uncore uncore minimum

USD equals 5 so the minimum USD is going

be set to $5 or excuse me self self.

minimum USD equals 5 and actually let's

do greater than or equals to instead of

just strictly greater than now if I

wanted to update this assert message so

that we're looking for the dollar amount

I can't just stick this in here I can't

just do self. minimum USD because

message. value is in terms of whey or in

terms of ether and this minimum USD is

in well USD so how do we convert this

message. value amount in ether AKA in

wayy to its value in dollars well this

is the part where oracles and chain link

come into play and oracles are an

incredible important part of your smart

contract developer Journey because

because almost 70 to 85% of defi or

decentralized Finance or a lot of these

Finance applications in the blockchain

space use Oracles in some capacity and

Oracle is a way to get real world data

from well the real world into our smart

contracts let's learn a little bit more

about decentralized oracles chain link

and how to get the price of ethereum


into our smart contract as we've talked

about blockchains are deterministic

systems which means that they themselves

can't actually interact with real world

data and events they don't know what the

value of an ethereum is they don't know

what random numbers are they don't know

if it's sunny outside they don't know

the temperature they don't know who's

President they don't know any of this

information these blockchains also can't

do any external computation maybe you

have some amazing artificial

intelligence model that you want to

integrate with a smart contract smart

contracts by themselves can't do

anything with that as we've mentioned

this is because blockchains are

deterministic by Design This is so that

all the nodes can reach consensus if you

start adding variable data or random

data or values that return from an API

call different nodes could get different

results and they would never be able to

reach a consensus this is known as the

smart contract connectivity problem or

the Oracle problem and this is bad news

because we want our smart contracts to

be able to replace traditional

agreements and traditional agreements


need data and they need to interact with

the real world this is where chain link

and blockchain oracles come into place a

blockchain Oracle is going to be any

device that interacts with the offchain

world to provide external data or

computation to Smart contracts however

the whole story doesn't even end there

if we use a centralized Oracle we are

reintroducing a point of failure we've

done all this work to make our logic

layer decentralized but if we get our

data through a centralized node or

through a centralized API or we decide

we want to make the API call ourselves

we are reintroducing these trust

assumptions that we've worked so hard to

get rid of we're essentially ruining the

entire purpose of building a smart

contract so we don't want to get our

data or do external computation through

centralized nodes those are bad news

chain link is the solution here chain

link is a decentralized Oracle Network

for bringing data and external

computation into our smart contracts as

we mentioned before this gives rise to

these hybrid smart contracts which

combine onchain and offchain to make


incredibly featur powerful applic

chain link is a modular decentralized

Oracle Network that can be customized to

deliver any data or do any external

computation that you like so for example

a lot of people might just say oh well I

can just make you know an API call to a

data provider to get the pricing

information onto my smart contract

however blockchain noes actually can't

make these API calls you can't make like

an HTTP get if you're familiar with that

HTTP get you can't make an HTTP get call

because the different ethereum or

different blockchain nodes would not be

able to reach consensus about what the

result of that API call even is

additionally this is a huge

centralization vector and kind of

defeats the purpose of smart contracts

in the first place so instead we need a

decentralized network of nodes to get us

this data for us now chain link networks

can be completely customized to bring

any data or any external computation

that you want however doing the

customization can be a little bit extra

work there are a ton of chain link

features that come out of the box

completely decentralized ready to Plug


and Play into your smart contract

applications the first one is going to

be chain link data feeds and that's the

one we're actually going to be using for

our application here chain link data

feeds currently at the time of recording

are powering over $50 billion in the

defi world the way they work is a

network of chain link nodes gets data

from different exchanges and data

providers and brings that data through a

network of decentralized chain link

nodes the chain link nodes use a median

to figure out what the actual price of

the asset is and then deliver that in a

single transaction to what's called a

reference contract a price feed contract

or a data contract on chain that other

smart contracts can use and then those

smart contracts use that that pricing

information to power their defi

application we can see an example we can

see an example at data. chain.

link and you can change networks you can

change price feeds you can change a

whole bunch of different information to

see some of the most popular price feeds

let's look at ethusd for

example on E USD we can see this whole


network of independent chain link node

operators that are each getting

different answers for the price of at

USD they're getting aggregated by the

network and then delivered on chain we

can see how often they're updated these

ones are updated for a 0.5 deviation

threshold or few hour heartbeat which

everyone hits first we can see when the

last update was we can see the number of

Oracle responses

Etc we can see the contract address

directly on chain

we can even look at the contract on

ether

scan we can see some of the history we

can see all the responses of the

different

Oracles and then at the bottom we can

see the different users and sponsors

keeping this network

up similar to transaction gas whenever a

node operator delivers data to a Smart

contract the chain link node operators

are paid a little bit of Oracle gas in

the chain link token right now these

users of the protocol are sponsoring

keeping these feeds up and are paying

the Oracle gas associated with

delivering this data on chain here's an


illustration of what the current model

of these data feeds look like a network

of these chain link nodes each reaches

out and gets the information about an

asset and then signs the data with their

own private key in a single transaction

then one node will deliver all the data

with all the different signatures to a

reference contract if that node doesn't

deliver the data another node will send

it instead reputation is incredibly

important when you're a chain leak node

operator if you miss data updates if you

forget to send transactions you'll

probably be quickly kicked off these

networks and have no chance of making

any more money in the future these data

feeds are used by some of the largest

protocols in the space such as

synthetics Sushi swap compound and a

with several billion dollars each we can

take a look at an example over at docs.

chain. link now the docs are probably

going to look very different by the time

you actually start looking at them

because they change the docs pretty

frequently so an easy way to get started

here is maybe go to docs. chain. link

and then over either on developer Hub or


overview go to data feeds and this is

where you can see most of what you need

in the getting started section of the

documentation and we can see the

solidity docs have the solidity example

directly into them but if you scroll

down you can also see some Viper

examples where if you click this little

read me it'll bring you to the Viper

addition of the chain link starter kit

which will show you how to make price

feeds using Viper we're going to walk

you through a little demo this is in

solidity so you can ignore the exact

code but the process will be essentially

the same an example of an entire

contract that uses and reads from one of

these Ching price feeds we can even open

this up in

remix and work with it in remix it looks

like this example is reading from a

price feed on Coen the reason we're

actually going to use a test net to see

this work is that there's a set of chain

link nodes monitoring the test Network

to to show you exactly how this works

out once we get deeper into the course

we'll show you how to actually run tests

and work with Chain Lake nodes without

actually being on a test net which will


make your development much faster but I

highly recommend walking through this

section along with me so that you can

see firsthand how this actually works so

let's go ahead faucets. chain. linken

we're going to switch to the coven

Network

Network and we're going to get some Coen

eth but remember look at the network

flag and use whatever network is in the

documentation so to get some Coen we're

going to come to the

faucet we're going to turn off test link

we'll just stay with eth I'm not a robot

and then send request once our Coen

ethereum has reached our wallet we can

go ahead and close and we can take a

look in our wallet and see that we do

indeed have 0.1 eth on Coen now let's go

back to our remix we'll compile this

contract we go and deploy this on

injected web 3 and again the reason

we're going to use injected web 3

instead of JavaScript VM is that there's

no network of chain link nodes watching

our little fake JavaScript VM there are

a network of chain link nodes watching

the test net so we'll scroll down we'll

switch contract to the price consumer V3


and we'll hit deploy mam mass will pop

up and after a brief delay we can see

our price feed consumer down here and we

can hit get the latest price which shows

us the latest price of ethereum in terms

of USD you may be wondering why the

number looks so weird that seems like a

really large number for the price of

ethereum in terms of USD and this is

because decimals don't actually work so

well in solidity and we'll get to that

in a little bit there's a decimals flag

associated with this price feed address

that tells us how many decimals to

include with this price it's also in the

documentation however I know that this

one has eight decimals so this is saying

the value of ethereum right now is

$3,262 it may of course be different

when you go ahead and try this now

there's a number of things that happen

in this contract that I'll explain in

our fundme example but if you want to

take a look now and see if you can

figure out what's going on I recommend

you do so price feeds are one of the

most powerful out of the-box

decentralized features you can use in

your smart contract to level them up

especially for decentralized finance if


you're looking for different addresses

of different price feeds you can check

the contract addresses section of the

documentation choose the network that

you

want and then scroll down and then look

some of the different addresses of the

different price feeds for example this

address will give you the price of 1 in

token in terms of ethereum this address

will give you the price of the Apple

stock in terms of USD and so on and so

forth you can see a lot of the different

chain link functionalities and tools and

services in the devhub OR aka the docs

of chain link one of the newest and

coolest ones that we have a section on

in this L course is chain link ccip or

cross chain interoperability protocol

which is a way to do token transfers

across different blockchains which as of

today is a big issue but you'll learn

about that much

later now I know we haven't really

written that much code but we've gone

over a lot of stuff already so I want to

do a quick recap of the important things

that we've gone over so far so first of

all if you want a function to be able to


accept ethereum to be able to send a

transaction with some mess. value have

to Market as payable then we have this

assert functionality where we can assert

anything and if that assert is broken if

the conditional of the assert isn't

evaluated to true then it will revert so

for example in this assert here if the

message. value is less than one ether it

will revert with you must spend more eth

reverting means undoing everything that

happened before and giving a refund of

gas to the user but not a refund of

everything the user if a if a

transaction is sent and it fails or it

reverts you still have to spend some gas

and finally getting data into the

blockchain from The Real World isn't as

easy as it is in python or JavaScript

because we can't just make an API call

we can't trust a centralized entity also

there's no way to do getter functions in

Viper we have to use something like a

decentralized Oracle Network like chain

link price feeds which is what we're

going to be going over

here so back to our problem so we want

users to send us not one whole ether cuz

coffee shouldn't cost $3,000 but we want

them to send us the minimum USD value so


we want to check hey are you sending us

at least $5 so the question that we have

again is okay great how do we convert

this message. value from ethereum to USD

so we can check this out so we can do

this assert here so we're going to need

to get the price of ethereum or polygon

or Avalanche or whatever currency that

we're working with here in order to get

its price in dollars so let's actually

create a new function to do that so down

here underneath the withdraw I'm going

to create a function called

deore get eth to USD rate and I'll do a

little pass here so typically when you

do this underscore prefix of a viper

function this is usually how you

annotate internal functions so this just

gives users a better idea that this is

an internal function however you

technically don't have to because in

Viper contract can't call a function

that's not marked internal so you don't

have to do this but this is still what a

lot of people do with internal functions

oops and this should be once again self.

minimum USD so what we can do is go back

to the chain link documentation for

Price feeds and again the links to get


here might be a little bit different

depending on when you come here but what

we can come down to is we can go to

chain link data feeds go to getting

started let's look for Viper now the

chain link docs do have some Viper

support here and if you go to the Viper

section you can click the read me

however as of today it's a little bit

out of date so I'm going to be teaching

you the up-to-date way to read Viper

information so the first thing we have

to know in order to use and read data

feeds is that we're actually reading

from some other contract so I'm also

going to be teaching you here how to

read from some other contract if you go

to the chain link docs and you go to

Price feed addresses you can scroll down

you can see all the different networks

that these chain leag price feeds are on

both evm and not BM and we're going to

stay on etherum and we're going to go to

sepolia here we're going to scroll down

to ethusd and we're going to copy this

address you can even click on this

address in here and see this contract on

suppo ether scan we can go to contract

let's do read contract we'll scroll down

in here if we hit uh where is it latest


answer this is actually showing us the

latest price that this contract is

giving us you can also look up latest

round data a query shows us a lot more

information as well but latest answer is

essentially giving us the price of

ethereum and you'll notice it has a

weird number of decimal places as well

you might be asking Patrick that doesn't

look like $3,000 what the heck well this

this number that the price feed gives us

is actually 1 2 3 4 5 6 7 8 it's

actually

3,253 because this price feed has eight

decimal places so understanding decimals

and understanding decimals is really

important in the ebm ecosystem because

there is no fractions there's only whole

numbers really even the Viper decimals

type which we learn about later

technically is a whole number so anytime

you see whole numbers anytime you see

large numbers like this that don't

really make sense it's probably because

it has some units of decimals and you

always want to check that but in any

case so this is the value that this

contract is giving us so now we have to

learn okay well great so that's the


price right there how do I read that how

do I read it in my contract so this this

is saying one ethereum is worth

$3,253 as of recording so we want to get

this now to reach out and interact with

an external contract you're always going

to need two things you're going to need

the address and you're going to need the

ABI or the application binary interface

put this a little the question is now

okay how do we read this value how do we

get how do we call a function in a

different smart contract because this

contract is the contract we want to read

from so the address is really easy to

get so we go back to the chain link

price feeds here we scroll down eth USD

boom that's the address we're on sapoia

right great that's the address for seoa

address boom super super easy for us to

get what is this API

thing well the ABI actually if you just

compile this now go to compilation

details you can see the ABI is right in

this Viper compilation details and and

if you scroll down in here there's a

whole bunch of stuff in here but it's

really just a list of the different

types of functions you can call and some

other information about the contract


such as what version it's with the evm

version the different functions you can

call you can see in here there's a fund

function you can see has zero inputs

zero outputs a withdraw function you can

see this one's not non-p payable Etc the

ABI is essentially a list or a spec a

design spec specification of how

different applications can interact with

this smart contract by saying hey here

are the different functions here's what

they do Etc doesn't need to include any

of the logic itself how can we get this

ABI into our smart

contract well there's another Concept in

Viper and in all programming languages

called an interface if we go back to our

remix buy me a coffee SE updraft and we

click the buy me a coffee I know this is

going to be the f code so there's going

to be a lot more stuff in here if we

look at the top here we can see there's

this interface aggregator V3 interface

and then this section here this looks a

little weird here but it says interface

aggregator V3 interface and it's a bunch

of function definitions like def

decimals def description a return type

but
nothing inside of them inside the body

of a function huh in Viper this is

what's known as an inline interface or

an interface inside of another contract

later on we'll learn of another way to

write interfaces that look a little bit

different than this but this is kind of

the quick way of doing it well you'll

notice is that similar to this API all

this has is the name of the function and

then the return type and any input

parameters which for all these are none

and for the ABI well what do we see here

well okay we see function withdraw

that's the name of one of our functions

in our code right if we go back to go

back to the compilation details right we

can see in here okay we have function

withdraw no inputs no outputs okay let's

go back to the buy me coffee okay we

have function withdraw no inputs no

outputs if I were to put you know number

of type un and 256 in here and I would

say like returns a Boolean you how to

recompile oh and I need a return

statement uh let's say return true true

like this now I go to compilation

details now for function withdraw we see

inputs we see a unit to 56 of number and

an output a bull as well so this ABI


just tells us basically how to interact

with this contract what are the inputs

for different functions and what are the

outputs in the same vein this interface

tells us the exact same thing we have a

function name any inputs these are all

blank of course and then an output as

well we don't need to know the logic of

these functions we just need to know

which functions of this aggregator V3

interface AKA this price feed contract

what functions on that other contract

can we call and if a contract is

deployed to an actual blockchain it'll

have all the logic already so we don't

need the logic we just say hey what

functions can we call on that random

contract over there so what I want you

to do is I want you to copy this

interface and go over to your remix oops

copy this interface and paste it right

at the top here now we're going to be

learning a different way to work with

interfaces in the future so for now

though just go ahead copy paste and use

this now what we can do to even make

sure that these functions even exist is

we can go back to the chain link

documentation so chain link docs with


the price feed contract addresses we

could scroll down we could do one on

ethereum mainnet but let's just use the

saoo one for this video we'll go over to

here we'll go to contract um me we'll

click this button here this link here

which will bring us to The sepolia Ether

scan or if we roll over to contract over

here all the way to the right and we

scroll down we go to write contract

it'll give us a whole bunch of functions

that we can call to spend gas on can

also go to read contract we can scroll

down to latest answer and we can again

see the latest answer right here so we

know that there's some function called

latest answer or some variable called

latest answer that's a public variable

that we can call in our contract now to

actually call that function to call the

latest answer function let me create a

new little function down here now to

show you this functionality of working

with this interface and calling this

function and getting the price we're

going to make a new function called at

external just called def get price like

this and what we're going to do is we're

going to use this interface that we just

pasted in here to call that latest


answer function so what we can do is we

can say aggregator V3 interface wrapped

around this address so I'm going to go

back and copy this eth address go back

here paste that in we'll say price feed

of type aggregator V3 interface equals

aggregator V3 interface of that address

and then we'll say return Price feed.

latest latest answer answer we'll say

this returns and int

256 because latest answer we can see on

nether scan is actually an INT 256 here

so we're going to deploy custom function

just to get and see this price feed here

this latest price

feed now typically this is all you're

going to need to do right so this

interface this aggregated V3 interface

gives us the ABI and when we put this

little address inside of the parenthesis

here we're saying hey we have a price

feed object of type aggregated V3

interface and this price feed object has

these functions that we can call it is

decimals description version and latest

answer so if I were to call Price feed.

latest answer we can see here in our

interface that does exist it'll go ahead

it'll reach out to this contract address


and it'll call this latest answer

function now there's one more important

thing here though is whenever you call a

contract outside of your current

contract you need to use a specific

keyword now this is a feature that only

exists in Viper doesn't exist solidity

but there's basically two different

keywords that you can use when calling

out to an external contract and this is

really good because calling external

contracts is kind of a security issue so

we want to make sure that we highlight

the lines whenever we call out to an

external contract so whenever we're

making we're calling a view function

which by the way this get price should

be an at view function whenever we're

calling a view function or we don't want

to change any state of this call we use

static call like this otherwise we use x

call which stands for external call

since this is a view function we're

going to use this static call keyword

which means we're going to call this

later answer function and we're assuming

that it is a view or a pure function

what this function is going to do is

we're saying hey this address here it

has a bunch of functions the functions


that this address has are these four

functions here and we're going to call

the latest answer function at this

address by setting it to this price

variable and we're going to statically

call it we're not going to X call it

we're not going to external call it

we're going to static call it meaning

we're intending to call a view or a pure

function which is something that Taz

went over in the last section

so let's go ahead and actually deploy

this to our fake tenderly chain and see

what we get so remember if we have your

tenderly application set up it's going

to fetch data for a second if you have

your tenderly virtual test set set up

what you want to do is we did this in

section one set up your metamask with

this as well what we're going to do is

we're going to first compile this and

you should definitely do this with me

let's go to deploy we'll switch to

injected metamask we're going to go to

our our fake chain our fake little

little chain here we're going to go

ahead and deploy oh we're running to an

issue so we got to make sure we compile

the solidity first because as of


recording uh that needs to happen for

some reason and let's go back to our

Viper we'll go to contract buy me a

coffee buy me a coffee let's go ahead

and deploy mamass pops up we'll go ahead

scroll down hit confirm it's been

deployed here now since this now our

fake chain is based off of the sapoia

network so it'll Return To Us whatever

the eth price was when we first created

our fake chain because we have state

sync turned off we don't want to turn

State sync on we want to leave that off

because State sync might actually charge

us and I don't want to get charged I

want you guys to get charged so whatever

the price was on suia when we first set

this up we'll be what the price is now

we'll go ahead and hit get price and

boom we do indeed get a price this is

what the price of ethereum was when we

first created our Network here so pretty

cool now I'm actually going to switch

back where is it on deploy tab we're

going to switch back to remix VM because

we're going to test some more stuff with

the remix VM later but this was kind of

a lot of information so remember two

things that you're always going to need

when you want to interact with another


contract are what it's the ABI and the

address those two things we got the

address of the chain link price feed

from the chain link

documentation and we got the ABI from

this interface this interface is

essentially the ABI and it tells us what

different functions are on that address

and when we call out to that address we

have to say it's either a static call or

X call in this case this is a static

call because we're just calling the view

function of latest answer so I know

there was a lot of information here be

sure to pause take notes ask questions

if any of this was confusing but this

concept might be a little bit difficult

to grasp the first time you play with it

this interfaces and the stattic call and

blah blah blah if it's not totally sit

sitting with you right now that's okay

just keep going we're going to drill

these Concepts all throughout updraft so

if you don't understand it right now

that's okay let's just keep going with

the curriculum don't get discouraged

you're doing great take a deep breath

exhale and let's keep

going now additionally this is


especially where AI can prove to be

incredibly helpful so if I'm confused as

to what's going on here what I might do

is I might copy this line and I might go

to my AI of choice I'm going to use

Claude here because that's what I've

been using as of recently I've been

thoroughly enjoying it but you can use

chat TBT cruser find Google's Gemini

whatever you want to use again we have a

lot of links to different AI tools on

the GitHub resources associated with

this course what we can say is we can

ask a question with a and give it a lot

of context so let's say we didn't

understand that last section we were

saying what is going on here I don't

understand this this interface well

CL 3.5 actually is really really good at

understanding context it might not

understand everything about Viper but if

you give it a context generally it can

help you out so let's go ahead and

practice asking it a question with a lot

of context so it can give us the most

thoughtful answer so let's say so let's

come to Claude or whatever AI you're

working with and say something like hi I

have this function and what you want to

do in a in both asking a A's questions


and asking other people questions is use

these three back ticks to say hey the

next line is going to be a code block

and indeed if you hit shift enter you'll

actually enter into a new line into a

code editor and if I paste this in it'll

actually even add some syntax

highlighting it right it'll actually

even add some syntax highlighting right

so all these colors are known as syntax

highlighting where it adds colors to

different keywords to make it easier to

read and then if I hit down I can now

say hey I have this function and it

should be pretty clear that this is

Viper or python but usually I want to be

a little explicit this is in my Viper

Smart contract and then you can ask a

question about it so I've given my AI

context I say hey I have this function I

paste the exact function say this is my

Viper Smart contract I don't understand

I don't understand what the static call

keyword is doing can you help explain it

to me so so I've given it the context

here and then I've asked a pretty direct

request help explain this to me like

what why am I confused and then we just

go ahead we hit enter and usually Claw


is pretty good so it's given a great

answer here let me explain what static

call is doing your VI smart contract

static call is a special type of call in

ethereum that ensures the called

function cannot modify the state of the

blockchain it's similar to a regular

call but with the guarantee that it will

only read data not write it says it

tells where it's important when blah

blah blah think of it like reading from

a book static call versus writing in a

book regular call your price feed query

should only be reading the price not

changing anything would you like me to

explain more about why and when to use

static call and other scenarios and if

this answered your question you can go

great but maybe this actually is more

confusing right it says Hey without

static call you might be able to call

functions that unexpectedly modified

state which would potentially cost more

gas break the view decorator's guidance

could introduce security vulnerability

and maybe I say oh what do you mean it

would cost more gas and Claud is a model

that's usually pretty good at

understanding the context here so it's

saying hey uh let me explain the gas


costs aspect of static calls versus

regular calls and it gives a pretty good

outline now again we're going to learn a

lot in this curriculum and in this

course so that we're going to learn so

much that we know when the AI is

actually wrong and that's going to be

the key to you being successful is

you're going to be so good you're going

to be smarter than the AI I'm in the

process of building a certificate

program where I ask a ton of questions

to see if developers know their stuff

and I've designed many questions where

AI get it wrong but humans can get it

right and that's what we need because if

an AI gets something wrong and you

deploy a smart contract that could

potentially have disastrous consequences

where your codebase is wrong there's a

bug and people lose a lot of money so

we're going to do everything in our

power to avoid that so don't be afraid

of AIS they can be incredibly helpful

often the the hardest part is knowing

when they're wrong and knowing when to

look elsewhere because they will get

things wrong but they will think that

they're right and we'll give more


examples of them doing that in the

future all right so we're back to our

codebase here we now have this get price

function which we're actually going to

comment out again I'm using command

forward slash as a keyboard shortcut for

this because we're not actually going to

use this but what we are going to do is

we're going to create we're finally

going to create this get E2 USD function

here so we just learned how to get the

price from a chain the price feed which

is really exciting since this is the

only price feed that we're going to use

in this whole contract and let me zoom

out a little bit here what I'm going to

do is I'm actually going to make this

price feed variable a state variable up

at the top so since exactly the same as

our structs that we learned about in our

last lesson the interface aggregator V3

interface is another new type so we can

create a variable a state or storage

variable called price of type aggregator

V3 interface and in our deploy function

we can say

self. price feed equals aggregator V3

interface at address here now since

we're pasting this address in we're

hardcoding this price feed address just


like that now there is kind of an issue

here us adding this address in here

means that this contract will only work

on zolia and that's kind of a bad habit

so instead of doing that what we can do

is I'm even going to make like a little

comment here just say sepolia is in our

deploy function we can add an address as

a parameter so we could say uh price

feed address of type address and pass it

into our deploy function and then set

the self- up price feed to aggregator V3

interface face at address price feed

address so now if we change to a

different chain if we want to use a

different price feed address we just

pass it into our deploy function and we

can see what this looks like if we

compile this we go to deploy now if I

scroll down the deploy function on this

buy me a contract. VI the deploy

function now has this input of price

feed address where we have to paste in

our address and then hit transact or

deploy here so this way right we deploy

our contract we can parametrize or make

it custom the address that we want to

use and then this is a much more and

this is a much cleverer way for us to do


this rather than hardcoding it in but

anyways now that we have our price feed

object here we can scroll down to our

get eth to USD rate function here and

first thing we can do is we can say okay

the price which is an INT 256 type

equals static call right we're going to

do pretty much exactly what we just did

down here self. price feed because price

feed as I'm now remember it's this state

storage variable self. price feed it's

this state or storage

variable. latest latest answer like

so now this price is going to return us

the price with what eight decimals right

decimals cuz we did this before and do I

still have the contract no I got rid of

the contract well it's going to have

eight decimal places and it's going to

return something like you know 3,00

3,21 right so

$3,021 per ethereum now we're going to

need to convert that to the eth amount

in USD right we're going to need to

convert the price that we get remember

again we're going to get like a number

like this I even copy paste this just to

know that this is what this is going to

return we're going to get a number like

this and we need to convert this to the


eth amount in USD so this get eth to USD

rate function that we're going to use as

well we're going to have to pass in the

eth amount eth amount which is going to

be a

u56 we're going to say something like

you know Chris sent us

0.01 eth for us to buy a coffee is that

more or less than $5 right right cuz our

minimum USD is $5 so how do we convert

this

0.01 to its dollar amount so we get the

price which will be something like this

now our eth amount is going to have how

many decimal places and this is where

the math in blockchain gets a little bit

tricky so remember before in ethereum

there's ether there's guay and there's

whey right one ether has one ether is

this many way so it's got 18 zeros or 18

decimal places however we found from

looking at this and then actually

there's also a decimals function which

has eight here this answer only has

eight decimal places it has eight

additional zeros although some of the

zeros are actual numbers so it has eight

decimal places so we're first going to

need to update this price from having


eight decimals to 18 and that's actually

really easy all we have to do is say eth

price of Type U into

256 equals price

time 10 raed to the 10th and this is how

we add those decimal

places now if you compile this you'll

get an error uh oh what's the error

given reference has type into 256

expected uint 256 oh no so ethal is

going to be a uint 256 however price is

an INT 256 right remember remember the

difference between those right remember

U 256 is an unsigned integer and an n256

is a signed integer yes crazily enough

there are some instances when a price is

actually going to be negative insane

right so you can't just say Okay eth

price is equal eth price of type you in

256 is price which is a you know so

we're saying okay so

256 is equal is equal to an INT 256

times Well 10 ra^ of 10 is actually a

uent 256 you can't do that these are

different types you can't do an in 256

multiplied by U 256 you have to do the

same types so this is where Viper has

another built-in called convert where

you can convert a variable or literal

from one type to another so for us we


can very we can just convert our price

to a unit 256 by saying convert price to

a unit 256

and then we go compile now this compile

is fine and

boom now our price is unit to 56 we can

now times it by 10 10 so now instead of

this price we're basically adding 10

zeros on it so we it's basically going

to be the same with 1 2 3 4 5 6 7 8 9 10

so eth price now is this here so now

that we have the eth amount which are in

units of eth we have eth price which is

in units of dollar per eth and we want

to get dollars back to math this out you

just do eth times dollars per eth so

we'd say eth amount times the dollars

per eth or eth price and this should

equal the eth amount in USD and I know

we're getting a little mathy here this

is UN 256 now we're getting a little

mathy here but this actually is in quite

right either because we know that

dollars per eth is going to be something

like this and then eth might be

something like this so we're going to

have way too many zeros so we finally

need to do something called integer

division which is going to be two


division signs and we'll say 1 * 10 raed

to the 18th now this is a little heavier

math here and if this math is throwing

you off again this is where AI is

incredibly helpful AIS are wonderful at

explaining math and we did a couple of

tricky things in here like integer

division right so we're doing this

number we're doing this instead of this

and then finally we'll say this function

returns you 256 we can just say

return return this value here so I know

there's a lot of math here but just to

kind of review again so first off we're

getting our price

which has eight decimal places right we

get a response like this number here and

we go 1 2 3 4 5 6 7 8 boom however when

people send eth amount right because

we're going to be getting it in our fund

function right in our fund function

which is going to use message. Val

message. Val has 18 decimal places so we

need to convert this from it's eight

decimal places to 18 and we need to

convert it from an in 256 to a unit 256

so first we convert it and then we add

those additional decimal places by doing

time 10 raised to the 10th like so and

then finally once they're both in un


256s with 18 decimal places we can

multiply them by each other but since

we've added all these zeros on for

precision we need to then divide by the

18 decimal places like this and then we

can get the eth amount in USD so I want

to talk very briefly about this double

slash so this double slash is known as

integer Division and it exists in Python

so again this is you learning some

python just by learning Viper so if I

said you know if I said what's four /

two you would say hey Patrick that's

easy that's two great if I said what's

6id 3 say hey Patrick no problem that's

also two well if I said what's seven /

three using integer division what would

you say well let's try it so ready let's

say def divide me divide me we'll put a

number of Type U and 256 we'll have a

return a into 256 this will be at oops

at external this will be at

view we'll say return number integer

division by three let's go ahead and

compile this deploy this we can use the

remix VM let's grab any address here

let's grab our price feed address even

though we don't really need it scroll

down I'll divide me we'll do one so


where's our divide me function so one

ided 3 is what what do you think you'll

get if we do one divided by three one

integer division by three we get zero

huh okay what about two we get zero what

about three oh we get one what about

four we get one what about five we get

one what about six we get two so integer

division is basically cutting off any

decimal places remove all decimals right

what is seven actually divided by 3 so

let's do seven again so 7 / 7id 3 is

still two here but what if I do 7 divid

3 on the calculator okay I get 2.33 3 3

3 33 right that's very different than

what we're doing here since the

blockchain and smart contracts are very

precise Endeavor we cannot have decimals

that go to Infinity we need to be very

very precise when working with smart

contracts and know exactly how much

value everything's getting so whenever

we do division in our smart contracts

it's always going to be this integer

division where we cut off decimals and

this is really important to know when we

get more advanced we start doing more

advanced defi applications because that

is a crucial crucial piece of knowledge

when designing your very mathematically


complex applications as Taz went over

Viper does have a decimals type as well

which is supposed to make it a little

bit easier to do a lot of this but even

that gets cut off at some point so

whenever you're looking at division in

the smart contract space just always

know it's always integer Division and

you have to keep the Precision of your

math in mind so this is another one I'm

going to math I'm going to comment out

but I'll leave it in the G repo

associated with this course all right so

now that we've gone through all of that

math and we have this function get eth

to USD rate we can now finally go back

up and convert the message. value the

amount of eth that they send from eth to

its dollar equivalent so now instead of

saying hey the mess value must be

greater than one ether which would be

insane because because basically that

would mean coffee cost $3,000 we're

going to say message. value needs to be

greater than the US D value so we'll say

USD value of eth it's going to be a un

256 equals self Dot and I copy pasted it

get eth to USD rate right you can double

click to kind of highlight the whole


thing self oops uh and we just pass in

the message dot value so we're going to

pass in oops message message. value so

we're going to pass in the message. Val

to get eth to USD rate it's going to

take that message. value as the input

parameter eth amount and we're going to

convert it to the dollar amount again if

this math was a little confusing to you

don't worry about it we're allowed to

call this function again because it is

an internal function and remember even

though it's also a view function it's

still going to cost gas because it's

going to be called in a transaction

you'll see what I mean in a minute but

then we're going to take this USD value

of eth and instead of comparing like

this we will now say the USD value of

eth must be greater than or equal to the

self. minimum USD and an important note

right now uh we have this as our math

and this is where some of the math gets

a little bit tricky we actually don't

want to do it like this because what's

going to happen is it's going to go

multiply these two together then it's

going to divide by one and then do this

multiplication and so we're actually

going to get a way bigger number so we


want to wrap this whole thing up in

parentheses like that and if we wanted

to we could even make a little function

that checks to see okay what

is right so the minimum USD we're saying

is five however this is kind of an issue

why why is this an issue well it's an

issue because remember down here etham

mount in USD is going to have how many

zeros it's going to have 18 zeros or 18

18 decimal places 18 decimal places so

five isn't going to be represented as

five five is going to be represented as

five 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7

8 so we can't just do five for our

minimum USD we would have to do 5 * 10

rais the 18th or and this would be the

math here which would give it those 18

zeros we could also do 1 2 3 4 You Know

1 2 3 4 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6

7 8 however this is awful to review if

you're a code if you're reviewing code

and there's like a ton of numbers like

boom boom boom boom boom boom boom

there's a ton of huge numbers if I'm

reviewing your code I have to look and

make sure you have the correct number of

zeros on every single variable that's

awful so this is not very readable so


what we want to do again is want to use

this as with a

value five ether right so yes this

minimum USD is not ether but this is

just a shortcut for adding those 18

decimal places right so minimum USD is

going to be five ether like so and now

we can say assert the USD value of eth

which has 18 decimals is greater than or

equal to self. minimum USD which also

has 18 decimals

right so let's go over let's go ahead

and compile this test this out let's go

to the deploy and run transactions we

are going to want to use our injected

provider menas because we want to use

our our fake chain which has a chain

link price feed deployed on it so we're

going to use that we're going to scroll

down grab this address paste it in here

deploy oh and it's not popping up

because again I got to go got to go

compile I got to compile my high. soul

for some reason okay cool that's good

now we should be able to deploy this

paste metam Mass pops up great I'm on

our fake chain here so I don't care

let's go ahead and deploy this great we

have this contract deployed and now oh I

probably should have left the price in


here we know the price of ethereum on

this chain as of now is around $3,000 so

if I do a little bit of math pull up the

calculator if I want to do at least $5

worth of eth at $3,000 3000 over 1 = 5x

so we would do 5 /

3,000 so let's send so we'd want to do

this much eth let's go to that ethon

converter.com site it's going to be this

much eth so that'll be this much way

we're going to copy this uh this might

be a little light let's be a little bit

optimistic we'll do 0.2 I know it's

saying that this is plenty of dollars

but this is at a slightly different

price than what I think our price feed

will return so we'll do this we'll do

this much way paste this in here now

we'll go ahead and call the fund

function and boom metamask pops up it

doesn't give us an error we can confirm

and TDA it has gone through and we see

the balance

updated and if we want we can actually

make an external function that basically

runs this function and checks to see hey

if I send this much eth how much is that

in dollars so we could create an at

external
external at view def get e to USD rate

and you'll notice there's no leading

underscore even though these functions

are basically both going to be the same

we'll say eth amount you went 256

returns a and

256 and all we got to do is say return

sell self

doore get eth to USD rate and pass in

this eth amount so this is actually a

really helpful trick to use in Viper

anytime you want to essentially expose

one of your internal functions to be

external you basically just write an

external function and return Calling

that internal

function so now that we've finally done

all this work we can now finally check

to see okay is this assert working

correctly is this transaction failing

when people don't send enough money so

let's go and compile we'll go up we'll

deploy this we'll copy the price feed

address we'll go ahead and deploy this

we need to be on our fake chain the

using the tenderly RPC here we're going

to go to buy me a coffee we're going to

now do a little testing here so if I

send this much way so I I think the

price is around $3,000 right now so a


little bit of quick maths if we want to

send at least $5 5 ID 3ou oops uh five 5

ID 3,000 equals this much eth so this

much eth is this much way uh I'm going

to be a little bit safe and just do this

much way so that should definitely be

above $5 so if we were to pce this into

that function that we just created get

eth to USD rate it looks like that is

above

$5 we would have to count you know 1 two

3 4 uh 1 2 3 4 5 6 7 8 9 10 1 2 3 4 five

6 7 8 okay cool that looks like it's

around

$615 so this should work fine if we

scroll up we paste that amount into the

way value we scroll back down we hit

fund our metam Master should pop up

we'll go ahead and hit confirm

shower terminal looks like it went

through that's great and in just a

second our balance should be populated

with that way that we just sent or it

might take a little longer to be updated

here there we go boom yeah it took a

little long for it to update but now we

see it in here okay what if we were to

cut this in half though use this much

way which or this this website is a


little slow this UI or this website is a

little slow to update here but that

should be about half as much money so it

should be around $3 so now if we paste

this value in here we call fund again

well actually let's paste it in here

first looks like yeah it's about $3

instead but now okay wait uh yeah it's

in there okay cool now we hit fund remix

will even tell us hey uh this will

probably fail are you sure you want to

send this and we're going to say yep

let's go ahead let's send it but

metamask will pop up and usually

metamask will also tell you that this

will probably fail but let's send it

anyways just to see what happens when we

go ahead and send this let's go ahead

and hit confirm it said failed we have

this little X here this transaction

actually failed we hit the drop down we

see transaction mined but execution

failed so this is a real transaction

that we actually sent and it actually

cost gas right there there was a

transaction cost here it cost

43269 gas which we could figure out how

much money that is but um we could

figure out how much money that is but I

don't really want to do the math there


but this actually sent a transaction it

failed the balance will not update

because it was reverted so that means

though that our assert is working

correctly you have to send at least $5

to fund the contract excellent our code

is working exactly how we want this is

great let's keep

going okay our code is coming along

great we have a way to fund the contract

and actually send money we probably

still want to figure out how to get the

money out because if we don't code a way

to get the money out the money will just

get trapped in this contract forever and

we won't be able to buy any coffee that

wouldn't be great so we should figure

out a way to actually withdraw the money

with to actually pull the money out here

and the question that you might be

thinking about is you know so let's

let's do a little doct string here um

take the money out of this contract that

people people sent via the fund function

and the question you might be asking is

how do we make sure only we can pull the

money out right because as of today

anybody can call this external fund

function right anybody in the whole


world can fund this contract and we want

that right we want people to send us

money so we can go buy loads and loads

of coffee and be incredibly cracked up

on caffeine so we're going to need to

figure out how to give access controls

to this withdraw function and this is

where another one of the Viper built-in

environment variables and constants come

into play we can use the message. sender

who's the sender of the current message

to check to see whoever is calling the

function is us right so what we can do

right when we actually deploy this

contract is we can set an owner so I'm

going to go ahead I'm going to create a

new state or storage variable called

owner and this is going to be an address

and we're going to set it to us right so

like when our menas pops up and says hey

do you want to send this transaction

we're going to use this address here

it's going to be this address that's

going to get set to the owner of this

contract so right in the deploy right

when we deploy this contract we can say

self. owner equals message. sender now

what does this mean it means that

whoever sends the transaction that

deploys the contract is now going to be


the owner of this contract and since

we're going to be the on 's deploying

the contract the owner is going to be

set to us so what we can do then is down

in our withdrawal function we can do

another one of these assert lines here

we can say assert message. sender

remember again message. sender is going

to be whoever calls this function so

assert whoever calls this function

whoever the message. sender is needs to

be equal remember the double equal sign

needs to be equal to the self. owner

remember this is how you access those

state storage variables otherwise revert

with not the contract owner so let's go

ahead and try this out we'll compile the

contract real quick we'll go to the

deploy tab we don't need to use the

injected provider here we can just use

the remix VM because we're just going to

test calling the withdrawal function but

we do need to put a price feed in here

even though it's going to point to

nothing but that's fine we'll scroll

down we now have the withdraw function

so the person who deployed this if you

scroll up to these fake accounts the

person who deployed it is going to be


this address here right because we

deployed it on the remix VM if you did

use the injected VM the owner is going

to be here you know what let's actually

make this a little bit more obvious

let's make this public EXC me let's make

the owner public here let's

recompile cool that worked great let's

redeploy let's actually let's deploy

let's remove that old one let's redeploy

with that contract address great and now

if we hit owner we see 0x 5B 38 blah

blah blah and if we scroll up to our

fake accounts we see 0x

5B 3 blah blah blah so great so the

owner 0x 5 B3 blah blah blah the owner

is going to be this account here so this

account should be able to call the

withdraw function right so if I call

withdraw here me pull up the terminal

call draw boom it is successful and the

reason it's successful is because in the

remix VM we're simulating calling it

from this account right the transaction

the function itself doesn't do anything

it just doesn't revert it just makes

sure that the m. sender is the owner

right but if we were to switch accounts

to this other fake account then scroll

down I'm going to pull up the terminal


too then scroll down and call withdraw

we can see it reverts transaction to buy

me a coffee. withdraw errored rever

reason provided by the contract not the

contract owner so now we have some

working access controls where only we

can call the withdraw function

great however we should probably

actually make it so that this withdraw

function actually gives us the money

because right now it doesn't actually

give us the money let's implement the

functionality for it to give us the

money so now we need to figure out how

to send money send eth send the native

blockchain currency from a smart

contract and Viper actually has a

built-in function for this called send

which makes it really easy to do but

there's another one called raw call as

well that I want you to be aware of that

we'll learn later but send is the much

simpler one to send money all you have

to do is type send and you just need to

say who you want to send the money to

and then how much money or how much

value you want to send so we want to

send the money to the owner of the

contract so to self. owner who is going


to be us and then we want to send all of

the money that this smart contract has

but how do we know how much money this

smart contract has we can't just be like

all of the money can we do we have to do

like five well there's a keyword for

this as well you'll just say self.

balance so self. balance will always

refer to the native balance that this

smart contract has and that's it so

we'll send self. owner the owner of the

contract the entire balance here we

could also do message. sender because

we've asserted that the message. sender

is the owner but probably a little bit

more explicit to do it like this so

let's go ahead we'll

compile since we are going to want to

fund this first to test it out let's go

ahead and use the injected provider

let's use metamask here let's go back to

this whoops let's go ahead we'll grab

that price feed where is it here copy

paste deploy met Master pop up let's

confirm scroll down hit the drop down

here that looks good let's use this

right here paste this in great that's

more than $5 okay let's paste it in for

the away section let's SC then let's hit

fund minimass pops up we'll go ahead and


confirm pop this up looks like it went

through that's great let's just wait a

hot second for this to to update great

this did indeed work now we should be

able to withdraw because we're going to

use the same wallet that just deployed

this to actually withdraw so we're going

to go ahead and call the withdraw

function now metam Mass pops up looks

good to me we'll hit confirm and in a

second we'll see this balance go to zero

and we'll see our balance increase go

back to tokens eth the balance should

inre well this already went through so

our balance is already gone back up

we'll wait just a second we'll see this

balance go back to zero boom this has

gone back to zero to make this even more

obvious what we could do is we could

switch this to Ether we'll send one

whole ether in here we're connected with

our metamask still we'll hit the fund

function men mask pops up we'll go ahead

and

confirm looks like the transaction went

through we can check our balance if we

pull up our menam mask go to tokens we

click the eth we see it went down to 997

it was
998 now I know this hasn't updated yet

it'll probably take a a minute but oh

look it's updated right there but let's

go ahead and hit withdraw we'll scroll

down we'll hit confirm transaction went

through we look back at our menam mask

go to tokens click eth it's now G up to

998 so we we successfully funded our

smart contract with the whole eth and

then we pulled the eth back out with the

withdraw function that only we can call

this is

fantastic so our code actually looks

pretty good right we're able to have

people send us money send us a certain

amount of money at least $5 and then we

can actually withdraw the money out of

the contract that they send us again we

have some functionality to view some

pricing information as well in our

contract but let's make this a little

bit more sophisticated let's have this

have a little bit extra functionality

let's keep track of who sent us money

basically we can keep track of all the

awesome people who sent us money and

then also how much they sent us this is

where some of those data structures from

our last section is going to come into

play here so let's create a a a new data


structure for our list of funders so

we'll call it

funders and we could have this be a an

address array or an address list a list

of addresses but we're actually going to

use a Viper explicit type called a d

array or a dynamic array and to really

show you the difference between these

two because this can be kind of complex

I'm actually going to create a new

contract and walk you through some stuff

and then we come back over here okay so

I'm going to create a new file called

arrays compared. VI and in here I'm

going to have din array which is going

to be a din array of Type U 256 with a

Max size of 100 you 256 100 so a d array

is very similar to a regular array or a

fixed size sized array

Dynamic array and a fix sized array

where whereas a dynamic array is a un

256 Max size 100 so what's the

difference between these two because

they kind of look the same just have

different ways of doing them right so

this could still be 0 1 2 3 Etc but this

one could also still be 0 1 2 3 so

what's what's the difference well the

fixed sized array is going to be fixed


at size 100 so at all times the length

length of this of this array is going to

equal 100 at all times the dynamic array

however when you first create it the

length will start at zero and every time

you add something to the arraylist it'll

grow in size so let me show you what I

mean so let's have a function called def

add to a array and then let's make these

both Public public so we can view them

public and then I'm also going to make

two additional functions def D array

size going to return U into 256 this

will be at external at View and this din

array size we're just going to return

the length of the

self. damic

array like this and add to array let's

just do pass for now so this Len keyword

is how you get the size of a dynamic

array now if you were to try to compile

this as it's written here it'll compile

fine so we're able to get the length of

a dynamic array but let's try to get the

length of a fixed sized array so let's

go ahead and copy paste this and instead

of doing self. Dynamic array let's call

this fixed array size and we'll return

the length of self. fixed array size

we'll go ahead and compile this uhoh we


get a compiler error over here it says

reference has Type un 25600 expected one

of blah blah blah some random code here

you actually can't call this Len or this

length function on the fixed sized array

because like I said the length is always

going to be 100 at all times this array

will be initialized as 0 0 0 0 0 blah

blah blah blah blah all the way to 100

zos however this array the dynamic array

when you initialize it it starts off as

empty right so if this is let me put the

brackets down here like this empty and

when you add something to the array if

you were to add a zero to it it would

look like this so a fixed size array

looks like this it's always going to

have 100 elements whereas a dynamically

sized array or a dynamically sized list

is going to have it's going to look like

this with a maximum size of 100 and

there's a number of reasons why you'd

want to use a fixed sized array or a

dynamically sized array as you get

better and better you'll start to

understand the difference but let's go

ahead and let's finish doing this little

add to array functionality here oh why

is this oh yeah I got to delete this


function here so and then uh so to add

to array for the dynamic array we can do

self. Dynamic array. append you know

we'll do zero so we can do aend on

Dynamic arrays where this is how we add

something into the list but if I were to

do but if I were to try to do self.

fixed siiz array. a pen zero and I were

to compile this it's it's it's going to

fail you cannot append to fix sized

arrays what you have to do is you have

to set the values so we would say self.

fix sized array at index zero equals one

and actually Let's do let's set this to

one as well we open this up we compile

this this actually compiled

successfully now if I were to do self.

Dynamic array of zero is set to one do

you think this would compile let's try

it out oops this does compile but when

we add actually run this code what do

you think happens so since we know that

a dynamic array is initialized like

this if we try to set an element in the

zeroth spot before we append an element

what do you think is going to happen so

again let's compile we'll go to deploy

we'll go to remix VM because we don't

need to do mamass stuff let's go ahead

and deploy this contract so this is


going to be the arrays compared contract

here we'll scroll down we can click

Dynamic array size which is going to be

zero here oops I forgot to add external

here external whoops let's delete this

contract let's redeploy oh after I saved

and compiled of course okay great now we

have add to array Dynamic size array is

zero calling this will error right now

because there's no elements in the

dynamic size array however looking at

the zero with element on the fixed size

array will return zero right because

fixed size array automatically gets

populated with zeros the D the dynamic

array does not so now let's call add to

array and we get an error why do we get

an error well the error message itself

is kind of cryptic but because we're

trying to say hey the element at the

zeroth position aka the first element is

set to one but the D but the dynamic

array has nothing at the zeroth element

right now so we don't want to do this we

want to use this append functionality

here and for the fixed size array if we

wanted to we could like keep track of an

index variable we could do like index un

256 like this un 256


256 and every time we appended we would

do self. index and then we would do

self. index equals self. index + one and

every so every time we we update an an

element we increment some index go ahead

and actually delete Contract I hit

command s or controls so it's saved and

compiled looks like it's looking good

let's deploy this now if I hit add to

array the dynamic array size says one

because we appended something if I hit

add to array again and then look at the

dynamic array size it is now two so

Dynamic arrays change in size if I look

at the zeroth element I get a one if I

look at the first element I also get a

one if I try to look at the second

element we pull up the terminal it

actually aired I know it says one here

but it's because it just hasn't changed

it's it's erroring right so I can look

at the first element boom that didn't

error second element boom that did

revert fix size array though zero withth

element is one first element is one

second element goes through but it just

returns zero right so that's going to be

the difference between a dynamic array a

fixed sized array or list and that's how

we're going to use


them so with this new knowledge of how

arrays work what are we trying to do

well we're looking to keep track of all

the funders in our contract so we could

set this as a fixed sized array like

kind of like what we're doing here but

it's probably going to be better for us

to do a dynamic array so let's make this

a public D array of address with a Max

size of let's just say a th000 so

there's a maximum of a th000 addresses

we can have as funders if we have more

funders our contract will kind of break

but let's just hope that we don't get

too many people who want to buy us

coffee so we'll scroll down to our fund

function and let's keep track of this

fun here of whoever funds us we'll say

self. funders do append message. sender

boom

so we're going to say hey in our funders

Dynamic array we'll just append we'll

just add to the list the message. sender

whoever calls this fund function great

and then when we call withdraw we

probably want to reset the funders maybe

we don't but I want to reset the funders

every time I call withdraw and we can do

this really easily with Dynamic arrays


which is part of the reason why I'm

using a dynamic array we can just say

self. funders equals this boom that's it

this is how you identify an empty array

right so self do funders equals this

means it's an empty array and it is

essentially

reset okay great so now we have a way to

actually track who is funding us but we

don't have a way to track how much they

sent us so let's think about this how do

we how what's a good way to keep track

of how much they've sent us well this is

where mappings are fantastically helpful

here so what we can do or hash Maps if

you will so we can create a new mapping

called funer to amount funded and we'll

make this a public

hashmap of address and unit 256 unit

256 unit 256 so this is basically going

to be funer mapped to how much they

funded and what we can do is in the fund

function after they fund us we can say

self. funer to amount funded of the

message. sender AKA whoever funded us

equals

self. funder to amount

funded plus message.

value now there's actually a shortcut

you can do instead of doing instead of


saying hey my giant variable equals my

giant variable plus you can instead just

do plus equals and this is the exact

same as doing this so self. funder to

amount funded message. sender equals

self. fund to amount funded message.

sender plus message. value or just plus

equals so this is kind of like a little

shortcut for those doing the exact same

thing so now we're saying whenever you

fund us we're going to going to keep

track of how much you actually sent us

so the message. sender plus equals

message. Val and don't worry we'll test

this in a little bit then when we

withdraw let's let's uh do the resetting

funders that's really easy can we do the

same for the mapping can we do like

self. funer to amount funded equals like

a a blank mapping uh no we we actually

can't do this we have to directly go

through and update each mapping and that

is actually really gas intensive right

we have to literally go through every

single address that ever sent us money

and set their balance to zero so this is

where later on as you get better and

better at smart contract development

you'll start to weigh the trade-offs of


different data structures if you use an

array here if you only use an array well

great you can reset it super easy you

can add them super easy but to figure

out how much money they each scent it's

actually really hard with a mapping it's

super easy to figure out how much money

they sent but resetting the mapping is

really hard so let me show you how to

actually reset the mapping so to reset

the mapping we're going to use something

called a for Loop now to explain for

Loops to us we're going to have Taz go

over for Loops just really briefly once

again in case you forgot let's see some

examples of for Loops in Viper first

I'll create an external function and

then this will be Pier again cause def

for loop we're going to run a for Loop

and then we'll collect the results in a

dynamic array and then return this

Dynamic array so that we can see what's

going on inside the for Loop so say

dyn array up type un to 56 let's say Max

size 10 in the first part I'll

initialize this Dynamic array R type dyn

array of type un 256 Max size 10 and

initialize this equal to an empty array

so let's run a for Loop the most

simplest way to run a for Loop is to say


4 I in range let's say up to five and

let's just append this index into the

array R do append I and then we'll

return this array this range will

execute the for loop from I equals to Z

to I less than 5 so what you're going to

end up with is a dynamic array having

elements from 0 to four okay let's try

compiling the contract

I forgot to add a type for the range

over here the type will be un

256 okay let's try compiling

again deploy the

contract and then let's call the

function for Loop and we get a dynamic

array with elements 0 1 2 3 and four so

that's the simplest case of a for Loop

using range we can use range in a

different way as well we can specify the

starting index and the ending index so

for for

example let's call this for Loop start

and end game we initialize a dynamic

array of size 10 of type 256 and let's

run this for loop from 5 to 10 so

starting index five and up to but less

than 10 compile the contract

again and then let's deploy a new

contract and then call the function for


loop St start end and what do we get 5 6

7 8 9 since the range was from 5 to 10

another way to run a for Loop is to

iterate through a fix size list for

example let's call this for Loop list

and again I'll initialize a dynamic rate

so that we can see what's going inside

the for Loop so I said that we can

iterate their fix size list so let's

create one first nums say 50 6 of size

let's say 4 is equal to put 11 22 33 and

44 and then we'll replace this range

with the fixed size list nums since the

element of nums is UN 256 this I will be

also un 256 and for each iteration we'll

simply append it to our Dynamic array

and then return this let's try compiling

the

contract and then let's playy a new

contract

again and then call the function or doop

list and we get the Elements 11 22 33

and 44 these are the elements of the fix

size L nums for the next example I'm

going to show you how to skip a

iteration of a for Loop and also how to

break a forward Loop before it reaches

the end condition so to begin with let's

copy this one and then paste it

here so far the for Loop is going to run


from I equals to Z to i = 4 since the

range is 5 let's say that you wanted to

skip this for Loop for I = 2 then what

you would do is type continue so for

example if I is equal to two then

continue this will skip the rest of the

code so for I equals to 2 this will not

be appended to this Dynamic array then

go on to the next iteration where I is

equal to 3 another example is how would

we break out of a for Loop early the way

we will break out of a for Loop early is

by using the keyword break for example

when I is equal to 4 let's exit this for

Loop so say if I is equal to 4 then

break when I is equal to 4 this will be

the last iteration however here it says

when I is equal to 4 break so the

execution of the for Loop ends here and

then we exit this for Loop what you're

going to see is that this part of the

code will not be executed so in the

dynamic array the element four will not

be included let's call this function as

for dup skip okay let's try compiling

the

contract and then let's deploy a new

contract and then call the function for

Loop Skip and what we end up with is a


dynamic array of 0 1 and 3 two is not

included since it skipped this iteration

and four is is not included since the

for Loop exited when I was equal to four

all right welcome back so now that we

understand how four Loops actually work

let's go ahead and before we reset this

funders array to nothing let's Loop

through that list of funders and reset

the balances here so we can use a couple

of different ways to reset the array I'm

going to go with what's known as the

four each Loop so instead of doing four

U and 256 I in

range self.

funders length of the self. funders I'm

just going to say for each address

excuse me for each

funer address in self.

funders self. funer to amount

funded of funer equals zero so I'm going

to manually reset all the elements in

this mapping to zero now doing a for

Loop like this in a function is going to

cost a lot of gas right because this is

incredibly complex if there's 1,000

people in the funders list that means we

have to reset 1,000 different addresses

and this is incredibly gas complex so

again these are the things you're going


to want to think of when you're

designing your smart contracts and when

you're picking your data structures but

this is saying for each address in the

self. funders array update that funders

balance to

zero okay so this is looking really good

let's scroll up and let's make some of

these public so that we can actually see

them and interact with them when we

actually are testing this out so looks

like these are all public now great

stuff is looking good okay so now that

we've done this now we should be able to

we should be able to do what we should

be able to fund the contract with

different funders and see the balances

increase we should then be able to

withdraw the money out and additionally

we should be able to see the different

amounts of the different funders in here

for us to test this out on our virtual

test net I'm going to actually go up

into my metamask and I'm going to create

a new account so if you just click the

account let's hit add account or

Hardware wallet and just hit add new

ethereum account we'll leave it as

account two and this is going to start


off with zero tokens on once again our

fake virtual test net I'm now actually

going to copy this address we're going

to go to my virtual test net on tenderly

we're going to go ahead and fund it

paste this in here hit fund great so now

it is successfully funded let's go up to

our wallet and in a second this should

be populated with a bunch of fake money

cuz we've added the balance in here wait

we might have to wait a minute or two

okay great we now see the the money is

in here we have 1,000 eth so let's go

ahead and test this out end to end we're

almost done with this section actually

you've learned a ton so far so let's go

out let's test this end to end so let's

make sure this is compiled we'll go

ahead and compile this great compiled

successfully now let's go over to the

deploy let's delete that make sure that

we're on our fake chain we sure are

let's move to injected provider metamask

here great that looks fantastic let's go

ahead we'll grab this price feed address

we'll paste it in here we'll hit deploy

our metamask went ahead and popped up to

deploy this we'll confirm we'll deploy

this contract and we can see that if we

look at my different accounts my first


account is active it has this little

Green Dot which means that's the account

that's connected the second account is

not connected so this this 0x 1D 07f

should be our owner so if we scroll down

we hit the owner button 0x1d 07f is

indeed the owner okay great minimum USD

is going to be $5 in units of way we can

see the price feed address balance of

zero fantastic so let's call our first

funding by actually switching to our

account two so we want to switch to our

account two and it's not connected yet

so what we can do though to connect is

hit this little thing here we can

see uh we can edit this right here let's

go ahead and connect account to we'll

hit update account permissions updated

great so now account two is indeed

updated so let's call fund with this

much way so I'm going to copy this paste

in paste the amount in here let's switch

over to way instead we'll scroll down

we'll hit this fund fun function our

mens does inde do pop up you can see

that we're on account two here instead

of account one we're going to scroll

down we're going to confirm and it looks

like that went through and now if we see


this funders to amount funded and we

copy this account to address paste it in

here call it's now got the amount funded

in fact if we copy this right and we

paste the value in here again we scroll

down let's call fund one more time we'll

confirm in our metamask here we can

scroll down we hit call again it's now

updated if we go to funders we look at

the zero with index we see it's that

address here go to the first index it's

also this address here because we funded

twice with the same address if we go to

the second address aka the third index

we revert because the dynamic array and

we've only funded twice nice all right

so our mapping is working great we're

actually being able to fund now let's

stay on account two cuz account two is

not the owner let's try to withdraw

we'll pull up the terminal we'll call

withdraw ah remix is like what are you

doing you crazy like it's probably going

to revert are you sure you want to do

this let's go ahead let's say yeah remix

we know better than you we're going to

send the transaction anyways remix is

now going to pop up saying hey here's

what you're doing I'm going to say great

let's confirm this and it's going to be


blocked so our contract is still going

to have four e in it if we look at

funded to amount funded it's still

returning the same amount and our

funders array still has stuff in it

because it didn't get reset because we

didn't call it with the owner now

instead let's switch over to the owner

let's switch to account one we can see

account one is now connected we'll call

withdraw metam Mass pops up remix didn't

say hey uh this is probably going to

fail which is great we can go ahead and

confirm this it looks like it went

through now if we uh keep this address

in here right if we put our account two

address where is that account two we'll

copy this this should now be reset if I

paste it in and it sure does it now

returns zero and now if I try to access

the zeroth or first element in my

funders array it reverts so it still

shows this under here because the UI

just didn't update but it reverted here

which is fantastic so our smart contract

is doing everything that we wanted to do

this is so fantastic we have a way to

deploy and update some starter variables

in our contract Constructor aka the NIT


function we can fund the contract and

actually make sure there's a minimum

dollar amount they must hit in order to

even fund this contract we're keeping

track of how much and who is sending us

money for us to go buy a coffee then

only we can withdraw the money out that

is withdrawn with this send function

from the contract and then we're going

to reset those data structures that are

keeping track of the funders we have a

way to actually get the price of this

data and we have a little external

function as well so that we can make

sure everything is working this is

fantastic great job now if you want to

go the extra mile and actually test this

on a true test net like sapoia you can

but again like I said getting test net

aoia can be very tricky very difficult

so we're going to so I don't recommend

you do this because you're going to run

into a lot of issues however so I highly

recommend we just stick with the

tenderly virtual test in here which

again shows us all these transactions

very similar to what an Explorer would

do

anyways all right so now basically all

in all your code does exactly what we


want it to do right let me even zoom out

a little bit so that we can see it a

little bit easier right your code does

everything you wanted to but let's level

it up a little bit because there's a

couple of things that we did in here

that are kind of newbie they they make

us look a little bit less Advanced and

they're actually not very gas efficient

so we're actually going to improve a lot

of our code quality to make it a more

readable and B more gas efficient right

remember everything that you do anytime

you change the state of the blockchain

in the blockchain world anytime you

change the state of the blockchain in

the blockchain world you have to spend

gas so whenever we're spending gas we

want to make sure we're doing it in the

most gas effective way so let's level up

our codebase with something called a

mutable and constants and I'm going to

have Taz explain this concept of

immutables and constants and then we're

going to apply it to our buy me a coffee

here so here's Taz sometimes you have a

varable that you know it's not going to

change once the contract is deployed

however you don't want to make this


variable a constant since since you want

to be able to set this value when the

contract is deployed in this case you

can use a immutable so for example let's

say that we have a owner of this

contract owner public

address the way I showed you how to set

the owner for this contract is inside

the Constructor we say def in it and

then inside the Constructor we will say

self. owner equals message. sender now

imagine the case that we know that this

owner is never going to change inside

this contract so what you might want to

use is a constant for the owner to save

on gas since constants use way less guas

than accessing State variables okay so

but if you make this a

constant then we need to be able to

declare the value of this owner when the

contract is deployed for example like

this message. sender and of course this

is the invalid syntax the valuable

constant must be set when the contract

is compiled

but we want to set the value when the

contract is deployed so this is a good

use case of immutable immutables are

like constant but the value is set when

the contract is deployed this is a


perfect example of using immutable since

we know that this owner will never

change once the contract is deployed so

we will declare this as immutable and

inside the Constructor we will set this

immutable variable to have the value

message. sender now since immutables are

like constant we don't refer it with

self. owner instead we simply say owner

and for this example I'm going to

capitalize all of it to indicate that

this will act like a constant owner

owner I'll show you another example

let's say we have bow public immutable

and let's make this U

256 and then inside here let's say bow

is equal to some number which we will

pass as input say B of type

256 and let's set this equal to Bel okay

so this is a example of immutable now

once you declare immutable and you

forget to set it somewhere inside the

Constructor the contract will not

compile to show you this I'm going to

intentionally comment out this code so

bow is not set when the contract is

deployed and when we try to compile this

contract you'll see that it throws an

eror to fix this we need to make sure


that all immutable variables are set

when the contract is

deployed okay our contract compiled

let's deploy this for B I'll pass in 1

two

three and then owner is this address and

B is equal to 1 to3 so in summary

immutables act like constants Gess wise

they're cheap to access like constants

unlike constants you'll be able to set

the value of immutables when the

contract is deployed inside the

Constructor

all right welcome back now that we've

learned more about ambles and constants

let's level up our codebase here to make

it look more professional and be more

gas efficient with these new Concepts so

first off actually before we even get to

the mutable and

Conant let's level up this at the top

here so it looks a lot nicer if at the

top of your contract you use this dock

string type comments remember doing

these three quotes is equivalent to just

doing this hashtag on every single line

right but this means that we don't have

to have a hashtag on every single line

just everything inside of these quotes

will be a comment for example if I were


to just do this you can see this is kind

of now highlighted as orange this whole

thing would be a comment now but we

don't want it to be a comment we

actually want the compiler to look at

this code and use it so we're going to

not comment it so at the top here we're

going to say at

pragma version

0.4.0 we're going to say at license MIT

at title this will be the title of the

contract we'll say actually we don't

need this colon here buy me a coffee at

author this is going to be you and then

we can also do this at notice and we can

tell developers a little bit about what

this contract what it does say this

contract is for creating creating a

sample funding contract now all these

little symbols here at license at title

at author notice are known as natspec

metadata this is a way to provide

documentation to your smart contracts

and it's known as the ethereum natural

language specification format or natspec

for short and you can see in the Viper

documentation they have a little example

here which is pretty much exactly the

same there's a lot of tags that you can


use for your natspec to label the

different parts of your natspec actually

if we look in here we see that pragma

isn't part of the npec so whoops sorry

this does not have a little at sign we

can just do pragma version

0.4.0 and we should remove these spaces

here as well but cool so this already

looks a little bit better right it's

highlighted a different color right at

the top of our contract to tell us some

more documentation about what this

contract even does

great pragma version license blah blah

blah and technically pragma is not valid

natspec so convention right now is to

put it outside of the dock string I

don't love this and I usually will put

it inside of my dock string but this is

the convention that a lot of

professional Viper developers are using

today where they just have the comment

right above the npec string and then

they put this up here anyways so this is

how we can level up our our code with

some natspec at the contract level right

right at the top of the contract we have

this npec in and boom it already is

looking a little bit more

professional great let's finally now


move on to the immutables and the

constant variables here so down here we

have these different values minimum USD

price feed owner funders Etc now as of

today these are all what's known as

storage variables storage variables and

storage variables can be very gas

intensive to work with every time you

read or write to a storage variable it

costs a lot of gas we're going to learn

about storage much much later in the

course so for now just you want to think

of anytime a variable isn't ever going

to change you want to think about how

making it a constant or in immutable

constant and immutable variables mean

that they can never be changed however

these are more way way way more gas

efficient for a whole bunch of reasons

and we can even test this out so let's

take this minimum USD now minimum USD we

set to $5 and then we never change so

what we could do is we could set this

minimum USD to be a constant so we could

say public constant U into

256 and the convention for constant

variables is to have constant variables

be all uppercase so we would do minimum

USD and then since it's constant we


don't set it in the Constructor down

here anymore we would have to set it

right up here so we would say minimum

USD public constant U 256 equals asway

value 5 ether and then we would oops and

then we would

delete this line

here now constant variables are not

considered storage variables which is

another reason why we have them all

updated both constants and immutables

are not storage variables again we'll

learn About Storage much later and since

it's not a storage variable we scroll

down we no longer have to reference it

with self. minimum USD this self when we

do this self. minimum USD we're usually

referring to storage variables or

functions since minimum USD is a

constant we can actually just refer to

it like this in all caps here boom so is

there any other place where we have

minimum USD nope that's it okay great we

can just leave it like that okay the

next the price feed so price feed we set

one time and we never update it again so

can we set the price feed to be constant

well we could if we were always using

the same price feed so I could do you

know constant constant aggregator V


interface you know equals aggregator V

interface wrapped around this address

here oops not the aoia part however this

would assume and let me zoom out so you

can see that however this would assume

that we're always going to use this

address now the price feed for the

ethereum USD price is going to be

different on different chains so we

don't actually want this to be constant

what we want it to be is immutable so

let me undo everything I just did with

command Z or control Z so instead of

constant here we could make this IM

mutable so to set this as IM mutable we

would go mut aggregator view interface

and then now same thing price feed we

would do from lowercase to all uppercase

price feet because this is also not

stored in storage now what we can do

though is right in our Constructor we

can set price feed equals aggregator V

interface the price feed that we pass in

this way whenever we deploy this we will

update the price feed with whatever

address that gets passed in here this

way when we deploy this contract on

different chains we can use different

price feed addresses on those different


change and leave the contract as such so

now I can scroll down let me look for

any spots that we refer to the price

feed same thing here static call self.

Price feed. latest answer we would just

do the immutable price feed instead let

me remove these comments as well okay

great so okay so this one's a constant

because we're it's always going to be

five no matter what this one's a mutable

because it's going to be different

depending on the change that we're on

but once we figure out what it's going

to be it's always going to be the same

the owner hm what should the owner be

well if we change accounts the owner is

probably going to be different depending

on when we change it so the owner we

probably want to be a mutable as well so

we say

immutable and then same thing we're

going to make this uppercase owner we

scroll down here now instead of self.

owner we're just going to say owner and

we can scroll down some more let's look

for any spot we refer to owner okay

great right here owner self. owner is

now just

owner let's look for some more nope that

looks pretty good okay great do a little


clean up here these comments okay so

these are going to be

constants and

immutables okay great what about the

funders dynamic array is this ever going

to change well yes every single time a

funer funds this is going to get updated

so this we have to keep as a storage

variable storage what about funer to out

funded is this ever going to change yes

same thing every single time a funer

funds or we or we withdraw money this is

going to change so we're going to leave

these as not constants and not

immutables now there's one more number

I'm going to update here and we could

probably update a few more numbers but

this in particular is what's known as a

magic number or a floating number and

this is kind of difficult to read and if

you have some really fancy math here you

might not be sure okay what is this

number representing why are we doing

this number now there's a rule of thumb

in programming that you should not have

magic numbers you should not have

numbers that are kind of just floating

in your functions you should ideally use

a variable to describe what the number


does we probably should make this a

variable as well but I'm just going to

make this one a constant at the top so

at the top I'm going to say

Precision is going to be a constant I

don't need to make this public U into

256 equals 1 * 10 raised to the 18th and

instead of doing divide by this random

math here we're just say divide by

precision and if you want to be very

explicit you can also wrap this up

however these are going to be the same

since this variable will get evaluated

as a variable itself and then the math

will happen here

so so now that everything's a constant

and immutable let's see how expensive it

is to deploy the contract and then call

fund as well with these constant

variables right so let's make sure this

compiled let's go to the deploy tab let

me zoom in a little bit here going to

remove that I'm going to be on my

injected metamask on my oh I'm going to

go back to the fake our fake chain here

great we're going to go ahead and use

this price feed address copy this paste

it in let's go ahead and deploy metam

Mouse pops up we're going to confirm

this
transaction great we now have a contract

here awesome now in here let's see first

off how much it cost to deploy this

contract so if we go into the

transaction details we scroll down we

can see the transaction cost this is the

entire cost of the whole transaction and

we're going to copy this and right above

our deploy we're going to say with

constants constants well with constants

and immutables cost this much gas

262,525

call the fund function I'm going to use

this amount right here again we'll place

it into the value section and we'll call

fund MMS pops up we'll go and confirm it

great that went through let's look at

the transaction cost in here copy this

right here and we'll say with with with

constants it's going to be this much gas

10533 to now I'm going to delete this

contract and we're going to undo just

the minimum USD that's the only one

we're not going to undo all the

constants I'm just going to remove the

keyword constant here which means I have

to remove that there in the deploy let's

do self. USD equals asway value 5 ether

which means this should be a lowercase


and then finally down here this should

be self. minimum

USD so we've changed that let's go ahead

and compile this

now let's deploy this again we're going

to use that same contract address where

is that it's up here going copy that

paste it in deploy metam mask going to

pop up let's go ahead and confirm

contract is here now let's see how much

money we saved switching so transaction

cost let's copy this and let's compare

so with constants it cost this much

without just put them Side by side so we

can really see it cost 20,000 extra gas

to use storage variables so we saved

20,000 gas so we want to see how much

that is we can go back to ethereum

converter we can put in

20,000 which it doesn't seem like a lot

based off the price but we technically

saved 7 cents by switching from Storage

variables to a constant just on

deploying the contract so deploying the

contract was seven cents cheaper

okay well what about funding let's do

the exact same thing right let's do the

do

0.002 let's copy this let's call the

fund function all right let's paste


where is it paste that into the value

bit let's call fund metamask is going to

pop up we're going to go ahead and

confirm we'll pop up the terminal we'll

go to debug this let's scroll down to

the transaction cost right here copy

that let's scroll down now we'll say

without it's going to cost this much

money so we saved 2,000 gas by using

constants so a lot less than deploying

the contract but still so imagine all

these little changes can in all these

little changes can add up to a lot of

money you save for people interacting

with your contracts so this is why it's

so important to get these right Plus if

you're trying to make a really awesome

smart contract and someone else sees

your smart contract and decides they

want to make a similar one and all they

do is rewrite the contract to be better

with constants and immutables they would

be able to Market it as hey my smart

contract is way more gas efficient so

you should use mine instead of yours so

this is why we want to be very very

aware of some of these differences like

I said much later you'll learn why it's

actually cheaper to do these constant


and immutables right now it's a little

advanced just know that if we can make

them constant or immutable we should now

I'm going to hit undo a whole bunch undo

undo undo undo undo so I can make this a

constant again and great now we're back

to

normal so right now it's great people

can actually send this contract money

and we can withdraw it which is

fantastic but what if I were to try to

send this contract money without calling

the fund function would we keep track of

who sent us the money well no because

you know they didn't call the fund

function right the fund function is the

one with the functionality here but

would it even work I I told you you know

we've we've seen that contracts are kind

of just like wallets right they have an

address you can send the money so what

if we were to deploy this and you can do

this on injected provider or let's just

do it right on remix VM let's go ahead

and deploy this I'm going to copy the

price VI adds let's deploy this we see

this address here now when you scroll

down to this deployed contract section

and you see the contract you see all

this functions in here but then you also


see this low-level interactions section

now whenever you call a function your

function parameters get transformed into

this thing called call data and that's

something that we'll learn much much

later in the updraft curriculum here but

what we can do here in our remix VM is

we can actually scroll up and put some

value in here so if I were to put like

eth one if I were to scroll down and hit

transact this would basically do the

same thing as in our metamask hitting

the send button and sending you know I'm

pasting the address in here and then

sending one e it would do pretty much

the exact same thing if I were to go

oops so so if I were to go ahead and

send a transaction with one eth right in

our dummy remix VM account here scroll

down to the bottom hit transact we get

this little error in order to receive

ether transferred to the contract you

should have either receive or payable

fallback function now these are keywords

specifically for solidity but Viper also

has something like this in Viper there's

a very special function called the

default function and this is executed on

a call to the contract if no other


functions match the given function

identifier again we're going to learn

about function identifiers much later in

the course but basically if you don't

have one of these fallback functions or

one of these default functions your

transaction will revert it won't go

through Viper by Nature blocks any

transaction that comes through if

there's no default function but we can

go ahead and add this and try it now so

let's go ahead and create an at external

at payable very similar to fund how we

need to make a fund payable we'll say

def uncore uncore default uncore

underscore no parameters pass so that it

just does nothing we go ahead and

compile this now we go ahead we delete

this let's go ahead and copy that

address again copy this paste deploy

scroll down we can see it in here now

let's try to do that again right let's

try to call let's try to send this

contract money directly by having a

value of one for ether and then

scrolling down and hitting transact with

leaving call data blank

and huh actually went through how

interesting does our balance update it

sure does the contract balance is now


one eth as opposed to zero so the

default function is what gets called

anytime you send money to this contract

or try to call a function on the

contract that doesn't exist and you'll

learn how to do that much much later in

the course now what we could do if we

wanted to be really clever here with

this cool default functionality bit is

we could say anytime somebody sends

money to this contract we should have

them automatically call this fund

function so let's do one more bit of

refactoring to make this change so I'm

actually going to make this fund

function

underscore and internal so we're going

to have this internal fund

function and above this we're going to

have an

external exter return all fund function

and all it does is call Self doore fund

like this and same thing anytime anyone

calls the default function or anytime

anyone calls this contractor tries to

send this contract money or do something

with this contract that doesn't exist

we're going to call this fund function

as well so now if we compile this let's


do this again because just actually

before we get rid of this if we look at

funders right fun is a zero even though

it has a balance one eth fun is a zero

you know reverts here fun to amount you

know we'll grab this copy this contract

address fun to amount is still zero but

if we update this to say okay just go

ahead and call this fund function let's

go ahead and remove this contract now we

should go back to injected metamask

great we're on count to let's do this

whole thing again let's copy this add

address let's paste it in here let's hit

deploy MMS pops up we hit confirm we

scroll down we click here now let's do

this where we have one ether in our

transaction here and we scroll down and

we just hit transact what happens or

since we're using injected metamask now

we can also just copy the address go

right into our metamask hit send paste

that address in here we can send it you

know any amount 0.5 eth for example we

add one in here and then we scroll down

and we hit transact metamask is going to

pop up we're going to say okay amount is

1 eth let's go ahead and confirm this

scroll up it looks like went through

fantastic now we can see the balance in


here is 1 E again however if we grab our

address here and we look at this funders

to amount funded we paste this in we do

indeed see a balance and if we look at

funders of index0 we see that address

here so this default function is

incredibly powerful and this actually

gives our smart contract some extra

functionality if somebody sends US money

even though they forgot to call the fund

function we would still keep track of

them as a

funer now there's one more thing that I

have to show you before we log off here

so way down here I went ahead and I

showed you this where is it this send

line here now this is the the easy way

the simple way to send funds however

it's not exactly recommended as far as

security goes so I'm actually going to

show you the more advanced way to send

funds here and it's this way that you

should always default to when sending

funds there's an issue here with gas

where the evm might change how much gas

different op codes call a big one being

logging it's kind of really low level

the rationale for why this line is an

issue so I'm going to not go over why


it's an issue right now you can later on

in the curriculum you'll start to

understand I'll let you do a little

research on why this is an issue

yourself but for now I'm just going to

tell you don't do this ever again so you

learned how to send here but don't do

this ever again this is the only time

you're going to use this send keyword

instead we're going to use a different

keyword we're going to use this built-in

function called raw call and this is how

you can actually call anything any

single function in the whole world even

if a smart contract doesn't have that

function and that'll make sense much

much later in the course we'll learn raw

call and how to use it to its most

Effectiveness much later in the course

so it's this command that we're going to

use and we're going to use this value as

well so so back in our remix instead of

doing send here we're going to do raw

call and then we're going to say value

equals so we'll say value equals self.

balance like this we also have to say

where we want to send this so we're

going to send it to the owner and then

we also have to do this B and then some

empty quotes in here this b stands for


the data that we're sending with this

raw call and we're going to be sending

nothing now at first glance this is

going to seem kind of bizarre it's not

really going to make sense what this is

doing but that's okay I'm just going to

tell you right now now consider this for

the raw call this first input is the two

for now just leave this blank this is

the data and this is how you leave it

blank and then to send the value to

Value equals self. balance if there's an

error Viper has a builtin revert on

failure and this defaults to true so it

will go ahead and revert if this fails

so for now we're going to do it like

this so anytime you see a line like this

just know that it's doing the send

there's a reason that this is actually

safer than this and the reason is kind

of really Advanced so we're going to

save it for another time can learn more

about raw call and kind of the more

advanced features that it does if you go

to Viper by example and you go to Raw

call down here but like I said we're

going to go over this lowlevel raw call

much later in the

course all right so you've done it


you've built a very minimal but

professionall looking smart contract

project you we worked with an interface

to get the ABI we're working with

calling other contracts in order to get

real world data into our contract real

world price feeds we refactored some of

our code to be more professional by

adding in constants and immutables to

make it much more not only much more

professional but also much more gas

efficient we're able to fund the

contract keep track of funders with a

minimum amount you have to spend at

least $5 worth of E in order to fund

this contract you can either call the

fund function which is up here or you

can go ahead and you can call no

function at all you can just send the

contract money and it will call the fund

function for you and keep track of your

donation in the smart contract itself

we're able to get pricing information in

this contract from a decentralized chain

link price feed and then finally we're

able to withdraw the money out so we can

actually go buy a coffee but only the

owner can actually withdraw the money

because we've implemented access

controls for it now this is the Viper


fundamentals section of the course

however there's a number of things that

we haven't covered for Viper

fundamentals because it does get a

little bit more advanced and we will

cover that in the Python and the

mckinson section of this course some of

the fundamentals that we haven't covered

are flags events Tri catch function

selectors encoding hashing modules

Imports and testing however learning

these are more advanced so we're going

to learn that in the moxon section of

this course and then going over them now

doesn't really make sense until you have

more context so we're going to go over

them later and the reason I'm bringing

that up is because this is the last time

we're going to be working with the remix

IDE thank you so much remix you've been

very helpful in helping us understand

the basics of smart contract development

however if you have gotten this far you

can drop into most Viper code and be

able to get an understanding of what the

code is doing you could see a Viper

contract and go hey you know what I I

actually understand some of this code

which is so incredibly powerful already


you should give yourself a huge round of

applause a pat on the back for doing

this because this is hard stuff and as

always I hope you're using AI to help

you and as always I hope you're using Ai

and the discussions to help you along

the journey when you get stuck or when

you run into obstacles so let's do a

quick refresher of all the different

things that we learned in this section

and then we can send you on your way to

the really powerful part of the course

where we get into Python and Moccasin

and titanoboa so we learned a little bit

about natspec or a way to document some

of our code and our contracts and we

learned a and we learned the most

elegant setup for setting up our

contracts here where we use pragma

version in a comment and then we use

these different tags like license title

author notice in these three quotes and

comment in order to comment on what the

contract is actually going to do who

wrote it what it's about the license Etc

we learned how to work with an interface

for working with other contracts and

interacting with other contracts this

interface will give us the ABI or the

application binary interface which is


kind of a mouthful but basically this is

going to be the way that tells our

compiler hey here's how you can interact

with other contracts here are the

functions that exist that you can call

on those other contracts and we created

a price feed of type aggregator V3

interface of this interface where this

price feed if we scroll down we're able

to call where is it latest answer

because our interface says hey this

latest answer function exists on this

price feed and the and there's some code

at this address which says hey here's

what this price feed stuff does if we go

to sepolia Ether scan we can even drop

this address in here because again we

said that this exists on the spolia

Chain we can hit this contract tab we

can scroll down and we can see ah this

is actually written in solidity and we

can see all the solidity code here

what's really cool is that by learning

Viper you're actually going to be

learning a lot of solidity as well all

of the same Concepts that work in Viper

also work in solidity we learned about

constants and immutables and how these

can save us a lot of gas in the long run


and then we learned that these constants

and immutables are somehow different

than these storage variables we don't

quite know why but we know that they're

different and we'll learn why later we

learned about Constructors or the init

function of our smart contract we

learned that when we deploy our contract

this will automatically get called the

instant we deploy our contract and we

can actually send and we can actually

deploy our contract with parameters that

we can update and add right when we

deploy the contract we created a

function called fund which was payable

which is a decorator that allowed us to

actually send eth to this contract

without this payable decorator you

actually can't send any eth you can't

work with message. Val so we have this

payable decorator where we said hey you

can send us money as long as you send us

at least $5 worth of eth and we use that

price feed function if we scroll down we

use this function where we statically

call the price feed to get information

we learned about static call versus X

call we learned that they're different

we don't ex we haven't actually seen the

difference between the two but we know


that they're different we learned about

converting different types we can

convert an INT 256 to a u 256 with the

convert function we learned about

integer division in Viper and we learned

about magic numbers and how they're not

cool it's much much better to use a

constant variable this technically is

also a magic number so if you want to go

the extra mile and turn this into

something else you should do so we

learned about this default function or

this fallback function where if you

don't call any function in the contract

or you just send it money it will

automatically trigger this functionality

here and we set our contract up so that

if you were to send this contract money

it would trigger the fund function which

keeps track of all the funders we

learned about Dynamic arrays versus

fixed sized arrays where fixed size

arrays the instant you create one it's

always going to be that size whatever

size you say whereas Dynamic arrays have

a maximum size which is very different a

fixed size array if you say there's 100

elements in it it'll populate every

single element in it with a 100 in it


whereas a dynamic array will start empty

and you'll have to add things with the

append keyword but the append keyword

doesn't work on fixed size arrays

because it's always the same length

there's only a length function for the

dynamic arrays not the fixed size arrays

we learned about some of the trade-offs

between using a mapping versus using an

array or a list the mappings are great I

can look up an address and immediately

get back how much they funded however

they're incredibly hard to reset because

you have to individually set them all to

back to zero however the dynamic array

is really easy to reset you say hey a

new blank Dynamic array and boom that's

it we learned how to send money from

inside of our contracts which is very

straightforward you just do the send

function we say we're going to send the

owner the self. balance self is

referring to the contract you're

currently in so send the balance of this

contract we did a very clever for each

loop we're saying for every address in

the list of addresses for every funer in

the list of funders reset their mapping

and we also learned a little bit about

dock strings inside the functions


themselves now later on we'll probably

make these doc strings look a little bit

more professional as well but this is

good for now so with all that being said

now that you have your buy me a coffee

contract now is a great time to go get a

coffee yourself or if it's late now

might be a good time to go get some ice

cream go to the gym go for a walk

whatever you want to do cuz now is a

great time to take a break and I highly

highly highly recommend taking breaks

because your brain will not absorb

information as well because your brain

absorbs information much better with

breaks added in so go take a break gear

up for the next section because we're

getting closer and closer to switching

over to Python and Moccasin so take that

break and I'll see you soon

now we're going to be doing the AI

prompting section from the solidity

course here working with AI in Viper is

pretty much the exact same as working

with AI in solidity so we're going to be

playing we're going to be going over the

AI prompting section from the solidity

course and we're going to be using some

solidity examples the code won't make


sense to you because obviously you

haven't learned solidity yet however the

concepts are going to be exactly the

same so the examples will be solidity

but don't worry too much about that just

focus more on the AI prompting and how

we prompt and what we do to do code

blocks and and stuff like that

definitely 100% we want to go through

the setting up GitHub you should 100%

have a GitHub set up by the end of this

whole section and and by the end of this

you'll have a decent understanding of

how to work with AIS how to ask

questions in the different discussion

forums how to format those questions and

the like being a developer is actually

much much more than just knowing how to

code stuff because a lot of the times

yeah you can just ask an AI you can just

Google something being a developer often

times isn't so much knowing the answer

but knowing where to find the answer or

how to get the answer so it's incredibly

important that you get used to using

these tools so that when you're coding

you can find the answer so with that

let's go ahead into this AI section

now a lot of people get discouraged by

AI thinking ah like why even bother


learning anything if AI already knows a

lot of the stuff well in order to think

critically about problems and how to

solve them you always need the

prerequisite knowledge before you can

even start coming up with solutions to

fix a problem so yes AI knows a lot of

things but in order for you to solve

problems effectively you need that

knowledge as well so you need to take

the knowledge from AI thank you AI for

giving us all this knowledge as well so

that you can think critically and come

up with better Solutions than AI could

ever do because as of today that's where

humans shine we are phenomenally better

at coming up with Solutions and AI is a

tool to help us have even better

Solutions but in order for us to come

with the best Solutions we need the

knowledge

first believe it or not we do have a

little workshop even for this AI section

here why well because you should get

really good and really familiar with

working with AI even though for for most

of these workshops I'm going to tell you

to not use AI when you actually go out

and start coding and start building real


projects you will definitely be using ai

ai is a tool that's going to supercharge

your development and your learning

experience I use AI all the time in my

professional coding and I use it so much

that I also am very aware of what its

limits are I know where it's bad and I

know where it's good I know where it can

help me and I know where it's going to

screw me up if I blindly try it working

with AI understanding that AI is here to

help us but being so good at what we

work with we know when AI is being dumb

is crucial to Our Success here so I have

a workshop for you I want you to get

idea for how good your AI is maybe you

are working with claw. a maybe you're

working with where is it chat.com now

chat GPT maybe you're working with the

find AI what whatever AI you're working

with and maybe even do all of these AIS

try to start getting a good idea of how

good they are at smart contract

development start asking them some

questions like literally ask them these

questions hey could you make a minimal

Viper contract for me asking some

questions that you know the ANW to

what's the difference between a dynamic

array and a fixed size array in Viper


here's some Viper code literally copy

paste this in and say what does this do

or ask it even harder questions that you

know right we've learned a lot in this

section section we've learned a lot in

these two sections already you have some

good knowledge about how Viper Works

maybe even ask it this even harder

question right in our buy me and coffee

we learned that we want to do raw call

instead of send maybe ask it hey is send

safe in fact as I was talking I decided

hey that's actually a pretty good

question let's actually try it out right

now so I'm going to copy this let's try

it on find First the free version of

find is this Viper code safe let's give

it the back tiex send based on the

provided code at search results here are

the key points regarding the safety of

the Viper code blah blah blah blah blah

blah adding a balance check before the

transfer no no you lose that nope that

wasn't good enough okay what about

chat.com the free version of chat TBT is

this Viper safe let's see if it gives us

the the raw the raw call answer I'm

going to hit enter potential issues use

of self balance blah blah blah


conclusion what's a better way maybe we

should ask at that use the withdraw

pattern uh wow chbt did give us the raw

call well done chat so that's actually

pretty pretty good the the code here is

kind of wrong but it actually did a good

job using the raw call okay what about

Claude paste it in here this looks like

it's Claude 3.5 oh ran into an issue

let's try again and uh I've reached the

limit of my free trial here so try out

some different AIS see how you like like

them see how intelligent you think they

are and then come

back congratulations you've just

completed the introduction to Viper

Viper fundamentals AKA Viper 101 you

should be incredibly proud of yourself

you've learned a lot of the basics of

working with Viper and smart contracts

including deploying them writing

functions sending ethereum or whatever

native blockchain currency

and so much more you should be

incredibly proud of yourself because

just with this skill you can actually go

into different smart contracts and start

reading them and actually have a general

understanding of what they're really

doing but we're really just scratching


the surface here there's so much more

for you to learn to become a positive

force for the blockchain and web 3

Industry now that you've learned the

basics of Viper we're going to now move

to python Titanoboa and Moccasin these

tools are going to allow us to build

much more professional setups and one of

the best parts about taking this Viper

and python course is that AIS are

massively trained on Python and can give

you incredibly good feedback on how to

improve your python especially from the

beginner sides additionally a lot of AI

tools are written in Python so you're

not only going to learn more advanced

smart contract development techniques

and some security techniques as well but

you're also going to be working with the

language that is dominating the AI

industry as of today and additionally

moccasin is a pythonic smart contract

development framework that's going to

help us deploy test and do way way way

more advanced and really cool smart

contract tricks they're going to help

you on your journey here so as always

now is a great time to go for a walk go

get some ice cream or go to the gym


because the next thing to learn is going

to be the moccasin fundamentals which is

also going to teach you a lot more of

Viper so congratulations on finishing

Viper Basics and I'll see you in the

next one

welcome back to the moccasin and python

fundamentals section where you're going

to learn how to build and deploy even

more advanced Viper Smart contracts

using some really powerful python tools

the main tool that we're going to be

working with is this tool called

moccasin which is a smart contract

developer framework we're going to be

teaching you the same tools that the

pros use so buckle up and let's get

froggy Now remix is a phenomenal tool

but pretty soon we're going to be moving

over to this tool called moccasin which

is going to give us more which is going

to give us a more professional setup for

deploying and testing and working with

our smart contracts however before we do

that we're actually going to teach you

how to do a lot of the basics with raw

python with no Frameworks no nothing

just Python and Viper that's it and this

is incredibly helpful for you as a

learner because you'll learn what's


going on under the hood of moccasin and

then additionally if ever you want to do

something yourself do something manually

you can come back and just do it right

in Python additionally Additionally you

will also learn a lot of the basics of

python here as well and how we work with

python in updraft I'm going to be

teaching you a lot of modern best

practices for working with python that I

think are going to help you in the long

run help you really understand what's

going on that a lot of other python

tutorials kind of skip over sometimes

and similar to everything that we've

been working with so far all of the code

for all of our examples are going to be

in the GitHub repo associated with this

course as of recording I just haven't

put them in here yet but they will be

here don't worry additionally especially

when it comes to setting up and

installing these tools we've got a ton

of really really helpful links in here

for you to use as I've said many times

installing some of these tools and

getting going

is often the hardest part of the entire

course is just installing stuff AIS are


phenomenal at helping debug installation

issues so we'll be using those when we

teach how to do some of these

installation methods here now you might

be asking a pretty astute question here

you might be saying hey uh Patrick why

are we even going to this other tool why

are we even going to python why are we

even going to Maas and remix is working

great like I'm able to deploy contracts

what are you talking about here's what

the issue is we had to do a lot of

manual work to do anything with remix if

I wanted to deploy this contract I would

have to go okay first I got to go

compile it I got to wait for the compile

okay cool and then I go to the Run tab

well let's say I didn't have this

contract in here have to okay I got to

switch to the correct Network that I

want to be on okay cool I got to okay

let's grab the price feed let's Okay

then I deployed it um let me look in

here whoops I made a mistake okay I got

to

un delete that I got to come in here you

know make my change whatever it is I got

to come back I got to recompile I got to

go back hit the deploy and then I got to

paste this back in or I don't have the


red address paste it in okay maybe I

maybe I make a new function or something

okay I want to see if it actually works

I go redeploy I go check it works after

some time let's say you have a thousand

different functions and you want to test

that they're all still working when you

go back and you make some small change

you don't want to have to press every

single button press deploy press get

Contract make sure all your new

functions are working it's going to take

you forever to get anything done in

remix so we want a framework that

automates all of this for us and so that

we can make sure we test every single

part of our codebase in a reproducible

manner smart contracts are fickle if you

have a bug it can be a disaster it can

ruin your entire smart contract so we

want a way to interact with test deploy

script and all of that stuff in a more

programmatic autonomous way rather than

us manually clicking buttons in Moccasin

we can do all of that in one command in

one click like I said we're going to be

teaching you Python and titano first and

then we're going to be moving over to

moccasin and now additionally now that


you're on this moccasin fundamentals now

if I scroll down in here there is a

flagship project in here let me scroll

down where is it it's got a big star

next to it moccasin buy me a coffee

later on in this course in this working

with moccasin working with python

working with Viper we have a how to get

hired and this section is useless unless

you finish this section this is where

we're going to push code up to GitHub

we're going to start working with a

cyphon profile Etc so you must must must

must must get to this

section now for this section we're going

to do things a little bit differently a

little bit differently than a lot of

python tutorials there are a lot of

great python tutorials out there such as

this one from free code Camp if you want

to learn a lot of the deep more

fundamentals of python you can go ahead

take this one on free code camp or

really any other to be honest YouTuber

can teach you a lot of the fundamentals

of python there's so much free content

out there on Python and AIS are so good

at python that I highly recommend that

you don't take a paid course if you want

to pause the updraft tutorials and go to


python however I am going to give you a

crash course and we are going to give

you a crash course in Python here and

we're going to do it a lot differently

than a lot of the tutorials out there

the way we're going to do it is we're

first going to walk you through coding

in Python with this tool called Google

collab now the reason we're going to

start with this is because you don't

have to do any downloading or any

installations or anything like that it's

very similar to remix how we were able

to do everything online and in the

browser with Google collab we can

actually do the same thing we can do

everything online and in the browser

window here without having to fiddle

with our local setup and the completed

code for this Google collab will be

located here and we'll do a brief walkr

of everything that you're going to see

once we do this Crash Course once we

walk through this python crash course

and again hint hint because you actually

walked through both of these I secretly

was teaching you python the whole time

this python crash course is going to be

a breeze for you once you finish going


through this Google collab then we'll

walk through getting you set up on Mac

OS and Linux and getting you set up on

windows with WSL Microsoft will tell you

to set up your development environment

using python from the Windows store

using Powershell using all this stuff

and I'm going to tell you right now

we're not going to do that I don't want

you doing that that's not how

professionals do this we're going to

teach you the Linux based way which

which is how maybe 90% of all developers

work probably 99% of smart contract

developers maybe 90% of not smart

contract developers but we're not going

to follow this Powershell this Microsoft

way we're going to do it the updraft the

web 3way so first we're going to go over

Google collab and do a python crash of

course then we're going to go up

installation and setup based off of your

local environment and then we're going

to do this python in updraft section now

if you are pretty good at python if

you've got a good foundation if you've

got a good grasp of python already skip

all of this but don't skip with the

python and updraft section I promise you

there is a pretty good chance that the


python and updraft section will be

different from what you're used to so

wanted to give you this heads up that

this is the steps we're going to take

we're first going to walk through a

python crash course with Google collab

then we're going to learn how to

actually install and set up python on

your computers and in my opinion this is

actually the hardest part of this whole

course is getting python set up locally

let's get started with the python crash

course yes you're learning smart

contract development but we're also

teaching you python if you're brand new

to coding we're doing double duty here

you're learning Python and your learning

smart contract development so let's go

ahead let's get started with Google

collab

so if you're following along with the

course now let's scroll on down to where

are we at we're going to our moccasin

fundamentals starting with section one

the python crash course and we're going

to be using this tool called Google

collab it's a online browser IDE for

typing and working with python and you

can see kind of all the different code


that's in here this is the final code

and if you get lost or you get confused

click this link and you'll be able to

see the code in here so to get started

let's go ahead and click this link here

which will open up us into Google collab

which like we said is kind of like an

online pythonic IDE this will be the

final Google collab here however we

don't want to use the final one we're

going to start from a brand new one so

what you can do now you will need a

Google account to use this so if you

prefer to not use a Google account if

you don't want to use Google collab and

you're familiar with other python

notebook tooling feel free to do so but

to use this you will need a Google

account so this is going to be all the

completed code but we don't want to use

the completed code here we want to do a

new notebook so that you can practice

getting these done yourself so we're

going to select file new notebook and

drive which will open us up in a new

notebook here so let's go ahead and name

this updraft python or whatever you want

to name it and let's go ahead and get

started with with this python crash

course these are known as Jupiter formly


IPython notebooks and it's an open

source project that allows you to easily

combine Mark text Python executables and

more into this thing called a notebook

in this notebook you have all these

different cells where you can run little

Snippets of

python so it's in these little sections

here is where we can add our code if I

wanted my program to just print hello I

could say print

Hi and then go to runtime and hit run

selection and it will run this little

this shell this little line here you can

see at the bottom it has to do a little

bit of setup first and then we get

printed out here hi you can see there's

a lot of keyboard shortcuts as well to

do a lot of what we're going to be doing

here I did run selection which was this

set of keyboard shortcuts here so I can

also just do the keyboard shortcut and

that will also run the cell now when I

hit runtime run selection I'm actually

just running that single line that my

cursor is on so if I have several lines

like print high and down here print by

if I have my cursor on the print high

and I do runtime run selection I'll just


run after a brief delay I only get

printed out High however we can also

press this play button here and this

will run everything inside this little

box which is known as the sell if I hit

the play button here we now see high and

buy if I put my cursor directly on this

line and I do runtime run selection I

will only print out buy now for most of

these the easiest way to run the whole

cell is just to click this button like

here you can also run the whole cell

with keyboard shortcuts like shift enter

which will run the whole shell and also

create a shell down here you can hit

command enter which will also run the

whole shell or control enter and there's

a lot of other keyboard shortcuts that

you can run as well if I wanted my

command to print something El I could

print something like bu run the sell

again and we will get buy gets printed

out now we can additionally have

comments hi I'm a comment anything

that's prefixed with this little hashtag

here means anything after it is going to

be a comment so this too would be like

another

comment and comments are parts of the

code that will not be executed let's


change this back to hi and run again and

our code prints out

High what's really nice about Google

collab is that if you don't understand

something you can use the AI features

such as Google Gemini I'm going to go

ahead and hit Gemini here be sure to

read the Privacy notice let's continue

and you can enter different prompts here

we could even copy all the code here if

we don't understand what's going on go

into Gemini and write a little prompt

what does this code

do three back ticks another new line

with shift enter paste it in shift enter

again three more back ticks this is

typically how you notate that something

is code you put three back ticks put all

the code and three more back ticks so

what does this code do let me zoom out a

little bit we'll hint hit enter Gemini

will start thinking okay let's break

this down this line is a comment

comments of python start with the

hashtag symbol they are ignored and

python interpreter are and are intended

for humans to read this comment is

simply saying hi I'm a comment print

high this line is a function called to


the built-in print function this

function takes one or more arguments and

displays them in the console in this

case it is printing the string hide to

the console and then another comment and

blah blah blah it even gives you some

sources for where it learned how to

understand what this is doing it did a

little bit of Googling itself on the

back end so as you're coding as you're

learning feel free to use different AI

features to help exped your learning

process here and then we can hit these

three dots close tab to close the tab

here okay great let's keep this here and

then if you want to save this locally

for later you can hit file download and

then you can download this as a py NB

orp file for you to have it locally if

you want to study offline as well but

let's go ahead let's create a new cell

or a new block of Code by scrolling down

and we'll see this Plus Code button here

and we'll click that and we'll get a new

so if you want to practice using some

generative stuff you can if you want to

practice using some generative code you

can click generate here and you could

type something as simple as write a

print statement to print out the word I


hit enter and it'll give you exactly

kind of the code that you want here it's

important though that you do understand

what this code is actually doing so that

when AI gets it wrong you can actually

correct it but let's go ahead we'll

close close this and we'll delete

everything in here and start with the

next

section so let's talk about variables in

Python you can assign different

variables and my generative AI is even

giving me a suggestion here and

variables are essentially just keywords

that we can use to represent some other

value for example I can say my variable

equals 7 now anytime I use this keyword

my variable it's going to represent the

number seven so if I were to print out

my variable what do you think it would

print out well if we hit this little

play button here to execute the cell we

see it prints out the number seven

because my variable now represents seven

uh the keywords or the names of your

variables can be almost anything that

you want you can assign almost anything

to a variable and python comes with many

types for example we can assign numbers


my number equals 10 you can assign

something called booleans which are true

or false you say my Boolean equals true

we could also do false you can assign

whole strings or texts my string equals

hello strings are notated by being

between these little quotes here you can

use single quotes or double quotes both

work great in Python if the words string

is a little confusing to you just know

that anytime someone says hey this is a

string a string just means it's text it

means it's not a number it's not a

booing it's just

text additionally in Python we can use

something called type hints where we

could say my

typed number we would then put a little

colon and say int equals 9 or whatever

number we wanted to put here this little

colon and then int is known as a type

hint and it's more helpful for human

beings to know that hey anytime you see

my typed number that's going to be an

integer or a number we could also say my

typed bull which is of type bull equals

false we say my typed string which will

be of type Str Str or string equals hi

so Str Str is a type hint for string

bull is a typeint for a Boolean which is


a true false int is a typeint for an

integer AKA a number can also update

variables so my variable originally

started off as seven we can copy this

value paste it here and then we can

update it to

77 so you can have all these really cool

variables and there are even more

complicated variables that you can have

so let's create a new section a new cell

here and let's create a list so or an

array so let's say my list

equals

cat true your lists can be of just about

anything and you can even type into your

variable my list by saying my list is of

type list these little brackets notate

that this is the list and these are the

different elements or objects inside of

the list so seven cat and true are in

the list we can also print my list same

as we print any other variable and if we

hit the play button here we see seven

cat true now each one of these objects

in a list has a certain index so seven

is the first item in the list cat is the

next item in the list or the second item

in the list and then true is the third

item in the list however in Python and


in most programming languages the first

index is actually the zerith index so

seven is actually at position zero cat

is at position one and true is at

position two this can be a little

confusing at first but after you use it

for a while it becomes second nature now

that we know each one of these elements

or these items in our list have a

different index we can actually update

specific indexes so I could say my list

at index one and we use these bracket

notations to do so

equals dog or is set to dog way to read

this equal sign is set to so we're

saying my variable is set to 7 my list

of one is sent to dog now if we were to

print out my list again and run and

execute the cell we now see seven cat

true and then seven cat dog because we

updated the element at index one which

previously was cat we updated cat to dog

python also has some incredible features

to help sort list and make them much

easier to work with so if we had a list

of numbers my numbered list equals 0 7 8

2 3 or 3

99 this list is pretty out of order so

what we can do and if we were to print


it right now print my numbered list

let's go ahead and execute the cell we

see it's still out of order what we

could do is we could call my numbered

list. sort and then print it out again

execute the cell and we would see it's

now in the correct order this do sort is

known as a method or a function of the

list so let's scroll down let's create a

new code section and let's talk about

input so we can additionally have our

code prompt users for information so I

could say

input what is your name and then execute

the cell and we see python is actually

going to prompt us saying what is your

name if I type anything in here right

now nothing happens it just says I just

said my name is Patrick and it said oh

okay cool your name is Patrick so what

we could do is we could save whatever

input the user has has to a variable so

if I say name equals input what is your

name and then print out my name is plus

oops name this plus operator here is a

way for one string to be concatenated

with another string so if I go ahead and

I hit play here and I type in Patrick

what do you think it'll print out mying

name is Patrick my name is plus whatever


the input was given us plus name which

is going to represent whatever we set

for the input another way to represent

this kind of string with concatenation

is using something called an F string so

I could also say print F and then our

quotes here curly brackets name is my

name so if you have an F string if you

prefix your quotes with the character F

and then in curly brackets you have some

variable it'll input the variable inside

of those curly brackets so now if we

execute this cell and I say my name is

Patrick it's going to say my name is

Patrick and Patrick is my

name now I can create a new code block

and let's talk about types you can

convert types from one to another using

something called casting for example

let's say I had this year equals

2025 now since this has quotes around it

this is technically a string this is a

string if I got rid of the quotes it

would be a number it would be an INT but

since it has quotes it's a string now

what if we tried to add 25 to this year

number here well let's go ahead and try

it out let's say year plus 25 five and

we'll execute the cell we actually get


an error can only concatenate string not

int to string since 25 is an INT and

year is a string right because year plus

25 is essentially doing 2025 as a string

plus 25 python goes hey you can't

actually do that so what we can do is

since 2025 is clearly a number we can

typ cast it to being an int so we'll say

year as int equals int year and now we

can do year as int plus

25 execute the cell and we see 2050 here

you'll notice that I didn't put a print

line here that's because in these python

cells whatever the last line is will get

printed but it's probably better to just

wrap this up as a print or to copy this

to a new variable called added up year

equals year is into plus 25 and then

print the variable here and let's

execute that cell and we get 2050 again

you can also convert this number back

into a string so we could say year

string equals Str

Str open and close parentheses and then

do a little print year string

plus is 25 years after

2025 execute this line and we'll now see

2050 and we see the print line that we

just added 2050 is 25 years after

2025 let's do a little bit of math you


can do math in Python so let's start

with simple ads here my number equals 5

5 + 5 print my underscore number the

little plus button here add 10 5 + 5 is

10 good job python

print

subtract my number equals 5 - 5

print my number that should be zero

let's go ahead and try that out great

subtract gives us zero let's do

print

multiply my number equals 5 * 5

print my number we'll

do

print

divide my number equals 7 /

2 print my

number and let's hit the execute but and

I'll zoom out a little bit here add 5 +

5 is 10 subtract 5 - 5 is 0 multiply

great 5 * 5 is 25 Great Divide 7 ID 2 is

3.5

awesome now there are even more advanced

types of math that we can do for example

we can do something called integer

division so we'll do a little print

integer division

division to do some integer division we

could say my number equals 7 divide


divide to print my number integer

division will always round down your

division to the nearest whole number and

it will get rid of any decimals so 7 / 2

is 3.5 but 7 integer division by two is

what well let's press play we can see 7

/ 2 with integer division will just be

three we can also do something called

modulo This is where you'll get the

remainder of division so we could say my

number

equals

7% to this percent stands for modulo and

then print my number what do you think

this will give us let H the play button

returns one because 7 divid two gives us

three even divisions and then we have

one left over so ID two we get 2 + 2 + 2

but there's three twos and then we have

this additional + one this one is the

remainder in our division so that's how

we get the modulo of one another example

would be what's six modulo 2 well 6 is

evenly divisible by two so this will

give us what if we hit play gives us

zero because six divides perfectly into

two if we do six divided 4 what do you

think we'll get we'll hit play we get

two because 6 ID 4 is 1.5 and that one

that 0.5 represents the two remaining so


let's put this back to 7 modulo 2 and

that's how the module works we can also

do things like

exponents which are represented by my

number equals 2 Double multiply three

this double multiply means raised to the

power of three and then we can print my

number hit play and we'll see exponents

is eight 2 raised to the power of three

is

eight right let's create a new section

now and now let's start talking about

functions functions can be written by

typing out the defa keyword a function

is a self-contained reusable chunk of

logic now this is especially where AI is

going to be helpful because functions

can be very tricky and difficult to

understand but let's say we wanted to

create a function that will print high

two times for us so we can create a

function by having the defa keyword then

we'll give our function a name print

high two times open and close

parentheses and then a colon here we'll

explain what this parentheses bit do in

just a a minute then we'll hit enter and

you'll see that Google collab will even

indent your function a little bit here


so the line doesn't start over here it

actually starts up here tabbed in this

is because when it comes to functions

python is a indentation based language

where you need to indent to type the

body of the function so this is the

function name print high two times and

anything that's indented will be

considered part of this function so if I

print the the keyword high and then in a

new line I print the keyword High since

high here is indented this print line of

high is considered part of this function

but python will see that this is not

indented and say oh well this line isn't

part of the function so if I indent it

though now both lines are part of print

high two times and we have two I print

statements if I run this cell right now

nothing will happen we don't see any

highs printed out but if I copy print

high two times and I'm doing that with a

little bit of a shortcut of double

clicking print high two times and then

hitting command C or contrl C and if I

paste out print high two times and add

those parentheses and then I run the

cell it's going to print high out two

times this is because this is considered

an invocation or a calling of our print


two times function up here where we have

def print two times this is just where

we defined hey any time somebody calls

print two times these are the things

that they should do they should do print

high and then print high but you should

only do these things when somebody calls

this function and this line down here

where it says print two times with the

open and close bracket that's an example

of somebody calling that method or

calling that function so this is why you

see it print out high high after we

added this line here because because

before we had this line here nobody was

calling this function so now anytime I

want to print high two times s instead

of having to write this print high twice

we can just put this function I could

even do it again and I'll hit play and

now to do high high high high functions

are incredibly useful for when you have

very complex or or chunks of logic that

you want to reuse and because this is

much easier to write often than writing

all the code inside of a function now

you can also create functions where you

pass parameters to them for example I

were to say def print some word and pass


in my word

print my word like this we now have a

function that takes some word as

parameter and it's going to print it out

so now I could call print my word or

print some word miss you Mom and we'll

run this and we'll see it prints out

miss you Mom because print some word is

called with this as an input parameter

miss you Mom gets assigned to my word

and then we print out my word so you can

almost think about when we call this

line miss you mom is placed into here

and print my word is placed into here we

can also do more interesting things with

math we could

say def add six my

number and we could just do

print my number plus 6 so now we have a

function

that takes some number as an input

parameter add six to it and then prints

it so if I now call add six of 10 it

should print out 16 let's hit play and

we see it does indeed print out 16 you

can also have functions that take more

than one parameter so I could do like

def add

together my first number comma my second

number and just say print my


first

number plus my second number like this

and I could just call add together comma

20 and it will add 10 and 20 together

and then print out the result so if I

hit play here scroll all the way to the

bottom 10 + 20 is 30

python you can also have this concept of

what's called conditionals so let's

create a new cell or a new chunk of code

and in here we can do if/ El statements

which are known as conditionals I could

say if 7 is greater than five print 7 is

greater greater than five and I could

run this code right as it is here and

we'll see 7 is greater than 5 isn't

indeed printed out if I wanted to see if

these were equal I could say if 7 double

equals 5 print 7 is greater than 5 and

if I were to run this cell does not

print anything out because 7 is not

equals to five you'll notice I'm using a

double equals here and not a single

equals here because technically this

single equals is saying set to so if I'm

saying if seven is set to five which

doesn't really make sense so if I want

to check if they're actually equal I'll

say if 7 is equal to 5 and again if we


print this out nothing gets printed

because 7 is not equal to 5 you'll

notice just like functions we have some

indentation here if I remove this

indentation python actually gives us an

error and saying it expected an

indentation block after an if statement

so we'll go back we'll indent it we'll

run it it doesn't print out but if we

say if s is greater than five we print

it it'll say 7 is greater than five we

can also do an else statement with this

colon here we'll hit enter

print 5 is greater than

seven so if we run this line again we

still get printed out 7 is greater than

five because what we're saying is if 7

is greater than 5 print out 7 is greater

than 5 else prints out

5 is greater than 7 if we were to flip

the sign around to say if 7 is less than

5 print 7 is greater than five now since

seven is actually not less than five

it's greater than five it won't execute

this line it'll go to this else

statement and execute this line so now

if we hit play we see 5 is greater than

7 this is kind of similar to saying if

true do this if other wise do this so we

can even run this and we say 7 is


greater than five if true print this if

false don't do this do the else and if

that's a little confusing don't worry

about it for now it'll make sense to you

the more you do

this all right let's keep going let's

scroll down let's create a new coding

section and let's start our section on

Loops so let's let's say we wanted to

print out the word high a thousand times

it would be incredibly tedious to write

high high high high high high

high a thousand times is there a better

way and well there sure is in Python we

can do repetitive tasks with something

called loops and there are many

different types of Loops that we can use

the first one is going to be the while

loop so let's say we have a variable

called my number that starts at zero so

my number is set to zero we can then do

something like while my number is less

than three we do the little colon here

press enter and you'll notice once again

we're indented to know that we're inside

of this while loop we could say print my

number is plus Str Str my number and as

long as my number stays less than three

python will just keep looping and


running this now don't hit the play

button yet because python would

technically run into an infinite Loop

because my number would always be less

than three since my number is never

incremented so first we'll say print my

number is plus my number and then we'll

say my number equals my number + 1 and

this is how every single time we run

this Loop we add one to the number here

and then we'll print out done notice

again that this print done is outside of

the while loop because it's not indented

so if we hit play Here We scroll down

you'll see we get my number is zero my

number is one my number is two and then

done you see it stops because once my

number is set to three my number is no

longer strictly less than three and it

will execute so we can even kind of

visualize this a little better by saying

okay my number starts off as zero

then we enter the loop my number is zero

so it says while 0 is less than three 0

is less than three so it goes into the

loop print out my number is again it's

zero so it would print out zero and then

my number equals 0 + 1 so then my number

would be set to one so

while while one is less than three print


my number is one and then my number

equal = 1 + 1 which is now 2 so then my

number is then set to two and we would

read it as while 2 is less than three

which it is we would print out my number

is two my number equals 2 + 1 so my

number now equals three then we would

hit while three is less than three now

three is not less than three 3 is equal

to three so it will skip executing the

loop and just print out the done so

that's how you can think of walking

through these while Loops here and let's

just revert everything back and we'll

hit play and

boom now there's several different types

of Loops in Python the next one is going

to be the four Range Loop and this one's

a little bit more concise than this

while loop that we did up here so

instead we could say for each number in

range three print my number

is plus Str

Str my number and then print done this

four Range Loop says for every single

number in the range of three print out

my number is my number if we hit play

we'll

see whoops I have my number here and


this should be

number instead of my number because we

want it to be this in range three let's

go ahead and hit play again we now see

my number 0 1 2 so in range three says

from 0 to two which going to be 0 one

and two print out my number is plus the

number so we get 0 1 2 this is a much

more concise way of doing what we did

above here with this while loop for

number in rank

R and then finally let's look at the or

each Loop so let's say we have a list my

list equals 0 1

2 we could Loop through all the elements

in this list by saying for each element

or each item in my list

print my number

is plus Str Str element then print done

so it's going to Loop through every

single element in here and element will

be one of the elements in here so if we

print so if we hit play for this one we

scroll down we see my number is zero my

number is one my number is two if we

were to add maybe three four or 3 5 7

and then hit play scroll down we see the

35 and seven added to the print

statements here you can see how using

these Loops would be a really easy way


to print out High a thousand times we

could do something as simple as for

number in range 1,000 print this now I

recommend you don't do this because

you're going to get a massive cell that

gets outputed here you know what screw

it let's try it for number in range of

thousand let's go ahead and hit play if

we scroll down we see just a ton of

numbers some of this was even

truncated and we'd have to scroll for a

long time but you can see it's printing

out every single number between 0 and

999 so let's leave this as three so it's

a lot more digestible and let's continue

on with what we're

learning all right now it's time for

your final Workshop project of this

crash course this whate function

Workshop here's what we want you to do

to practice everything that you've

learned and you can use AI to help you

what I don't want you to do is just copy

paste this whole question into AI I want

you to try to do it without copy pasting

the prompt you can still ask Gemini

something like you know what is a

variable in Python in Python and stuff

like that but try to use AI as little as


possible and use the information you

have up here as much as possible what I

want you to do is create a function that

takes two inputs the first is a year and

the second is number of days and the

function should either print out y days

after January 1st X it will still be the

year X or Y days after January 1st X it

will be the year Z where X is the

starting year the first input to the

function y is the number of days the

second input to the function and Z is

the year after X number of days for

example if you were to do what year 1985

376 it would should print 376 days after

J January 1st 1985 would be the year

1986 because there are 365 days in the

year this is more than 365 days it's

going to be one year later but if you

did something with less than 365 days it

should print out 200 days after January

1st 1985 it will still be the year

1985 or if you were to do something like

what year 1985 1,98 it should print 1098

days after January 1st 1985 it will be

the year 1988 notice how still is only

added in this sentence when the year is

1985 even after the days are added

here's some assumptions assume a year is

365 days and if you're off by a day or


two that's okay it doesn't have to be

perfect don't worry about leap years

don't use the daytime package just

assume a year is 365 days to make it

very simple let me show you some

examples of what it should look like

when you're done and again the GitHub

repo associated with this course the

final solution will be available in this

completed code so that you can reference

what I did to what you did but for

example you should be able to do what

year 2000 and add 366 days execute the

cell and it'll print out 366 days after

January 1st 2000 it will be the year

2001 or if I were to do 50 in here hit

Play 50 days after January 1st 2000 it

will still be the year 2000 so this is

what you should be able to do at the end

of this so go ahead pause the course and

let's see what you can do creating this

whate

function all right so spoilers in here

ahead of me is what I have as the sample

solution to this we created our function

that took two parameters a start year

and days to calculate how many years had

passed we decided to use integer

division because it rounded down to


figure out exactly how many years had

passed to get that amount we did the

number of days sent in integer division

by 365 and to get the target year the

number of years later we just did the

start year which was the first parameter

plus years past then we did a

conditional where if years past was

greater than zero we said print days

after well we said days days after

January 1st start year it would be the

year Target year otherwise if years past

was still zero we would say print days

days after January 1st it will still be

the year Target year and this allowed us

to do all of the examples from our

prompt and if we ran this here we would

see 376 days after January 1st 1985 it

will be the year 1986 200 days after

January 1st 1985 it will still be the

year 1985 1,98 days after January 1st

1985 it will be the year

1988 and this was your crash course in

Python using Google collab now a lot of

people both data scientists and

portfolio managers or people who work at

hedge funds or asset managers they use

things like these python notebooks or

Google collab

in their professional work environment


now there was a lot in this course and

if you took the workshop if you were

able to come with this function if you

were able to come up with a solution

here give yourself a massive Round of

Applause and maybe get yourself some ice

cream and then go to the gym because you

should be incredibly proud of yourself

for getting this far it took me a long

time to learn how to code Python and

learning a lot of the basics here is

absolutely fantastic now there's a lot

more for us to learn coding on Google

collab or remix or any online IDE is

great however we can write way more

production professional code in our own

local environments so now is a great

time for you to take a break go get a

coffee go for a walk go to the gym and

I'll see you soon because what we're

going to do next is in my opinion the

hardest part of any Python tutorial and

honestly I feel like this is the part of

python tutorials that most Educators

gloss over the most because setting up

your python on environment on your local

computer can be incredibly challenging

so we're going to spend the time to make

sure we get you set up correct so that


you can be successful now I do actually

want you to take at least a 30-minute

break before going to this next section

because I want some of the information

here to settle in and guess what your

brain cannot process too much

information in a day it will do a worse

job of learning that information so

pause for at least a half an hour if

you've already been coding for a while

today pause for the whole day because

installing Python and getting your

environment set up correctly can take a

long time and if it does take a long

time don't be frustrated it took me a

long time the first time I got it set it

up but if you can get through installing

Python and installing your environment

the correct way you can do anything

because it's honestly the hardest part

of all of this so take a break and I'll

see you

soon now for the rest of this course and

the rest of this tutorial I'm going to

be working with this thing called Visual

Studio code you might also hear it

referred to as VSS code but it's Visual

Studio code and this is essentially what

it looks like and this is the website

for it and it's important to know that


Visual Studio code is very different

from Visual Studio or Visual Studio IDE

I know they all have almost the exact

same name I know they look very similar

but they're totally different Visual

Studio code is what we want to work with

not Visual Studio you can see the logos

are also kind of similar I don't know

who decided to do that from their end

but you know I digress now if you choose

so and you're a total Hardo you can do

everything in this course in a raw

terminal that works great and I know a

lot of people like to use something like

a Google collab however for this I'm

going to recommend you don't work with a

notebook because for developing our

smart contracts the notebooks are much

less reproducible and are phenomenal for

kind of testing and tinkering but not as

great for building uction environments

and I want to teach you how to be a

professional and of course if you're

working with Adam or sublime or some

other code editor you can absolutely do

so in the next couple of sections I'm

going to go through setting up vs code

the way that I like it set up however

you can of course set it up however you


like but the reason I'm going to show

you the way that I'm going to set it up

is because I think it's going to make

your development experience a lot easier

and I'm going to show you a lot of the

pitfalls if you set it up wrong and

additionally we'll work with AI to debug

any issues that we run into now to get

set up we're actually going to go

through three three different

installation processes the first one is

going to be for Mac OS and Linux

environments most Professionals in both

blockchain and pretty much any other

industry in the world works on a Linux

like environment Macos by default is

Linux like Windows users have a very

different environment and so we're

actually going to teach you how to

download and install things in a very

different way and then finally I'll show

you the GitHub code spaces or the gitpod

setup however I highly recommend you

don't use git pod or code spaces as you

can very quickly run out of your free

trial of those applications and this is

blockchain you don't really want to be

sharing your secrets or your private

keys with those anyways so we're going

to go through three ways of setting this


up Linux slmc Ox number one Windows

number two and then git pod Cod paste

and then get pod SLC Cod spaces for

number three however I recommend you

don't do number three

the first thing you're going to want to

do is download the Mac or if you're

working with Linux download the Linux

installation of Visual Studio code once

you have it installed it'll look a

little something like this and if it's a

fresh installation it'll even give you

some tips and tools to actually get

started if you've never worked with

Visual Studio code before I highly

recommend going through any get started

or getting instructions tips that come

with opening Visual Studio code

additionally we have a visual Studio

code crash course in the GitHub repo

associated with this

course hello my name is basili and I'm

going to be your instructor for

everything related to development on

Windows installing developer

dependencies on Windows is a little bit

tricky and sometimes really messy that's

why we are going to install a tool

called WSL or the windows subsystem for


Linux on the upcoming videos I'm going

to be really straightforward on how to

install the tools we are going to use

for the rest of the lessons however if

you want to actually understand what WSL

is how it works the basic command line

tools and a lot more please be sure to

check our 100% free crash course about

WL for smart contract developers we

published on YouTube with that said

let's get that Windows environment ready

for

development Microsoft has definitely

increased their support for developers

in the recent years but when it comes to

Smart Control development there is a

better option to consider using WSL the

windows subsystem for Linux trust me is

a game changer you see smart contract

development often involves working with

tools and utilities that are commonly

found on Unix based environments while

Windows has come a long way in

accommodating developers there can still

be some challenges when it comes to

Runing certain command line tools and

setting up the right development

environment not mentioning that if you

want your code to on any machine using a

units based system Mac and Linux is


better for your developer needs here is

where WSL shines by installing a Linux

distribution through WSL you can access

to a full-fledged Unix like console

right on your Windows machine and don't

worry you don't need to be a hacker or

wear a hoodie to make it happen is

actually quite simple so let's do it

let's get started with the installation

process first we need to install WSL

using the windows terminal in Windows 11

you can just hit the Windows key and

type terminal hit enter and this will

open the windows terminal for you which

defaults to PO shell however if you are

using Windows 10 you are going to need

to install the windows terminal through

the Microsoft store so you can open the

Microsoft store look for Windows

terminal and please be sure to select

the one from Microsoft Corporation once

you have it please open it and

installing W cell is going to be a

really straightforward process and on

the terminal we are just going to type

WSL D- install this is going to trigger

some admin level operations as you are

going to see on the screen right now you

just select yes hit enter and once the


installation process is finished it this

will require you to restart your your

computer once you reboot your computer

this is going to automatically trigger

this window to continue the installation

so let me actually make this big for you

to see and the first thing we need to do

here is to select our Unix username I'm

going to select chare hit enter and then

we are going to be required to set up a

new password something interesting on

most of Linux operating systems slash

distros is that when you're using the

terminal if you type anything over here

the password is going to remain hidden

that doesn't mean that you're not typing

anything but the terminal is not going

to show anything over here unless you

use another Linux Dr for example Linux

mean otherwise most of the Linux

operating systems are going to keep this

always hidden

I'm going to type my password though and

then hit enter and as you can see here

the terminal recognizes that password

and ask me to type it again for

confirmation and once we finish this

that's it we have W cell installed on

our machine as you can see here the

installation finished it properly and we


can continue I'm going to actually close

this for now

now that you have WSL set up you can go

to the search bar and look up BTU you'll

see either you BTU on Windows or

something like Linux or an app like this

and if you click it you start it up

you'll get dropped into a yuntu shell or

a yuntu application and it's in this

type of shell that we're actually going

to be doing work another way you can

open this up search bar you can look for

the terminal application and this is

what a lot of coding tutorials are going

to teach you how to use now the first

time you open it it actually might take

a long time because because your

computer booting up an entirely new

operating system different from your

Windows operating system and that might

take some time when you open up your

terminal it will default you into this

Windows Powershell this is not what

we're going to be using IF anytime you

see a Powershell like terminal that

should be your key

to know that we should switch over to a

yuntu or a WSL or a Linux like terminal

in Powershell you actually select the


drop down here and switch over to yuntu

in a new tab and it'll give you that

same yuntu setup now you can work

directly off of your Linux slabon setup

but we're actually going to be doing

most of our work directly inside of the

app Visual Studio code there are a

number of ways to install Visual Studio

code will let vasili teach you how to

install Visual Studio code because there

are multiple different ways that you can

get it

installed there are plenty of ways to

install Visual Studio code and I'm going

to show you three of those ways on this

video the first one is going to be using

the terminal as we are going to spend a

lot of time using the windows terminal

anyways we can install it with the

hacker SL programmer way for that we are

going to use winget which is a package

manager pre-install it on Windows 11 for

installing software you can also get

winget on Windows going directly to the

documentation so for example if I want

to install Visual Studio code using

winget I just use winget search vs code

this is going to show me all the

available packages to install Visual

Studio code so installing Visual Studio


code using this is going to be really

easy I'm just going to copy this and say

Wing get install and the package name I

just selected if I hit enter this is

going to start the installation of

Visual Studio code on my machine as you

can see this is opening the installation

for me and that's it this is how you

install or code editor from the terminal

and if I go to the main menu I already

have Visual Studio here installed the

second way to install Vis Studio code is

open your favorite web browser on the

search bar look for visual studio code

select the one from code. Vis studio.com

this is the official Microsoft one you

can click on download for Windows this

is going to automatically trigger the

download and open it this is going to

start the installation process and of

course we have the user and license

agreement mostly no one car about this

stuff and no one reads it but I highly

recommend you to spend a little bit

doing so as a good practice I'm going to

accept the agreement hit next this is

going to give us the path and the

installation is almost the same as we

did on the terminal way but in this case


is going to allow us to have more things

like this add open with code action to

Windows Explorer File context menu this

will allow us to do a right click here

and have the ability to open open any

folder using visual studio code I'm

going to also create a desktop icon hit

next and install on the meantime this is

installing I'm going to mention that if

you are concerned about Microsoft having

that much control over the data because

they own Visual Studio code they own

GitHub they own a lot more of tools and

you want a open-source version of Visual

Studio code that will lead us to the

Third Way which is BS codium BS codium

is an alternative to visual studio code

which is exactly the same but without

Microsoft Telemetry Gallery logo and Etc

so basically they take the basic Visual

Studio code buil remove all the

Microsoft Stu from it and change the

license to the MIT license so basically

if you are concerned about your privacy

or Microsoft having access to your data

BS codium is a really nice alternative

the installation is exactly the same you

hit on install St you download the

latest release this is going to lead you

to GitHub and select the one for Windows


in this case is going to be the one

marked as vscodium user setup do XA you

hit this this is going to trigger the

download and you're going to have the

package to be installed over here if you

open it this is going to allow you to

install vscodium but as this is not

signed by Microsoft Microsoft is going

to prevent to run this you click on more

info and run anyway this is going to

open the installation and the process is

going to be almost the same because at

the core they are the same code editor

and this is how you can install Visual

Studio code in three different ways

select the one you like for this

tutorial and for the rest of the course

I'm going to keep from the one coming

directly from Microsoft Visual Studio

code thanks vasili I'm going to go ahead

and install it directly from the website

now remember Visual Studio code is

actually very different from Visual

Studio Visual Studio is a completely

separate app even though I know they

have almost the exact same name we want

to use Visual Studio code I'm going to

download it directly from the website

for my Windows application going to go


ahead and hit save I'm going to open it

up

now accept the agreement next next next

create a desktop icon add open with code

actions to the Windows Explorer next

install finish and let's go ahead and

launch Visual Studio

code now right away when you open up

visual studio code you actually might

even get prompted saying you have

Windows subsystem for Linux installed on

your system you want to install the

recommended WSL extension for Microsoft

for it and you can go ahead and hit inst

all now if you don't get prompted with

that you can also go to this extensions

bit the left hand side here and look

up

WSL in the extensions and we want to

install WSL here for visual studio code

WSL make sure you see the little blue

check mark to make sure that this

extension is coming from microsoft.com

let's go ahead and hit install now that

we have this installed we can actually

reopen up our Visual Studio code with a

Linux or a Ubuntu terminal built

directly into the visual studio code I'm

going to go ahead and hit X here what I

can do is I can hit these three little


drop downs and go to terminal select new

terminal now what's going to pop up is

very similar to our terminal application

going to pop up in the Powershell

terminal here similar to what we did in

the Powershell application we can hit

this little drop down and switch to a

yuntu WSL terminal instead again this

will take some time for it to actually

start loading up if I type CD in the

command line it'll bring me to What's

called the home directory additionally

at the bottom left you'll see this

little open a remote window section we

click on that you can also select

connect to WSL instead which will open

up our vs code directly in a WSL yuntu

setup now when I select the dots and go

to terminal new terminal it'll open us

directly up in a Linux like or yuntu

like terminal instead of Powershell so

your cue moving forward is at any time

we're working with Visual Studio code on

your windows you should see this WSL

yuntu in the bottom left because we're

always going to be working with yuntu or

WSL or this Linux like environment and

not the Windows like environment if we

close out of Visual Studio code and then


we reopen up in Visual Studio code we'll

see in the bottom left that it's

actually going to open back up in yuntu

and if we click

here and we close the remote connection

you'll see the WL Ubuntu goes away we

close Visual Studio code and then reopen

it you'll see it's still gone so we want

to open it back up connect to WSL and

now we're connected back in in the WSL

environment let's open up our terminal

and there's a shortcut with control

shift back tick if you want to use that

as well and boom we're back in our our

Linux like or our WSL like environment

the rest of the course as I just said

this is the environment we're going to

be working with and anytime you work

with terminal commands use the Linux or

WSL or yuntu like terminal commands

don't use the windows ones anytime

you're typing in a vuntu or Linux shell

and a website says hey here's the Linux

command here's the Windows command if

you're in this type of shell if you're

in this type of terminal use the Linux

commands now one of the awesome things

about Visual Studio code is it has this

thing called terminals which are

commandline prompts that allow us to run


scripts basically it's where we're going

to be running all of our code the way we

can open up the terminal is we can go

ahead and hit terminal and select new

terminal you'll get something like this

now you might have bash or zch or some

other type of shell the type that you

have doesn't really matter because on

Mac and Linux it's going to be Linux

based and like I said sometimes

installing this can be the hardest part

of this entire course so so don't get

discouraged and please use stack

overflow stack exchange ethereum and the

GitHub repo to move past any issues you

run into now if you're on Mac or Linux

you can actually hit control back tick

to actually toggle your terminal mode

this will pull the ter terminal up and

down for you getting familiar with

keyboard shortcuts will actually make

your life a lot easier cuz you'll be

able to move around Visual Studio code

much more effectively we have a link to

a list of keyboard shortcuts

additionally in the GitHub repository

associated with this section as we move

along I'll give tip on different

keyboard shortcuts that you can


optionally use otherwise you can just go

ahead and click as well you can click

the trash can to delete the terminal go

back up terminal new terminal to pop it

back up now the next thing that we're

going to need a little bit later we're

not going to need it for this section

but it's good to install it now is going

to be git we will have links to the

installation instructions in the GitHub

repository installing git on Linux

you're going to use one of these two

commands and on Mac OS if you just type

git on the command line it should go

ahead and prompt you to install it so if

we're back in our command line and we

just type get it should prompt you to go

ahead and install it and if you do get--

version you should get something that

looks like this you can also use a Mac

OS G installer by clicking this link

here and running through the

installation process all right now that

you have get and visual studio code

installed we can continue on to the next

section awesome if you're not planning

on using Windows or git pod feel free to

skip the next two

sections to install python on a Mac OS

system we're just going to go to the


python.org website and we're going to

download python directly from python.org

so on python.org go ahead to download

down and it should give you download for

Mac OS right here and we can hit Python

3.13 and we can hit the button to

download that version however before you

select that actual version scroll on

down and in the GitHub repo associated

with this course you'll see right at

this section one python crash course or

whatever section number it is you'll see

python version 3.11 so whatever version

is in the GitHub repo ass with this

course that's the version that we want

to go ahead and download here so to use

3.11 we'll go to downloads we'll go to

Mac OS and we'll look for 3.11 so now

that we're in the Mac OS download

section we'll scroll down and we'll look

for the latest python 311 that has a

universal installer so we can see here

there's no files for this release for

this version so we're not going to use

that but by the time you watch this

maybe there will be but we'll look for

3.11 we'll hit enter and it looks like

this version of python 3.11 has a Mac OS

installer and this installation version


supports both Apple silicon x86

sl64 versions so if you're like hey I

have apple silicon or an Intel chip

don't worry this should work universally

on both versions of Mac OS so we go

ahead and click this we'll go ahead and

Save which will be saved to our

downloads which we'll go ahead and we'll

open up into the python installer we'll

go ahead and continue we'll agree

install and it'll go ahead and install

this version of python great once it's

installed you might get a little popup

like this we can go ahead and close it

out it'll say congratulations Python and

then the version you installed has been

successfully installed we let's let's go

ahead and close this here and move to

trash now that python is installed we

can actually open up our vs code here

now remember to open up the terminal we

can either select terminal new terminal

or do control shift Tilda or do control

shift Tilda or do control shift

pilda which will open us a new terminal

here since we just installed and let's

go ahead and pull this to the top and

since we just installed python 3.11 we

can type in Python

3.11 and get dropped into a shell that


might look like this to exit this we can

type quit with an open and close

parentheses or you can always just close

and delete the terminal by hitting the

trash can and then open up a new

terminal to make sure you're on the

correct version you can do python 3.11

D- version and it looks like we're on

the correct version here now you might

also have python 3- version which is a

different python version as for me I'm

for me my Python 3 is updated to the

correct version you might also have

python D- version however as of

recording I do not have the python

keyword so if you have so one computer

can actually have multiple versions of

python installed at the same time and

this is where some of the the confusion

can come into play when working with

python this is why very soon we're going

to switch off of python and move over to

a tool called UV and a tool called

moccasin which are going to make our

lives a lot easier to work with these

different versions of

python now we're going to learn how to

install python in this WSL if you're on

a Windows machine or if you are on a


Linux machine just right on your Linux

machine now most of the time most sites

are going to ask you to go directly to

the python website and select download

the issue with this for those of you on

a Windows or a WSL environment is that

downloading directly from the website

will download this into your Windows

operating system we don't want to do

that because we are going to be working

in the Linux the WSL the abtu operating

system we want to download into our

Linux operating system

the same is actually true for any other

software application that you want to

run in your WSL environment you're going

to have to download it directly from the

command line as opposed to downloading

from some website with a click of a

button now if you're watching this on

YouTube there will be a link to the

GitHub repo associated with this you're

watching this on cyphon updraft of

course this will be in the course

materials section of the website we

scroll down on in here we scroll down to

where is it marus and fundamentals the

python on Crash Course section we just

finished the Google collab section just

set up Windows and WSL and vs code Etc


now we're going to be installing python

on Windows WSL or Linux or yuntu first

thing we want to do you want to do this

new

terminal terminal and again we want to

make sure we're on WSL Ubuntu if you're

on a Windows machine if you're on a

Linux machine you will automatically be

in this environment and to even make

sure you can do Echo Dollar Sign capital

s h l enter and if you get something

like bin bash or bin zsh or if you just

don't get an error that's a good sign if

you do get an error this is a great time

to take that error and drop it into an

AI like Claude for example say hey I I

ran into this error I'm trying to use my

VSS code in a WSL environment or I'm

trying to use my VSS code in a Linux

environment what's going on why am I

getting this we can type clear in the

terminal and hit enter to clear all the

lines if I have a whole bunch of lines

here and I'm like ah this is cluttering

up my space I can hit clear like that

and I can and I can scroll up this

terminal to make it bigger or smaller by

dragging on this horizontal bar here and

just make sure you're on this terminal


section here not debug output problems

ports blah blah blah Etc so to install

python now python has gone through

several revolutions and one of the

biggest ones happened several years

years ago where python moved from python

2 to Python 3 it was a groundbreaking

change and we want to check a couple of

things on our system first we want to

check if python is even installed check

if python is even installed we can type

which python like that and if we don't

get a response this means that python

the keyword python is not installed we

can also type which Python 3 see if

Python 3 is installed it looks like on

my computer here pyth py 3 is installed

now for those of you who did follow the

WSL instructions Python 3 will be

installed by default with your yuntu

installation now if you don't have

Python 3 installed don't worry we're

going to teach you how to install it but

if you do have Python 3 installed you

can type python 3-- version see what

version is installed most ubu

installations come with python 3.8 now a

lot of this python versioning stuff can

be very confusing and we're actually

going to fix and make it way way easier


for you later on in the course when we

introduce the tool called UV but for now

for this section we know that a lot of

other python tutorials are going to

teach you how to install it directly

which we think is a little bit confusing

but we want to at least walk you through

those steps as well so that you can see

what the differences are when we move

over to UV if you don't have Python 3

installed that's okay because what we're

going to be showing you now is going to

inst a completely different version of

python anyways so let's minimize vs code

and let's go ahead and let's run these

commands to install a specific version

of python as of today we're going to be

working with python 311 so first let's

just go ahead and copy paste some of

these lines sudo app get update this

will update our packages and remember it

might be a good idea to even ask your AI

assistant as you write some of these

commands hey what do these do

understanding these commands will help

you be a better programmer in the future

so if I say hey like what does pseudo

appet update do CLA gives me a great

explanation again Claude version 3.5 is


currently my recommended AI you'll get

the pseudo appit update command

refreshes your system's package index

let me explain what that does and it

tells you a lot about what it does so

let's go ahead and let's paste this into

our terminal here and obviously we'll

get prompted for our password we get

prompted for our password because we're

using the pseudo command pseudo command

stands for super user do apt get update

means just update our package

and it's going to update all of our

packages so that we can that we make

sure we have the most up-to-date

versions then we're going to do sud sudo

apt get install software properties

common this is going to install one of

these Linux packages on our machines

great looks like I've already got it

installed here then we're going to do

pseudo apit repository PPA dead snakes

slpa again if you're like what is going

on here CLA V3 3.5 is great at

understanding this or most AIS are great

at understanding this and it says this

command adds a personal package archive

to your system specifically the dead

snakes PPA which is a popular repository

for python versions this is basically


how we're going to get different python

versions onto our environment so let's

go ahead let's paste that in here and

let's hit enter you'll notice that we

don't have to type in our password again

because our terminal remembers that we

just recently added our password let's

go ahead and hit enter to continue and

it's going to go ahead and install this

in our Linux environment next we'll do a

pseudo appkit update again just to make

sure everything is up to date and we're

up to date here and then finally we're

going to now be able to install a very

specific version of python I'm going to

run Pudo app get install python 311 now

if as recording we're going to use 3.11

but whatever version the code says to

use we'll go a and use that and we'll

paste in PSE sudo appg install Python

3.11 and hit enter now if we type in

Python 3-- version you have Python 3

already installed previously it'll still

show python

3.8 but if you type python 3.11 D-

version you'll see python

31110 to installing python 3.11 gave us

this command python 3.11 so we can now

do with
which paste python 3.11 which will show

us hey uh we do indeed have a python 311

in installed now for you Windows users

you have everything set up the way that

it's going to work in Cipher updraft and

this course now even though I just had

you go through all this work to download

python 311 or whatever version again is

in the GitHub repo associated with this

we're very quickly going to move away

from using python 3.11 in the terminal

like we're doing it here we're not going

to be using this python 3.11 very soon

we're going to move over to working with

UV and working with moccasin because

using those tools we're not going to

have to worry about python versioning

anymore there's a couple of really

annoying things with working with python

or to be honest even rust nodejs or

really any programming language is that

some features are only supported in

certain versions and some packages some

features of the language in some open

source packages or tools or libraries

some things about the languages are only

supported in certain versions so using

tools like moccasin and UV will allow us

to much much easier switch between

versions use tooling with versions in


the correct way and so on so for now

let's just do a quick recap because I

know there was a lot in here first off

number one if you're on Windows machine

in the bottom left you should see

running on yuntu it with this WSL yuntu

or whatever Linux version that you chose

in the terminal here if you hit this

little trash can and then you go back up

and you select terminal there is it new

terminal should enter you in this Linux

like terminal you can make sure you're

in a Linux like terminal by typing Echo

dollar sign shell and if you get an

output that looks like this and it

doesn't look like an error you are

probably in a Linux or a Ubuntu like

terminal now for you windows and Linux

users everything else in the rest of the

course is going to be pretty much

exactly the same here and it doesn't

matter if you're on a Windows a Linux or

a Mac as long as you have this terminal

here to the yuntu environment you're

going to be perfectly able to do

everything that everyone else is going

to use if you do run into an issue as

I've said many many times Googling

joining the discussions forum and using


AI will be incredibly helpful for you to

move forward

here so now we're opened up in vs code

if you're on a Mac OS or a Linux machine

the bottom left hand side should just

basically kind of look like this if

you're on a Windows machine the bottom

left should say like WSL or yuntu or a

combination of the two but now from here

on out all operating systems can run the

exact same commands whether or not your

Mac OS your windows or your Linux we're

always going to be using the Linux or

Mac OS like commands moving forward this

way the instructions will always work no

matter what again if we pull up our

terminals here and we type Echo dollar

sign shell it could say zsh it it could

say bash there's many different types of

shells out there that all work the same

doesn't matter which shell that you're

using because the commands that we're

going to run will all work no matter

what shell you're working with I've

mentioned this a couple of times but

just to reiterate often times my

terminal here will get kind of bogged

down with a lot of lines and what I'll

often do I'll often do to clear it is

I'll leave to type clear in the command


line to clear all those lines or I'll

type command k for Mac OS or this is

also control k for Linux or Windows so

the shortcuts are the only thing that

will be a little bit different depending

on if you're on Mac OS or Linux

Additionally the trash can and the X

here are actually very different the

trash can here means to delete the

terminal and anytime I say delete the

terminal that's usually what I'm

referring to if I just say like close

the terminal I often just mean hide the

terminal so if we were to do terminal

new terminal let's pop up a new terminal

and added a couple of lines here if I

were to hit the X here I'm actually just

going to hide it going to hide the

terminal but I could pull the terminal

back up now if I do terminal new

terminal you'll actually see that now I

have two terminals if we scroll up here

we can see that this other terminal is

the one with all the new lines and I

just created a new terminal here so I

can I can Trash one of the terminals and

that one is now deleted I can also

create a bunch of new terminals but

typically most of the time we want to


work with just one terminal there are

some scenarios where we want to work

with two now to toggle the terminal to

basically hide it and then pull it back

up you could do control Tilda on a Mac

OS on Windows or Linux it's going to be

Control Plus backtick so command

backtick for Mac OS Control Plus back

tick for Windows and Linux and this will

this is the same as hiding the terminal

and then doing hitting View and

selecting

terminal so again command backtick this

will toggle hiding and showing your

terminal you can also do view terminal

to hide it and then view terminal again

to show it and hiding it is equivalent

to pressing the x button here I'm on a

Mac OS and I also use command j a lot

but that keyboard shortcut might not be

the same for everybody now this is very

different from the trash can icon here

if I hit enter a whole bunch of times

and then I go ahead and do trash can and

then I toggle or reshow the ter

you'll notice that those new lines are

no longer there whereas if I do a bunch

of new lines hide the terminal and then

bring the terminal back up those new

lines are still here this trash can


means to delete and remove everything in

the terminal or kill the terminal

whereas the x is just to hide it now

let's get started setting up your Visual

Studio code so that it's going to be

very easy for you to all your files and

projects that are related to this course

in a single folder so let's go ahead

ahead and let's open up a new terminal

again with control or command Tilda or

command J or view terminal or terminal

new terminal or whichever command that

is most applicable to you now a number

of the commands that we're going to be

running are known as Linux commands and

they work on zsh they work on bash they

work on pretty much any shell that comes

with Linux or Mac OS or if you're on

Windows Windows WSL you can see what

directory you're in by typing PWD this

will show you which folder that you're

inside of when I typed PWD here I'm

inside of users Patrick I'm in the

Patrick folder this is known as your

home directory if you type CD which

stands for change directory you will

change directory to your home directory

this little Tilda stands for the home

directory I could also type CD CD Tilda


hit enter and then type pwe again and

you can see I'm in the exact same

directory it's cuz I changed directory

to my home directory here for all the

cyphon updraft course I recommend you

making a brand new folder specifically

to hold all of your files and folders

for this curriculum so let's create a

new folder

mkd mkd stands for make directory which

is a command to make a brand new folder

we'll do mkd and we'll give our folder a

name I'm going to call mine

mo-cu which stands for moccasin cyphon

updraft but you can call it whatever you

want it to be if you want to be a little

bit more specific you could say viper

course you could say updraft python

whatever you want to type in here so I'm

going to say MOX CU and then we can do

CD MOX DCU which stands for change

directory MOX cyphon updraft and now you

can see right here my terminal tells me

that I'm in the MOX CU folder depending

on which shell you're working with you

might see something else here but this

is currently what I see if I type PWD

you can now see I'm in the users

Patrick's MOX CU folder if you're on a

Mac OS and yes sorry this is a Mac OS


specific command I can type open Period

and this will open up that folder inside

of my finder I don't have any files in

there so obviously it's empty and I know

I said every command is going to work

the exact same no matter if you're on

Mac or Windows or Linux but there's

actually some slightly different

commands for Windows and for Linux here

for Windows users a similar command is

explorer.exe period which should open

you up in the Windows Explorer for Linux

it's going to be xdg hyphen open Period

which will open you up in the Linux

folder for Linux users you might not

have this installed by default and you

might have to do pseudo app get install

xtg utils to install this but again if

you don't have this command it's not

really that important now this folder

here remember let's type PWD this folder

here is where we're going toore store

all of our different projects and this

is where we're going to build up our

resume and build up our learnings to

become successful smart contract

developers now what's especially cool

about vs code here is that we can do

file open folder and choose our folder


that we just created this mock cuu or

whatever you named it select open and

we'll actually open up a new vs code

where the default directory is this

folder if I select terminal new teral

now or use the shortcut and I'm going to

hide in my Explorer by pressing this

little button here if I do PWD now I can

see I'm directly in this MOX CU and if I

hit the trash can terminal new terminal

or the keyboard shortcut and then type

PWD again I'm still inside of this

folder another shortcut that we can do

and if you haven't installed it that's

okay you can always do file open folder

like what we just showed but you can

also do code period

and this will also open up a new window

inside of this folder here file open

folder and then select the folder you

want to open or code period if you're in

the folder that you want to open up once

you are inside of the folder this button

over to the left here is known as the

Explorer and it will show you all of the

folders on the left hand side if I were

to right click and hit new file and do

something like hi. txt I now can see

this high. txt on the left hand side in

my terminal if I type LS which stands


for list I will list all the files and

folders inside of this folder and I can

see there's just currently this high.

txt if I were to create another file

with doing right click and then new file

again called hi 2.txt and now in my

terminal I do LS I can see high. txt and

hi 2.txt going to delete this what's

cool is I can even edit these files

directly in my vs code some stuff here

now what's important to note is that if

you see a little dot up here this means

this file is unsaved so to save we want

to hit file save and you see the dot

goes away which means it's saved this is

incredibly important because if you

forget to save stuff and you try to run

commands they won't work so I always use

the keyboard shortcut which on a Mac OS

is command s and for Windows and Linux

it is controls so type some stuff see

this little dot here command s Boom the

dot has gone away and now it is saved

and now I can flip back and forth

between my files and know that they are

being

saved unsaved saved unsaved saved

unsaved saved it's really important for

you to recognize that because often


times you're going to run a command

you're going to be furious that it's not

working and you just forgot to hit save

so I have a trigger finger after years

of programming where I just always hit

command s or controls on my keyboard all

the time so you'll see me run commands

and almost by force of habit I have

already saved the file because anytime I

pause to think for a second I've already

hit save you could also delete any files

in your folder directly from your vs

code by right clicking a file selecting

delete are you sure you want to delete

let's move to trash then we could toggle

our terminal again type LS and we can

see that file is no longer in the folder

and of course we can see it over here

final thing that we want to install and

we'll install a lot of these as we go

along is actually an AI EX extension

something in vs code to help us actually

have ai inside of our Visual Studio code

if you select this little box looking

thing that says extensions you get a

search box which allows you to search

for extensions the AI that I work with

the most is GitHub co-pilot but you can

use whatever AI you want or you could

just not even use an AI GitHub co-pilot


does cost money to use so feel free to

also not use it there's some other free

vs code extensions that use AI so feel

free to browse around and choose which

one you like for me I'm going to go

ahead and install GitHub co-pilot you'll

get a little guy in the bottom right for

your vs code that will let you know that

you've done it correctly you'll need to

sign into GitHub which is something that

we've recently made in order for it to

work you might also want to install

GitHub copilot chat this will give us a

chat box for GitHub copilot where if we

click the little GI up copilot icon we

hit GI up copilot chat we get a little

chat box similar to Claude or cwbt right

in our vs code now you'll see me using

GitHub co-pilot pretty often when I

write my code because I have this little

doad on down here I can start writing

some code and GitHub co-pilot will start

giving me suggestions as to what I

should write for example if I were to

add

spdx by sense identifier get a copilot

actually automatically starts to gray

out and give me a suggestion if I hit

tab I can autocomplete my code with


co-pilot suggestion you can go ahead and

click the little doad go to GitHub

co-pilot chat as well and you'll have a

chat box very similar to something like

chat gbt or Claude or whatever you can

also choose the different model by

hitting this little drop down and I know

mine kind of Pops off the screen here

but you can see there are different

models that you can use get up co-pilot

does cost money to use so please use the

AI of choice that you prefer to work

with so at this point you'll have

everything set up to start going if

you've chosen to add get up cop pilot

let me zoom out a little bit down in the

extensions section you will see a GitHub

Co pilot and this will be you'll see a

little disable button because it's

currently enabled you can click on the

little GitHub co-pilot to get a bunch of

commands to run with GitHub copilot we

will be in our MOX CU folder which

you'll be able to see at the top here

and if we hit our little file explorer

here we can see all the different files

in here we can toggle up our terminal by

hitting control Tilda which will pop us

into our terminals here now I'm always

trying to be positive to myself myself


so my terminal always tells me to make

it a great day but your terminals will

probably a little bit more neutral in

tone than

mine you should have python 3.11 in your

terminal and you can make sure you have

it by doing python 3.11 D- version so

now that we have this all set up we're

finally going to do some python coding

in our project here and we're going to

be showing you how we do python in

cyphon updraft and how we work with

python in cyphon updraft later on we're

going to be teaching you how to work

with moccasin but first we're going to

be doing raw some raw python because the

raw python will teach you what's going

on under the hood of this tool moccasin

that we're going to learn later on so

we're going to get started with python

we're very soon going to move to using

this tool called UV but you're all set

up so let's finally jump into doing some

Python and the reason I spent so much

time getting this set up for you and the

reason we spent so much time installing

and blah blah blah is because being in

the middle of a project and then

something not working the way you'd


expect is one of the most infuriating

things a developer has ever gone through

and as a developer and a software

engineer that is something that will

happen to you AI tools like Claude and

chat BT and GI up co-pilot directly in

your vs code will make debuging these a

lot easier but I spent so much time so

that we greatly lower the chance of us

running into those problems and

additionally we spent all this time

getting this set up because this is how

professional smart contract developers

and professional python developers work

making sure your environment

is as close to production as possible

will ensure you write the highest

quality code and unlike a lot of other

python tutorials out here I'm not here

to show you something that isn't what

professionals use I'm here to get you

career ready to get you to becoming a

powerful force for the blockchain and

the python Community I'm here to set you

up so that when you leave Cipher updraft

when you stop watching these videos or

reading these blogs or stop learning on

this platform you get out there and you

just start cooking going to make you a

chef of the software engineering person


asion and teaching you all the badass

stuff right from the GetGo is how we're

going to get there we are going to do

all of our practice in a real coding

environment because that way you will

get comfortable in this real coding

environment with all the obstacles that

come with it we teach you how to do real

stuff real projects real workshops so

that you can get out there and go oh

yeah I already know how to do this we

learned this in cphon updraft now one

more thing I want you to do and I know I

just said we would actually get started

coding right now but one more thing I

want you to do before we get started

coding go into your file explorer let's

go ahead and delete this high. txt

delete type in PWD make sure you are in

your folder that's going to hold all

your projects for this moccasin for this

Viper for this python course and I want

you to create a new file called

readme.md MD is the extension for

markdown and the readme file is a

classic file that pretty much all coding

projects will have that explains to

people what this project is is about and

what it does we're going to create a


readme for your Learning Journey and in

this readme.md I want you to write and

answer these questions first off why am

I learning Viper and python next what do

I want to do or be when I finish this

course and then finally what are the

steps I'm going to take to get there the

reason this is so important and the

reason I want you to do this is because

in the future what's going to happen is

you're going to come across things that

are difficult

I'm not going to Plate you and say

software engineering is incredibly easy

there are many days where I'm banging my

head up against the wall when I'm asking

my AI assistant how to fix something and

it keeps giving me solutions that aren't

working and I get frustrated so in those

times of frustration you can come back

and you can go is this all worth it why

am I doing this now the reason that

you're learning Viper and python is

going to be different from people to

people and it's Unique to you maybe you

want to just be part of the blockchain

movement and be part of this amazing

system of no centralized intermediaries

non-custodial Finance the future of

money maybe you're just saying you know


what Patrick I just want to get a job

and I want to make a lot of money and I

want to be a force for good maybe you

just want to learn new skill maybe you

want to be able to build your own

products become an algorithmic Trader

whatever the rationale is for you write

it down here and be honest don't plate

yourself if you're like hey honestly I

just want a job so I can buy a Lambo put

that in here be hon honest with yourself

next what do you want to do SLB when you

finish this course what is it going to

feel like when you're done do you want

to be a software engineer a security

researcher a technical CEO a technical

BD what do you want to do what do you

want to feel like when you're finished

with this course and then finally what

are the steps you're going to take there

this is a long course there's a lot of

code here there's a lot of things for

you to learn before you're good enough

to go off on your own so what is what

are the steps you're going to take to do

there maybe it's 30 minutes maybe it's

30 minutes a day for 4 days a week of

cyon updraft maybe it's 1 hour a day or

every day maybe you only have two hours


on Saturday whatever you're going to do

try to come up with a Cadence and stick

to it and if you get frustrated because

you're not hitting your pacing that you

set it's okay you can change the steps

in here maybe you come back and you go

you know what 2 hours a day on Saturday

was too hard I'm just going to do 1 hour

a day 1 hour a day on Saturday 7 days a

week was too much for me I'm going to

move it down to 3 days a week whatever

the pacing works for you try to come up

with a pacing schedule and stick to it

because that is going to be how you're

going to be the most successful here so

right up this readme.md this will be

your Manifesto that you can fall back to

when things get hard and don't share

this with anybody studies show that when

you share your goals with people who

aren't going to keep you accountable you

actually lose some motivation you've

probably told somebody before hey I'm

going to go out and do this and they go

wow what a great goal them telling you

you w with a great goal actually saps

some of your motivation you're getting a

reward for not even having done anything

yet they're saying wow that's so

exciting and you might say to yourself


wow you know what this is a great goal I

feel pretty good about yourself myself

but you don't want that to happen

because you haven't done anything yet

you should celebrate and you should

share the small wins but goal setting is

not a win so set these goals here set

them for yourself keep them private to

you and be honest with yourself all

right now that we have this out of the

way now let's finally begin coding and

let's start this phenomenal Journey that

you're being set

on all right so you're in your MOX

cyphon updraft folder and if you hit LS

you probably just have this readme.md

file in here let's go ahead and let's

create our first project folder and this

is going to be our Python and updraft

folder we very recently we did all this

work in Google collab where we learned a

lot of the basics of python and and if

you followed along with the Viper Basics

we learned a ton about Viper as well so

what we're going to do now is we're

going to start do using some of this

python in a more professional

environment so I want you to create a

new directory MK mkd python in updraft


updraft CU or you can do or if you want

to keep these in order you can also do

one- Python and updraft CU to number it

but whatever you want to do then hit

enter and if you do an LS now we now

have a file and a folder and if you go

to the Explorer we have a folder looks

like this and a file and now we can do

CD python CD python in updraft updraft

DCU now before you hit enter a quick

little tip is if you type is if you

start typing the folder name python in

and then hit tab it will probably

autocomplete the folder name and then

you can just hit enter and now if you do

PWD you can see we're inside of this

folder now I want you to open this up in

its own folder you can do that by either

type in code period if you've installed

this functionality or you can do file

open folder and then choose the python

and updraft CU folder I'll hit enter and

we're given a new window where if we

pull up our terminal here let me zoom in

a bit and we type PWD we can see we're

automatically stuck into this folder

now if you're following along with the

course at this point you have python

3.11 installed and one of the quickest

ways to try stuff out in Python is to


enter What's called the python shell or

the python console where we can just

write anything we want to get started in

there we can just do python 3.11 hit

enter and this will drop us into a

python shell this is actually very

similar to the Google collab that we did

before we could type print

high and we'll print out High we could

type my VAR equals 7 hit enter and then

nothing happens and now if we type print

my VAR it'll print out seven so this is

where we can kind of quickly test and

work with different python things now if

I hit type quit and I exit the shell and

then I type python 3.11 again we reenter

the shell but if I try to do print myar

now print myar I'll get an error my VAR

is not defined every time you quit your

shell it does not save what was in the

past shell so I'm going to go ahead and

delete the terminal pull up a new

terminal and again if I do python 3.11

one more time I still can't to print my

print my bar it still gives me an error

so delete the terminal pull up the

terminal and that's how you can enter

and exit a python shell

vs code is really powerful though and


one of the things we can do if we want

to we can create an environment very

similar to this Google collab

environment in here what we can do is in

the left hand side here is we can create

a new file called

cells. y andb andb like this now if you

click on this cells. iy andb you get a

pretty similar setup to what we saw back

over here in Google collab and in fact

we we can even Select Plus Code and do

some print high in here and we'll be

able to run this very similar to Google

collab now it won't run right away if we

hit the play button here or you type in

shift enter to try to run the cell it'll

give you a little popup saying install

SL enable suggested extensions python

Plus jupyter or browse Marketplace for

kernel extensions let's go ahead and

let's delete this don't click that quite

yet you know although if you do that's

also fine our ipy andb file in VSS code

needs a vs code extension for us to be

able to run these so if we select the

three dots and go to extensions or you

know just click the extensions button on

the left hand side here we can look for

jup ytr and look for this jupyter

notebook extension to help us work with


these notebooks and we'll go ahead and

install this one and then additionally

we're going to want to install the

python extension so we'll type in Python

we'll select this and we'll install this

as well this python extension will give

us a lot of really helpful tools

including including syntax highlighting

formatting and a lot more other stuff

you can see all the different extensions

that you have installed in the installed

section here I've got a number of

different extensions and the Jupiter

extension comes with even more

extensions as well now back over in here

if I hit plus one more time it still

won't run because I need to select a

kernel source I'm I'm going to go ahead

and hit python environments and you'll

see a couple of different environments

here depending on how you installed

python I'm going to work with this

3.1.9 because this is the python version

that I went ahead and installed recently

for us so I'm going to go ahead and

choose this and now you can even see we

get some syntax highlighting here

because now we have a kernel and we have

the python extension and then finally if


you get a popup like this which you

probably shouldn't but you can go ahead

and hit install to install this other

IPI kernel extension for your vs code as

well and now finally we can see the

output high in here we can additionally

do other basic python stuff like my VAR

equals 8 shift enter to run the cell and

then we can do something like print

print my VAR my VAR save shift enter and

we print myar and even down here we can

do print my VAR save shift enter and

it'll still print eight we can have

these Google collab type notebooks also

known as Jupiter or I python notebooks

directly in our vs code and if you want

in the GitHub repo associated with this

course if you want to play with it the

entire cyphon updraft ipy andb notebook

that we used in Google collab is

available for you to download in the

GitHub repo Python and updraft cyphon

updraft so great so now we know how to

work with the Sal . iynb let's now

create our first basic python file that

is how professional software Engineers

work with python so Google collab and

these notebooks are great for testing

and tinkering and learning and and

working with stuff and the like but


they're not great for professional

environments because similar to remix if

I wanted to test something and I had to

do like shift enter or execute all these

cells at the same time it can be very

disjointed it can be very annoying and

this isn't how professional project work

what they do instead is they create

python files to run and execute so for

example I'm going to create a new file

called basic python. piy thep file

extension is how vs code and other

python tools know that this is a python

file in here we can type and run kind of

the basic python stuff again I can do

print high in here remember this little

white dot means it's not save hit

command s to save it and then I could

hit this little Plus button that comes

with this and it'll run my python file

with this high now there's a whole bunch

of other stuff that it'll do and so this

is kind of like a cheat sheet shortcut

and this is something that you can use

to run your python files however we're

going to discourage that use for a lot

of reasons instead in your terminal if

you do LS you can see we have this basic

python. piy we're going to write python


3.11 basic python. piy let me zoom out a

little bit here so you can see the whole

line python 3.11 basic python. piy and

hit enter and we'll see it prints out

high so this is how we can execute an

entire file of python like

so now another thing that you can do in

Python is you can install packages and

libraries very easily we go online to

the Titanoboa GitHub repository we can

see this python package called Titanoboa

which is a python tool for interacting

directly with Viper if you scroll down

to the installation you can see how to

install this python package directly

into your environment pip install

titanoboa now we're actually going to

use pip not very often and depending on

how you installed your python you

actually might not even have Pip

installed at all if you type which pip

and you get PIP not found you don't have

it installed but you kind of secretly do

have it installed because we did install

python 311 what you can do to work with

Pip is you could type python 3.11 DM pip

and then you can do any pip command so

we could do das Das version and we could

see the PIP version right here so let's

go ahead and clear to install this


titanoboa package into our global

environment we could

do

python 3.11 DM pip install

titanoboa hit enter and this will

install titanoboa into our Global python

3.11 libraries I'm going to go ahead and

type clear in here and we can actually

see a list of all the different packages

we've have installed by typing python

31- M pip freeze hitting enter and we'll

get printed out a list of all these

different packages that have been

installed in our python environment

depending on how python got installed

you might a ton you might have very few

but we will at least have titanoboa if

we scroll down in here we should see

titanoboa right like this and it might

be a different version than what you see

here but all good so we've installed the

Titanoboa package into our Global python

environment now that we have titano

installed we can actually run commands

using this package in our python so one

of the things you can do with titanoboa

is you can actually evaluate Viper

directly in Titanoboa

work with a python package we would type


import and then the package name which I

know the package name here is titano BOA

but to import the titano boa package we

actually do import boa instead of import

titano boa you see a little hello world

here this is actually exactly what we're

going to follow we would type import boa

and then to evaluate some Viper we can

do print boa do

eval empty U into

256 so empty un 256 is actually some

valid Viper and this is the way to

create an empty un 256 object AKA Zer so

if we print bo. evaluate this Viper code

it should print zero because empty U 256

is Viper's way of getting us zero so now

if we pull up our terminal let me kind

of minimize it here let's clear it out

and we do python 3.11 basic python. piy

we'll see it takes a second to run but

it'll print out zero for

us now we're going to give you a lot of

information about python versioning

virtual environments and all this other

stuff and if this all doesn't syn in

with you right away don't worry it's not

critical to your Learning Journey that

this all gets absorbed right away as we

code more and more you're going to get

better and better and working with


python and working with different

tooling and I'm going to be giving you

tips and tricks along the way throughout

your Journey here AIS are great at

helping debug and for the moment it's

just best to follow along with the

commands that I'm going to give you so

that you get used to typing them and

coding them as you code along with us

now one of the issues that can happen

behind the scenes is that titanoboa

could have some features that only work

with certain versions of python maybe

for some reason we run python 3.11 basic

Python dopy and we get some crazy error

and we're not really sure what's going

on this is because certain packages

might work with only certain versions of

python and this can be incredibly

frustrating to be on the wrong version

of python and then have to go through

that whole process of installing the

other version of python and then we have

like 18 versions of python like python

3.12 3.13 python 3.5 3.6 blah blah blah

and that can get really annoying

additionally titano boa can have

different versions our python packages

can have different versions so we could


have a different version of python that

only works for certain versions of the

package and a different version of

package that only works a certain

version of and it gets even more

complicated when you have multiple

packages that only work with certain

versions of other packages and this can

be kind of a nightmare so this is why

for the duration of this course we're

going to be working with this tool

called UV is an extremely fast python

package and project manager written in

Rust it's incredibly fast and it's

incredibly modern and I'm so excited to

be showing it to you now before you run

into all the headaches that other

tutorials don't teach you UV will help

maintain both our python versions and

our library versions so we pretty much

never have to deal with that headache

again you maybe you already dealt with

it now maybe you've never dealt with it

but it will deal with all that

additionally when we get to Virtual

environments which will come very soon

UV will deal with all the virtual

environment work as well so let's go

ahead let's install UV and then we're

going to show you how to work with UV


how to work with virtual environments so

that whenever we create projects in in

Python they're incredibly professional

easy to reproduce so that anybody can

work with it so if we're in the UV

documentation let's scroll down to the

getting started section to install UV

and again there's a link to this in the

GitHub repo associated with this course

for those of you on Windows WSL you're

not going to use this command you're

going to use the Mac OS and Linux

command in your WSL Ubuntu environment

and then obviously for Mac OS and Linux

users you're going to go ahead and

additionally use this command so we'll

go ahead and copy this line H back over

to our terminals our vs code I'm going

to zoom out just a little bit going to

pull this to the top and we're going to

paste this in here this is going to

install the UV and uvx commands onto our

computer once you have it installed you

can go ahead and delete your terminal

and pull your terminal back up and type

which UV to make sure it was installed

correctly and you can type uv-- version

to see the current version of UV that

you're working with now that we have UV


installed what we do is create a new

professional python project using UV

andit and we'll see initialize project

python in Cypher updraft CU and you'll

see a whole bunch of new files on the

left hand side here let's go through

what some of these files have done and

let's go through why this is green here

first off we have a git ignore this is a

file specifically for working with Git

and with GitHub and we'll learn about

git and GitHub much later we have this

python version file which literally

tells other developers and and other

tools what version is recommended for

working with this tool this is kind of

optional and sometimes you'll see a lot

of projects delete it or not have it we

obviously have our two files that we

created we're given a hello.py which has

this very weird syntax which we'll

understand in a minute and we'll get

this P project. tml here now this p

project. toml is an incredibly important

file whenever we're creating packages

whenever we're creating python projects

it's this py project. that will tell the

world and python projects how to

interact with our python project here

and then of course we have our readme.md


which every single one of your projects

should come with uh you may also see

this little main section here and we'll

explain that in a little

bit now what's cool about UV is again

let's look at this basic python. piy if

I run python 3.11 basic python. piy let

me zoom out so we can see the whole line

here and I hit enter we'll see it prints

out zero right we could even print

something else out we could print hello

like so and let's go ahead we'll rerun

this we printed out zero and hello what

I can also do is I can run this with UV

I could say UV run python

3.11 basic

python. Pi but you'll see I'll get an

error saying file not found no module

named boa now this is where the multiple

versions of python can get a little

confusing and this is where UV is going

to help us out a ton we tried to run

this python script which has this

titanoboa package but we ran into an

issue said hey no module named boa this

is because titano was installed in our

Global or our base or our sitewide

python packages taking a look at for

example at this image here when we


installed Python and titanoboa we

installed it into our global environment

so in our global environment we had

python 3.11 with a package of titano in

our UV environment as of right now we're

not sure what python version it's

working with and we're not sure what

packages we're working with either so if

we go back to our terminal let's go

ahead and clear if I type UV run python

D- version ah I can see it's actually

python

3.1.6 versus if I type python 3.11 D-

version Oh the global one is

3.1.9 so if I come back over here here

we know that our Global python version

is

3.1.6 and our UV python version is

3.11 9 or excuse me other way around

this one's

3.9 and this one's

3.6 now let's say for example that this

script required a certain python version

for example I could do import CIS and

don't worry about understanding this

code quite yet I'm going to paste this

in here if cy. version info is less than

312 raise run toare the script requires

python 312 or higher so this is kind of

a quick way for me to say hey this


python script only works with

3.12 if I clear my terminal I can do

python

3.11 basic python. piy which worked two

seconds ago when we ran this but if I

run this now we're going to get an error

runtime error the script requires python

3.12 or higher well that's really

annoying so does that mean I have to go

back to python.org download python again

make sure it works in the terminal here

and then work everything with python

3.12 this type of mentality or this type

of error occurs on a lot of python

packages and a lot of Python scripts

because different versions of python

have a lot of different features so this

is why coding with python like this in

my opinion is a little bit discouraged

even more ambiguous is if you just do

Python 3 if you have Python 3 installed

basic python. piy you're not even sure

what version of Python 3 this is it

could be 3 1 2 3 4 5 6 7 8 9 10 11

obviously you could check using python

3- version but this can be very annoying

so what we can do instead is we could do

UV python install UV python install

3.12 and we can just directly install


python

3.12 into our UV tool then we can run

the script no problem now we still still

have the error of boa so I'm actually

going to comment out boa for a second

here so now let me let me comment out

the boa things for that because I'm

going to come to that error in a second

but now if I use UV python list I will

actually be able to see a list of all

the different python versions I've got

installed on my computer now I've got a

whole bunch of different versions so

that's why you see so many here now if I

try to run UV run python basic python.

piy I'm still going to get this error

saying the script requires python 3.12

or higher what I can do though is I can

do UV python pin 3.11 or excuse me 3.12

to update the python Das version of this

project to 3.12 and we can see that it

even updated in this file here now if I

clear my terminal and I'm going to hit

up a couple of times like literally the

up key up is a way to kind of cycle

through previously run commands to rerun

UV run python basic python. py again

I'll hit

enter now we can see it does a little

bit of setup real quick here we see the


hello printed out directly because

that's what the print line is doing and

I can clear again hit up a couple of

times I no longer get that setup because

already set up for me but we have pinned

the python version to

3.12 I could even update this to 3.13

save it hit up again hit run it'll

automatically download 3 .3 update our

virtual environment which we'll explain

in a little bit and then run the hello

once again the hello here so UV is a

great tool for actually automatically

very easily switching between Python

versions all you got to do is update

this python version. you no longer need

to do python 3.11 312 run blah blah blah

all you have to do is UV run UV run

Python and it'll automatically detect

the correct version in this python

version right here if you want to choose

a specific version of python you can

also do UV run-- python you know

3.12 python basic python. py and it'll

run our basic python. script with

3.2.7 because we didn't specify a minor

version here so Quicks so I'm going to

go ahead and delete this line now but

what I wanted to show you was that UV is


a great tool because it helps us automat

ially work with a correct version of

python based off of this python version

file

here now let's get back to our packages

issue so as of right now let's uncomment

these lines here now if I pull up the

terminal and I run python

3.11 basic python. piy we get correctly

printed out zero and hello because when

I installed titano boa I installed it

with py python 3.11 M pip install

titanoboa like this this install

titanoboa inside of this python 311

Global packages area so it was only

installed for python 3.11 if I were to

switch to python 32 or 310 or any other

version titano would not be installed

and that could be really annoying to

have to install python have to install

packages on different versions across

different projects etc etc and this is

again where UV helps us out to add a

package with UV instead of doing that

pip install stuff we do UV

add Tian Ooa like so hit enter and this

will automatically add the Titanoboa

package to our project here and you'll

see on the left hand side here a brand

new folder called venv and uv. loock


which we'll talk about in a little bit

but now that we've added titano to our

project we can do once again UV run

python basic python. piy and now after a

little bit of a brief delay oh I should

not import CIS anymore as well we

correctly get zero and hello what's cool

about this is we can flip between

different python versions We can flip

between different package versions We

can flip between any weird dependency

management issues and UV Ron python will

always handle it all automatically Ally

for us we don't have to think about

installing titanoboa on these different

versions and installing the different

packages all over the place we can just

do UV run Python and it handles

everything for us so when we did UV add

titanoboa that was sort of equivalent to

adding it to our packages in here Tian o

boa in our UV virtual environment like

so and UV allowed us to do python

whatever version that we want want and

additionally however many packages we

want being able to flip back and forth

between them no problem additionally

after we run UV ad in our P project.

Tomo we'll now see this dependency


section we'll see titanoboa added in

this dependency section saying that our

whole project now needs titano this

titano package to

work now even though we just said that

okay UV allows us to

have any python version that we want

there's Tech technically what's going on

behind the scenes is UV is setting

something up called a virtual

environment back in our cyron updraft I

can type UV

venv and it will say creating a virtual

environment ATV EnV now if you've been

following along that folder is already

there and I can run uvv EnV again and

and it will still do the same thing

creating virtual environment activate

with source venv bin activate this venv

folder is where UV is going to store all

this information about different python

versions and different packages so when

I run let's do a little clear here so

when I run UV run python basic python.

py it jumps into this venv folder and it

finds all the stuff it's looking for

it's looking for the python version and

it's looking for all these packages so

for example so if I want to update this

to make it a little bit more accurate I


would say UV environment virtual

environment venv and then I come back

you know I hit enter and you know uh

depending on if I have the packages

installed or not it'll you know it'll

install the packages and then run my

script now these two environments are

very different whenever we run a command

with UV run UV will automatically enter

this environment over here and start

running our code when I run just python

3.11

it's already inside of this Global

python environment over here however we

can also think of this a different way

we could think of there being some type

of active python environment and if we

don't specify one it'll automatically go

to the global python environment or this

you know python 311 or you know whatever

we have installed however we can

actually set our active python

environment to be something called a

virtual environment and have it be the

same one that UV enters the way that we

can do that is we can do when we do uvv

andv it creates that folder which again

we've already created we can activate

what's called a virtual environment by


running this command here source. VNV

bin activate and when I hit enter

depending on your shell or your terminal

or your bash or zsh you might get a

little parenthesis bit here that says

hey we're inside of a virtual

environment called Python and updraft

cyphon updraft so now if I type which

python

I now will see this crazy crazy crazy

long string in here saying telling us

what the current active version of

python is and now I can actually use the

python keyword or if I do which Python 3

I get the same thing it's kind of in

this crazy crazy long area but if I do

which python 311 huh I get this

different kind of path right these two

paths look pretty similar just with one

being python one being Python 3 but

which python 311 is this other path and

then what about okay what about which

python

3.13 oh I get that long path again so uh

what's what's going on here well when we

activate when we run this command we

activate what's called a virtual

environment and you can almost think of

it as us pointing this active virtual

environment to over here we're saying


okay the active python environment is

now this isolated this fake python

environment over here and we know that

it's active because again we can see

this little parenthesis SE in here and

this active virtual environment actually

comes with a whole bunch of extra

keywords it comes with Python 3 it

allows us to just write python basic

python. piy except if I do that I get

this module not found error no module

named boa and this is because we first

have to run UV sync UV sync will install

any and all packages that we set up with

UV ad when we run UV sync it looks in

our P project. toml at our dependency

section and goes ah any all of these

python packages that have been installed

we need to add to the venv now when I

run this python basic. piy it'll work

well after a brief delay it'll actually

work exactly as we expected to so now

we're inside of this virtual environment

right we have this we can look up python

D- python D- version we can see a

version in here

and this way if you get annoyed with

having to run UV run you know python

basic blah blah blah you can just


activate the virtual environment with

that source. vmb bin activate and then

just run everything with python now to

get out of this virtual environment you

can do a couple things number one you

can Trash the terminal and then pull it

back up we no longer see it's active and

for me if I type which python I get

python not found now you might still

have python but you'll probably no

longer get the path to the VV and again

we can reinitialize it with source. venv

B activate now we're back inside of it

the other way to get out of it is to

write deactivate and boom now we're back

outside of it so UV is this tool that

will allow us to create this virtual

environment very easily allow us to

enter and exit the virtual environment

allow us to install tons and tons of

packages and not have to worry about

different python versions different

dependencies and a lot of other

different issues that you're going to

run into UV also comes jam-packed with

several other tools as well that we'll

use throughout the duration of the

course and you'll learn more about how

UV works because in my opinion it's the

most modern framework for making


absolutely sure that when you run code

when you run your projects you never

have to worry about the weird Oddities

of versioning having to be compatible or

not

okay so we're pretty much done with the

python crash course and also teaching

you about python in updraft so at this

point you have learned a ton now like I

said the way that we're going to be

using python is going to be a lot

different than what a lot of other

python tutorials teach you how to do I

will tell you the equivalent commands to

what other python tutorials tell you

right a lot of python tutorials for

example even the Titanoboa GitHub it

says Hey install titanoboa with Pip

install titanoboa but we installed it

with you UV ad titanoboa the reason I'm

setting you up very differently than

what a lot of tutorials do is because I

want to set you up for success and at

the beginning there might be a little

bit more context but it's going to

prevent you from running into weird bugs

later on in your journey like I've said

100 times AI is phenomenal at working

you through these dependency issues


inversing issues and asking your ai's

questions about hey I'm trying to do

this but I'm running to this issue

what's going on AI is great at helping

debug there so to end off this section

let's do a quick recap of what we've

learned with setting up our vs code

working with Python inv vs code UV

different python versions Etc so first

off we all installed python into our

Linux like environments and we can

access and work with the python version

that we install with python 3.11 D-

version this is our globally available

or systems or base version of python

that has its own set of packages

associated with it we wanted to change

to a different version of python we'd

have to go onto the python website we'

have to download it we'd have to we'd

have to maybe change some links on our

vs code to point to the right version of

python and that's incredibly frustrating

so what we can do instead we can just

use UV to always manage our python

versions by UV run python D- version and

it'll give us our pinned version of

python if we want to work with a

different version of python well it's

really easy UV python pin


3.12 and it'll Now update our python Das

version from 313 to 312 and I can do UV

run python D- version and I can see we

changed to

3.2.7 additionally UV will manage all of

our packages in this thing called a

virtual environment for us so if we want

to add a package typically unit install

that package with Pip install or what we

learned which was python DM pip install

and then your package name like

titanoboa if I were to execute this

right now well first all if I were to

execute this right now well first of all

I'd have to say python 3.11 dmip install

this would install our package titanoboa

into our globally accessible python

environment and as of right now this is

also our active python environment

however if we change python versions

that package will not be available for

this other python version so to add a

package with the UV we would run UV add

titanoboa or whatever package that you

want and it'll add it to your project

and update your p project. tommo with

that dependency or that package so that

no matter what version of python that

you're working with you will always be


able to very quickly and easily work

with this package when we do UV add it

installs it into this venv folder

whereas when we do python 3.11m pip

install it installs it into that kind of

mysterious Global python environment so

and we can even look in here we can look

atvv lib we can kind of scroll down

through all the different packages in

here and we can see this boa package in

here which gets installed when we do UV

add titanoboa if we get sick of running

UV run python every single time what we

can do is we can activate the virtual

environment that UV automatically sets

it up for us so we can just run UV

venv which will set up and create that

virtual environment then we do source.

VV bin activate and now we have access

to the python keyword python D- version

without having to do python 3-11 python

3.11 D version we can just simply use

the python keyword we can also use the

Python 3 keyword and they both point to

the exact same version we can now also

just run python basic python topy we can

run all of our Scripts

and if we get an error saying module not

found no module named boa we would just

run UV sync to make sure that we


download all of the packages for the

current version of python that we're

working with we can run our Command

again and now after a brief delay to

load everything up everything works

correctly to get out of this we would

just do

deactivate and now for me since I don't

have a python keyword in my global

environment if I type which python I get

python not found if you type which

python you might either get python not

found or You' get python in a different

place if I were to run again the source.

VNV bin activate and now I type which

python you can see that this python

command is pointing to my python object

inside of myv EnV folder here so this

python also is inside this VNV so this

venv fold ER is containing all the

information about the version of python

the different versions of packages etc

etc if you have got this far in this

course well done you have set yourself

up to not fall into a lot of the issues

that other python developers fall into

and to be honest the ones that I fell

into when I was becoming a python

developer myself you now have installed


most of the tools that you're going to

need to become a successful smart

contract developer and I'm so excited

for you to get this far because you have

some of the most modern tools installed

in your vs code that's going to make you

way faster of a developer than most of

your peers out there so at this point

you should give yourself a big pat on

the back and now is a great time to go

take a break go grab a cup of coffee

maybe grab some ice cream go to the gym

or whatever you want to do because as I

always say your brain absorbs

information faster when you take breaks

taking breaks is important

congratulations for finishing the python

crash course and the python and updraft

setup

welcome to the web 3 Pi favorites

section of cyron updraft now of course

if you're following the GitHub repo

associated with this course you can go

ahead and scroll on down to wherever the

link is to this section okay it looks

like it's uh right here SE to web3 Pi

favorites list and you can actually see

a link to the final project available

right here as per normal all the code

for this section is going to be


available here now I'm going to walk you

through what we're going to be building

here and all the tools that you should

have installed at this point just in

case you skipped the last section about

getting set up with python which you

shouldn't have but if you did that's

okay because we're going to make sure

that you have everything up to speed

here now if you have signed up for

GitHub which again you 100% should the

full codee for this section will be

available right here we can go ahead and

click this into a new tab to see all the

code here but anyways this is all of the

final code that you're going to be

building and now let me walk you through

what this project is going to do you go

ahead and pause the video if you'd like

and walk through the read me now I've

got all the code from that repository

right here with me and what we're going

to be doing is we're actually going to

be writing some code we have favorites

or hello.py and favorites. VI we have

our favorites. VI file from our last

section right here in our codebase here

and we're going to be deploying this to

a blockchain using raw python actually


coding everything ourselves additionally

we're going to be working with some

really cool Advanced python where we're

going to write our own python key

encryptor we're going to encrypt a key

ourselves in Python we have a script

called deploy favorites.i where we're

going to use our encrypt private key to

actually deploy our smart contract in

Python and in doing so we're going to

learn a lot about what a transaction

even looks like how do you build a

transaction what is a transaction even

compromised of remember way way way back

in blockchain Basics we talked about

signatures and signing stuff and and but

like how does that work over here we're

actually going to show you what it's

like to sign a transaction in code so

that we can deploy a contract because

yes deploying a contract still requires

you to sign a transaction so we're going

to write this entire deploy script we're

going to write this encryption script

we're going to take our favorites. VI

file from the remix section and we're

going to learn what's going on under the

hood of all those remix buttons that we

press additionally we're going to start

working with more advanced python


tooling and how to make sure we're

productionize with all of our Python and

at the end we're going to give you a

workshop where we're going to ask you to

write your own minimal Viper Smart

contract and actually deploy it with

your own custom scripts so in this

section you are going to learn a ton and

please use the GitHub repo and of course

back in the GitHub repo associated with

this course be sure to use the

discussions when you have questions when

you get lost to ask questions and of

course use your AI buddies as you code

along with us this is what we're going

to be learning here this is going to

give you the fundamental knowledge to

understand a lot of what's going on

under the hood of those buttons that

you're pressing and remix and this is

going to be pivotal information for your

Learning Journey at the end of your

journey here you're going to be able to

run this command UV run deploy favorites

let me zoom out deploy favorites. py hit

enter it's going to read the Viper code

and deploy it to the blockchain it's

going to ask you to enter your password

for your encrypted private key and


you're going to go ahead and enter your

password I encrypted mine very poorly

with the password password don't ever do

that going to hit enter it's going to

decrypt the key for you it's going to

give you this huge huge huge piece of

like seemingly arbitrary code like what

is this but it like what is this this is

a signed transaction object to deploy

our contract then we're going to go

ahead and deploy the contract say done

contract deployed to and then give you

the address that it's deployed to

additionally afterwards if we want we

can also add transactions to interact

with this contract that we just deployed

such as adding a person storing a

favorite number Etc so and end that's

what we're going to be doing this is

going to be a pivotal moment of you

moving away from clicking buttons to

doing things to doing things

automatically and autonomously we as

developers want to work incredibly hard

to be incredibly lazy clicking a whole

bunch of buttons is often a lot of work

so we're going to do even more work to

write a whole bunch of scripts so that

we only have to run one command and

it'll do everything for us automatically


so with that being said let's jump in

and let's start learning this

section now back in your vs code you

might be in the python in updraft cyphon

updraft or if you took a break you might

be someplace else no worries so let's go

ahead let's do PWD to make sure we are

to see where we are let's do CD dot dot

this dot dot stands for change directory

down a directory if we hit enter we do

PWD now we can see we moved from Python

and updraft down to this directory MOX

CU and if we do a little LS in here we

have the readme and we have that python

in cyon updraft folder so these are the

two this is a file in this folder and

this is a folder in this folder what we

can do now is we can make a new folder

mkd which stands for make directory web

3 Pi favorites Das cyphon updraft or CU

now if we type LS we'll see the read me

Python and updraft and web 3 Pi

favorites cyphon updraft and we can now

do CD or excuse me CD web 3 pi and then

I just hit Tab and it autocom completed

the whole thing hit enter now if we type

PWD we can see we are indeed in this

folder if I do code period because I've

installed the code command it'll


actually open up it a new window for me

inside of this folder which is going to

be empty and I can actually close this

other window

and pull this one up onto my screen if

you do not have the code command you can

always do file open folder and just

select the folder you want to open which

is this web 3 Pi favorites Cypher

updraft and just hit open like that now

if we pull up our terminal again with

contrl Tilda or control backtick and we

type PWD we'll see or terminal new

terminal we'll see we are indeed in the

web 3 p favorites Cypher updraft and if

we open the Explorer right close the

Explorer open the Explorer we'll see

it's blank over here at this time in

this course you should have a couple of

things installed the most important one

for this section is going to be UV so if

you do do uv-- version you should get an

output like this if you don't have UV

installed go and install it okay we we

taught you how to install it in the last

section if you go to the GitHub repo

associated with this section the web3 pi

favorites cyphon updraft and you scroll

down there will be a link here to UV

that you can go ahead and click to bring


you to UV and just follow the

installation steps to install UV since

we have UV we really don't need any

other python tooling but maybe you

skipped over the last section and you do

have you know python 3-- version and

that's normally how you're used to doing

python management and tooling don't

worry I will walk you through how to

just to UV so I'll be giving

instructions but if you're used to doing

things raw if you will with Pip and

python Etc I will give you the tips in

here as well however you should still

have UV installed because we're going to

be using a lot of UV tooling throughout

this course now to get started we're

going to run UV in nit which initializes

a project a new Pi project. toml in the

web3 pi favorites Cypher updraft

directory and if we open up our Explorer

here we can see we're given a number of

files again we went through these and

what they're for a little bit in the

last section and with that we're ready

to start coding the raw low-level

understanding of transactions deploying

our own smart contract through python

code so that we can be well prepared for


understanding much later all right so

here we are in our vs code we just ran

our init command so we have a blank

python project in this folder let's go

ahead and get started by jumping into

this readme.md file and just writing out

from a high level what we want to do so

we're going to do uh a couple things

we're going to do a little hashtag here

and say web 3 favorites CU or Cipher

updraft and we want this to do a couple

of things do what does this project do

what are we going what does this project

do and then down here what are we going

to learn so number one we're going to

learn how to deploy our Viper contract

from raw python number two we going to

encrypt our private Keys locally and use

them to sign transactions remember how

every time metamask popped up and says

hey do you want to confirm inside

metamask metamask was actually signing

transactions and we're going to learn

exactly what metamask was doing exactly

what hex state of metamask was working

with and how we can do it ourselves so

we can reverse engineer metamask in any

transaction that's ever out there and

then finally this is going to be reprodu

Able by other Engineers UV with python


so we're going to be using UV to make

sure that this project is very easy and

reproducible for anybody else to come in

no matter what and what are we going to

learn well we're going to learn all this

but we're also going to learn what is a

transaction comprised of what's in a

transaction what is a Json key store how

can I safely store my private key and a

lot more so this is what we're going to

be doing let's go ahead and get started

with our first step we want to just

deploy our Viper contract from raw

python let's get started working on

this so to get started let's go back to

the GitHub repo associated with this

course the maos and FL course and you

can either just grab this file from the

favorites. vi in the you know web3 Pi

favorites cyphon updraft or you can go

back to the MOs and full course let's

scroll up let's look for this where is

it

uh favorit ciper updraft let's go here

let's click the favorites. vi and let's

just go ahead and copy this entire file

here and we'll come back to our VSS code

go to our file explorer and right click

new file type in favoritz by and then


paste that file in here nice so now we

have our smart contract right in our

code editor but this looks pretty

disgusting there's no syntax

highlighting like REM remix remember

remix had these that nice syntax

highlighting and even GitHub had like

some nice colors that made it easier to

read well so what we can do is go to the

extensions Tab and we can look up Viper

and we'll see we'll see this Tintin web

Viper extension for vs code and we're

going to go ahead and install this now

in our Viper file we'll see it's

highlighted very nicely maybe depending

on your setup you might not have this if

you go open up your terminal and you

type in which Viper if you do have viper

installed you'll get this nice

highlighting if you followed along with

us in the last section we installed

titanoboa which installed Viper under

the hood sometimes it might throw an

error if you have the wrong version of

Viper installed so for now just roll

with me if you have it installed or you

don't have installed no worries it

should be okay no matter what I'm going

to show you in just two seconds how to

install Viper with UV so if you have


some red squiggly lines in your vs code

giving you some errors don't worry about

it for now we're going to show you how

to fix it very soon but if you have no

red squiggly lines even better let's

keep

going so now that we have our code in

here what was the first thing that we

did back in remix whenever we had our

code bases well let's pop back over to

remix real quick to remind you well the

first thing we always did was we would

go over to this leftand side scroll down

for the Viper compiler and we would

compile our code Base by hitting this

big compile Buton button we don't have a

big compile button here we also want to

compile our Viper to well make sure it

actually works so we can pop open our

terminal we also want to compile this

Viper contract and we can do that a

couple of different ways but no matter

how we decide we want to do it we have

to download the Viper compiler so behind

the scenes this compile button is

actually reaching out to a Viper

compiler you can actually look up Viper

on GitHub Viper Lang svper

and this is all the code associated with


the Viper compiler you can go to the

Viper documentation to learn how to

install and build it some of the easiest

ways to install Viper are going to be

pipex install Viper or oh this is a tool

I'm familiar with UV tool install Viper

so we're actually going to start by

installing Viper with this UV tool

install Viper and I'm going to explain

what this does in a minute so I'm going

to go ahead and run UV tool install

Viper and it's going to give us these

executables Fang Viper and Viper Jason

I'm going to go ahead and clear the

terminal type Viper d-el and we get this

massive documentation output about all

the different things we could do with

Viper so we type clear again we do viper

D- version we'll see the version of

Viper that we installed yours of course

might be different than what I am seeing

here now to compile our favorites

contract all we have to do is type Viper

favorites. VI and hit enter and that's

it boom all of this hex that you see in

front of you this this is the hex code

which is kind of the binary code this is

the raw code of what actually gets sent

to the ethereum or ZK sync or optimism

or arbitrum or whatever chain that


you're deploying to this is what

actually gets sent to the blockchain all

of this stuff is just human readable

text it's this jaral list of numbers

that actually get sent to the chain it's

this list of numbers and letters that

gets sent to the chain well kind of it's

technically zeros and ones but never

mind now we're getting too low level

this is what actually gets sent to the

chain and with this we have successfully

compiled our favorites. vi just like

that Viper favorites. VI that's it

now I want to talk about what we just

did though before we continue we did UV

tool install Viper now if you're new to

UV this might be a little bit weird this

might be a little bit different than

what you're used to if you're from the

python world you're probably more used

to doing you know python 3-m pip install

Viper or you've probably seen this more

often just pip and saw Viper right now

you could do that and that works

perfectly fine fine however that will

install Viper into your active

environment and UV tool install

installed it into its own isolated

environment let me explain so let's go


back to our little environment here if I

just did you know pip install Viper or

you know python

3.11m pip install Viper it would install

Viper into the active python environment

you know so it would install Viper into

this into the global python environment

if I was in a virtual environment which

by the way you can also set those up

using raw python if I were to do you

know python 3.11 DMV env. venv slash

this would actually create that venv

file that V EnV folder that we created

with UV right here and then I could do

source. venv SL bin activate activate

and now you'll see we're in this VV

virtual environment if you skipped the

python and updraft section we talked

about this a little bit more at length

so be sure to go back and learn more

about virtual environments now if I did

you know python

3.11m pip install viper well the active

python environment is now pointing to

this virtual environment that you know

actually we installed that one with with

what python 3.11

DM uh EnV VNV and then we ran Source v/

bin activate you can see kind of where

I'm going with this virtual environment


stuff because it's already getting a

little confusing since the active python

environment is now this virtual

environment this environment basically

the same one as the UV environment we

would install Viper in here so actually

I'm going to go ahead and I'm going to

even install this into this virtual

environment you don't have to if you

don't want to now if I do a python 3.11

- M pip freeze and again you don't have

to do this I can see my Viper package in

here but I can see a whole bunch of

other stuff in here as well so the Viper

tool and any python tool in general

often depends on other packages as well

now what can happen is let's say for

example we wanted to use this package as

tokens but we wanted to use a different

version and we installed the different

version we would end up screwing with

Viper and we really do not want our

compiler to have different package

versions than what's recommended because

the compiler is incredibly sensitive so

we ran this install command called UV

tool install Viper and this did

something very special now we spoke a

lot about all these kind of different


virtual environments and how the active

virtual environment can switch between

This Global one and if we run uvvv or

source. VNV bin activate it can kind of

switch between these different virtual

environments and these different virtual

environments can have different packages

in them right I can have the Viper

package in my virtual environment but

not in my global environment I can have

different python packages and different

versions of python in in each one of

these different environments when we run

UV tool install Viper what we

essentially do is we create Viper's own

isolated environment way way over here

that we never see and we never interact

with and anytime you try to switch

python environments you pretty much can

never switch to the Viper environment

because because we don't want to screw

with any of the packages or the stuff

over with the Viper compiler if I type

which Viper even though I'm in this

virtual environment it points to this

users Patrick local bin Viper but if I

deactivate activate

deactivate the virtual environment let

me clear it out I type which Viper again

I'm still in this environment it's very


different though than if I installed it

into a virtual environment so let me let

me show you this if I do UV tool

uninstall

Viper I uninstall the executables which

means if I type which Viper now I'm

going to get Viper not found or you

might still have viper installed

someplace else but again I've in I've

uninstalled it everywhere but if I now

do source. venv vv/ bin activate and now

I do wi Viper I do indeed see I have a

Viper command because we installed Viper

in this virtual environment right and

when I ran the source bin activate the

active python environment was now this

virtual environment over here so we have

this Viper executable in here and when I

run

deactivate I move out away from the

virtual environment back to the global

environment where I uninstalled Viper so

the Viper package no longer exist CU I

uninstalled it way earlier and now I do

which Viper and I get Viper not found

when I do UV tool install Viper again I

am installing Viper but I don't install

it into the global python environment I

install it to its own isolated


environment so I can do which Viper

again and we do have a Viper executable

but it's completely isolated from the

global python environment and from the

UV virtual environment so there are a

number of commands which we're going to

always install them into their own

isolated environments like said a

compiler is a very very sensitive piece

of code and we do not want to screw with

it we do not want to touch it so we want

to install Viper into its own virtual

environments pretty much whenever we're

stalling in Viper now there will be

scenarios where we want Viper in our

virtual environment however for now I

want you to get into the practice of

saying ah okay there are some tools

which should be in their own isolated

environments and this is going to save

you a lot of headache much later down

the road when you do start to Tinker

with packages that other packages want

and you start to break them and things

will just stop working and you won't

understand why so that's a little bit

more about virtual environments isolated

environments Global environments and

virtual environments in general there's

a lot of understanding when it comes to


these different environments however

this will set you up for Success so you

can work with these a lot easier if this

was confusing that is okay there's a lot

of information that I just threw at you

and probably the virtual EnV

environments piece is one of the hardest

things to comprehend so if it didn't

fully sit with you quite yet that's okay

just keep following along with me please

ask your AI buddies questions and and

engage in the discussions Forum I have

that GitHub co-pilot chat on I might

even ask what's the difference between a

Python virtual environment and when I'm

not in a virtual environment I might

switch over to Claude 3.5 as my AI again

this is a paid feature so feel free to

use your AI of choice but all I might

add ask it a question and it's going to

think for a little bit and it actually

does a pretty good job explaining the

key differences between using python

with and without a virtual environment

it even gives us some helpful tips for

working with virtual environments right

in vs code but again I digress so going

to close out the chat delete and kill

the terminal pop the terminal back up we


should still have the Viper command

because it's installed in its own

isolated environment and we can continue

now that we've compiled our Viper file

nice all right so now that we learned

how to compile Viper via the command

line let's learn how to compile it in a

script and then actually deploy it to a

blockchain so what we're going to do is

we're going to close everything and

we're going to create a new file over

here called deploy

favorites. pi and this is going to be

our python file for actually deploying

this smart contract to a blockchain now

here's a bit of a python tip in Python

whenever you call a function in Python

whenever you call a file you know for

example when we did you know python

3.11 basic python. piy from the last

course or from the last section or if we

ran python 3.11 hello.py or even if we

did UV run python hello. Pi like so

actually and you might see this pop up

we will fix our we're going to fix our

python environment in just a second for

now feel free to just hit that X there

but you'll see hello from web3 PI

favorites Su or whatever you have in

your hello.py you'll see actually UV


gave us kind of this weird template if

uncore unor name uncore uncore equals

equals you know this string main call

the main function which prints this out

whenever you run a file you essentially

say hey make the name that you're

looking to callcore uncore maincore

uncore so anytime you invoke a file

basically just this so typically we like

to be very explicit when we're coding in

a more professional environment so we're

actually going to follow this same

convention in our deploy favorites dopy

so I'm going to go ahead and close

everything here I'm going to paste this

line in here now these double

underscores are also known as Dunder

names or double underscore names this is

called Dunder name and this is called

Dunder Main which means double

underscore so double underscore name and

double uncore main if double uncore name

equals equals double underscore main run

Main and we'll create a little def

main which we will just pass in here for

now and to make sure that this is

working we can do a little print

Blue from deploy favorites. piy and you

can see right there actually this is my


kit up co-pilot giving me a suggestion

and since I wanted take it I'm going to

go ahead and hit tab to add it to my

file and then of course hitting command

s or controls to save and we can get rid

of the pass line now now to make sure

this is working we can run UV run python

deploy favoritz dopy and we sure get

hello from deploy

favorites. but if you get sick of always

doing UV run python we can also once

again do UV venv we can then do this

line I'm just going to copy and paste it

baste now we have our virtual

environment set up and now we can just

run python deploy favorites. piy and I

hit tab to autocomplete and we get the

exact same output then let me clear this

out here and then just know that as

recording I actually changed my terminal

to get rid of that Patrick's MacBook Pro

because that's super annoying especially

when the commands get longer and longer

so moving forward it should look like

this or should be smaller but it's going

to be the same terminal here anyways so

we can activate our virtual environment

source.

vv/ bin SL activate and then I can do

python deploy and I can just hit tab to


autocomplete and we get hello from

deploy favorites stpy

great so in here let's change this print

statement to let's read in the Viper

code and and deploy

it so first thing we're going to have to

do is we're going to have to read in

this favorites. VI Viper file so let's

go ahead and do some nice little python

here and now actually you're going to

learn how to open files so we'll say

with open the name of the file

fa Ritz Dov and even my GI up co-pilot

is basically telling me how to do it but

I'm also going to do an

R comma

R um this is a let's open favorites. VI

in readon mode and we'll give it a name

as

favorites

file

favoritz code equals favorites

file. read so this is how you read the

contents of the whole file into a

single variable now this favorites code

variable has everything in this

favorites. VI

then we're going to need to compile this

in our codebase here so uh how do we do


that we can actually use the Viper

compiler itself to compile this codebase

so yes we installed the Viper compiler

clear you know Viper D- version as a

command line tool but it's also a

package we can add into our project here

so to add it in you already know how to

do this we can do UV add Viper and this

will add it in and a nice shortcut that

I use quite often either is either

hitting command P or control P depending

on if your windows and then type in the

name of the file that you want and it'll

allow you to just hit enter and open up

directly into that file like what we

just did now we can see in here we have

this dependency section where we've

added Viper greater than equal to

0.4.0 so now that we have viper as a

package as a dependency for our project

we can actually run UV sync in our

terminal as well and now Viper will also

be inside this virtual environment so

now we have a Viper in a isolated

virtual environment and then we also

have a different Viper inside of this

virtual environment so we have viper all

over the place now to work with this

Viper we can run from Viper import

compile code compile underscore code and


don't worry we're going to fix this

underscore in the next lesson this

compile code is a function that comes

with our Viper package and then we can

do we can run compile code with this

favorites code and do a comma output

formats equals and we'll say bite code

this way we'll get that exact same bite

code that we got when we ran you know

Viper favoritz favoritz Dov in the

terminal we got all this bite codee here

we want to get this CU that's the

compilation stuff we needed we want to

get this bite code and then we can save

it as a variable called

comply compilation details equals now

something that I like to do as well is I

like to do this thing called wrap word

wrap so that the code will show up on

the next line you can also toggle this

off the way that I'm toggling this is I

enter the command pallet by typing

command shift p or control shift p and

it's basically the same is that as this

command pet I just showed you but it's

just with an added you know greater than

sign and this allows you to run commands

very quickly on your vs code so I'm

going to go ahead and toggle word wrap


like so and now just to make sure that

we're doing this right let's just go

ahead and print compilation details and

see what we get so let's pull the

terminal and now since we are in our

virtual environment we can run this with

python deploy favorites. py or once

again we can do UV run p python deploy

favorites. if we're not in a virtual

environment or if you've ignored me this

whole time and have installed stuff with

Pip you know whatever you want to do

great I'm going to run python deploy

favorites. pi and we see this curly

bracket object with this section called

bite code and then the exact same hex

that we saw when we ran with the CLI

nice I'm going to comment this line out

for now to move forward

so now let's address this weird yellow

squiggly line here if we roll over this

with our cser we might see import Viper

could not be resolved H well that might

be a little confusing because what do

you mean it could not be resolved this

is vs code saying hey I'm currently

looking for this Viper thing that you're

talking about but I don't see it I I

don't see this Viper package now

obviously our Command worked right we


were able to print out the compiled

viper bite code however VSS code doesn't

know which python environment that we're

working with so if we go back to this

little diagram here again our terminal

has the active python environment

terminal our terminal has an active

python environment which as of right now

if we pull up the terminal it's this

virtual environment right it's not the

global python environment so let me

point this over to here it's this

virtual environment and this is the

terminals active python environment

however this section up here is is not

the terminal it's very different and

it's the extension it's that pylance

extension so even if we roll over it

again says this warning here is coming

from pylance if we look up pylance and

hit enter we installed this when we

installed the python package here this

pylance thing isn't aware of what's

going on in the terminal and that's okay

so what we need to do is we just need to

tell our pylance hey uh which one of all

these python environments is there is

the currently active one and so what we

can do is we can scroll down here and


click this button and it will say select

the python interpreter right now for me

it's using my Global python environment

right you see how it has This Global

word here and again mine might be

different from yours yours will probably

be this one but it might be a different

one um but you can see a whole bunch of

the different python versions here but

it is smart enough to say hey this is

the recommend one which is that venv now

this is currently our active python

environment in our terminal right this

is where this virtual environment is

pointing to so if we switch the Pan's

interpreter path to this one up here we

just go ahead and click this now that

little squiggly line goes away we see it

has a nice little green color to it now

and now our vs code pylance lter or

formatter or the the thing the governor

of the squiggly lines now knows which

python we're working with we're working

with this python in the venv and the

reason we're going to set up every

single project like this again with

these VN with these venv folders is

again so that dependencies don't Clash

so that every single project can kind of

run in an isolated type environment now


if you don't like doing that you can go

ahead and install everything in a global

environment I don't recommend doing that

because at the end of the day it will

make your life miserable but you know

you do whatever you want to do so great

let's keep

going so we have the bite code in this

compilation details variable that I've

created and we're compiling directly

from the Viper object so now that we

have this we need to actually create the

contract itself in Viper so now that we

have the object what we need to do is we

need to turn this compilation detail

stuff into a contract object to do this

we're going to use a tool called Web 3.y

wow that is freaking adorable I hope a

human being created this cuz that is so

cute so we're going to be using this

this package called Web 3. piy because

it's got a lot of fantastic tooling to

both teach us what's going on under the

hood and also help us deploy our

contract here so same thing if we go to

the quick start here we scroll down we

can see this little installation section

this is how we're going to install it we

can see this little installation section


and it says the classic pip install web

3 since we are using UV we know that

instead of pip install we're going to

run UV ADD web 3 and this is going to

add it directly into our active virtual

environment if you're not sure if it

added it or not you can run UV sync and

then you can also check your Pi project.

Tomo to make sure that this was indeed

added in here as well now that web 3py

is in here we can actually start using

web 3.y in our project as well and if we

go to the web 3.y documentation we can

look up contract we can look up this e.

contract API which allows us to very

easily create contracts if we have

addresses if we have contract names and

of course if we have bite code so we're

going to use this by at the top first

saying from web 3 import web 3 I know

that this is a little confusing this is

lowercase and this has an uppercase W

and then we're going to have to

initialize a web 3 object quick start

documentation here also gives us um some

ideas on how to initialize an object

they give us this etherium tester

provider like this we're also going to

import this ethereum tester provider so

that we can make a W3 object this will


probably be a little confusing don't

worry about it too much we're going to

get rid of it pretty soon so we're going

to grab this ethereum tester provider so

we're going to do from web 3 import web

3 and the ethereum tester provider and

we are going to say W3 equals W3 and my

get up co-pilot is giving me the keys

here ethereum tester provider like so

and what we can do is we can say favor

Ritz

contract

equals

w3.css

compilation details

at Key B code so this compilation

details object is what's known as a

dictionary kind of similar to the

hashmap that we saw in Viper if we print

out this compilation details again

actually if we do a little print

compilation details and then let's rerun

with python deploy favorites or UV run

python deploy favorites we get that

print line out again well we actually we

get an error about ethereum tester

that's okay we're going to get rid of

this in just a second because uh the

ethereum tester provider requires


additional dependencies installed via

pip install web3 tester we forgot to do

that but we're going to dump this pretty

soon so let's we're going to skip that

but if we scroll back up to where we

printed the compilation details again we

see we we see the object get printed out

this is known as a dictionary when we

reference the bite code key we get the

actual bite code response so to create a

contract type variable we do web 3. e.

contract bite code equals compilation

details of bite code that's kind of

equivalent to doing this line here is

equivalent to literally just like

pasting the bite code in like that right

now we're actually going to dump this

ethereum tester provider because because

we're pretty much never going to use

that ever again and I don't really feel

like using it what we're going to do

instead for now is we're going to

connect to an HTTP provider which is

something we have done before so in the

web 3p documentation we have this remote

provider section and we actually have

set up a remote provider already with

tenderly so what we're going to do is

come back to tenderly grab this https

link copy this go back over to our code


and we're going to say W3 equals Capital

web

3 web 3.

HTTP

provider and then in here we're going to

paste that

text from

tenderly to initialize a web 3 instance

you have to actually connect to a

blockchain note right and this is our

fake sepolia tenderly blockchain node we

I'm also going to show you in just a

second how to not even use this how to

use something even easier but for now go

ahead and use this because then we can

do this favorite contracts this favorite

contract section here and we can even

print out favorites contract so let's go

ahead let's run this whole thing again

let me clear out the terminal now we

won't get that error again python deploy

favorites ofu Pi I'm in my virtual

environment if you're not you can always

do UV run python deploy favor ofy let's

go ahead and enter and we see the

compilation details printed out and we

see this section down here so this is

the response this is the print this the

string interpretation the print


interpretation if you will of the

favorites contract you can see it says

class web3 dos. dat types. contract this

is basically saying our favorites

contract is of type contract which if

you go to the documentation here you can

read more about this contract object if

you go over to guides you can see

contracts and you can see a lot more

about interacting with and deploying

these contracts which is what we're

going to learn here very exciting so I'm

going to go ahead I'm going to remove

this print statement and then remove

this print statement as

well now we're going to run this one

more time but I'm going to show you one

of my favorite things about python I'm

going to add this thing called a

breakpoint right here in Python now if I

pull my terminal up and I run this that

command again and you know what I'm even

going to deactivate my virtual

environment right see now it's gone just

so I can do UV

run python deploy

favorites. piy just so I can show you it

also works perfectly with this if we run

this what happens is it executes all

this code and then when it hits this


line we drop into a python shell or a

pdb a python debugger shell where we can

once again execute python code so once

again I can type favorites contract

it'll do that same print statement as we

did before I can of course also write

print favorites contract I can do print

heyo

like this it is a regular python shell

that we've seen a few times now now what

can we do with this favorites contract

well is it

deployed uh no well does it have any

functions on it uh well no right now

this favorites contract isn't really a

contract it's just kind of a placeholder

for the bite code at the moment we got

to do a few more things before we can

actually deploy the contract to an

actual Network so this favorites

contract is kind of just it's not really

a contract yet it's just a holder for

the bite code and pretty soon it'll be

the holder for something else so you can

type quit to exit the debugger or a lot

of pdb debuggers also just let you type

Q to exit the debugger as well and then

we'll go ahead and clear get rid of the

brake line and we'll keep


going now I don't want us always using

this endpoint because what's going to

happen is if you end up if you do end up

buying a tenderly subscription if you

have this URL right in your code you

might actually end up pinging tenderly a

whole bunch and maybe racking up a bill

that we don't want to rack up so we're

actually going to move away from

tenderly to our a new fake local

blockchain very similar to this remix

remix VM kind of this fake remix VM you

my friends are going to run a miniature

fake blockchain right inside of your vs

code so the way that we're going to do

this is we're going to install this tool

called Foundry so if you go back to the

GitHub repo associated with this course

and we scroll on down here and if you go

to the giab repo associated with this

section and we scroll on down here we'll

see there's this Anvil prerequisite

we'll go ahead and click that or command

click it so it opens up in a new tab and

this will teach us how to install this

tool called Foundry now Foundry is this

incredibly powerful smart contct

development framework similar to

moccasin which we're going to learn very

soon that comes out of the box with this


fake blockchain called Anvil so we're

actually going to go ahead and install

this by copying this link and by copying

this code base right here or copying

this Command right here go back to our

terminal open up our terminal let's hit

clear paste this in and this is going to

install this tool called Anvil directly

into our terminal now you'll see this

section down here detected your

preferred shell is you know in the

whatever your shell is and added Foundry

up to path run you know this command or

start a new terminal session to use

Foundry up so this will detect what

shell you're on it could be zsh it could

be bash it could be anything like that

so I'm going to go ahead and delete my

terminal and then restart it and then

run Foundry up without the period right

there and you'll see it's installing

Foundry Forge cast Anvil and chisel like

so whenever we want to update Foundry we

can just run Foundry up and this will

update this Anvil tool that we're going

to be using which is going to be our

locally running fake blockchain we'll

know that we've installed this right if

we run Anvil D- version and we see an


output that looks like this now if when

you ran Foundry up you didn't get an

output like this there might be an issue

with Foundry up or Foundry being added

to your path if this is an issue that

you have please ask your AI buddy or

make a discussion on the on the

discussions tab of the moccasin full

course Cypher updraft section if you

trash your terminal and then pull it

back up again and you type Anvil Dash

Das version and you see nothing here

well I I do see something here it might

be because like I said you're having an

issue with your with your bash profile

or Z profile or one of your profiles

here what you can do to help fix that is

I've got a little shortcut for you in

the web 3 Pi favorites Cypher updraft we

scroll down if you're having an issue

it's probably likely that your bash RC

and Bash profiles are having a bit of an

issue here so you can if you're on bash

just copy this line and paste it in here

similarly if you're having if you're on

zsh copy that line paste it in here but

if you're not having any issues with

doing and build Das version you know

don't do anything all good even more

easily when you run Foundry up and


actually when you install Foundry let me

go ahead and clear this out and paste

this again when you install Foundry it

even gives you this this line here this

is what I would need to add to my path

so this little shortcut I would say Echo

uh Echo this line into my Z profile but

again if Anvil is working perfect for

you no problem just make sure it's

working even when you trash can the

terminal and then run Anvil D- version

again what these commands will do is

it'll add the bash RC to your bash

profile or the zsh EnV to your Z profile

which will essentially help your

terminal find envil easier if you want

to learn more your AIS are great at

understanding what those commands do and

feel free to ask them a ton of questions

about that anyways trash the terminal

open the terminal back up if you can run

Anvil D version you're looking good

great let's keep great let's continue

and if you're not looking good ask AIS

ask the discussion ask on the fors Etc

Great got it cool let's continue

so now that we've installed Anvil what

we can do that is really really cool is

we can just run Anvil like this and


we're going to get an output that looks

like this and if we scroll up we can see

whoa we're actually currently running a

fake little blockchain ethereum node

right inside of our terminal right

inside of our vs code and what we can do

is we can leave this Anvil instance

running create a new terminal and do all

of our stuff inside of this terminal and

instead of connecting to tenderly here

what we do is we go back to Anvil scroll

to the bottom we can copy this little

link that it gives us and delete all of

this and instead do

HTTP dot dot SL slash and then paste

that in here and connect to our Anvil

instance instead now to test this out we

can go ahead and run UV run I'm going to

reactivate my python environment with

source. VMV pin activate so I can just

run python deploy favorites. piy we'll

see we'll get the output like so if we

turn off our Anvil instance by hitting

contrl C which will delete it or you can

just you know kill the

terminal back in our terminal here if I

run once again python deploy favorite St

Pi uh it'll work fine however when we go

to actually deploy the contract this

needs to be a working endpoint but for


now since since we're not actually

deploying it doesn't really

matter so now that we have this favorite

contracts thing which is in this

contract object which is still a little

bit hazy to us but whatever how do we

actually deploy this thing well well if

we think back to how we did it on the

remix VM well what do we do well we hit

well we selected our contract we went to

the Viper compiler we hit compile then

we went to the deploy Tab and we hit

deploy and it was that easy when we were

on injected provider with metamask we

would hit deploy and metamask would pop

up and say hey do you want to send this

transaction and that my friends is the

key to our next step to deploy this

contract we must build we must stick

this in a transaction and this is how

we're going to learn exactly what even

is a transaction and how can we create

one now this will be one of the few

times we actually manually create the

transaction ourselves and in the future

we will use tools that will essentially

automatically create these transactions

for us but to really understand what's

going on when we call a function or


deploy a contract we need to build our

own custom manually deployed transaction

so we've seen these transactions happen

whenever we call a function or deploy a

contract but like what what are they

really so if you go to the ethereum.org

website there's a lot more information

about what transactions really are and

you can see down here a submitted

transaction includes the following

information you can see there's a from

address a to address a signature which

is something we learned way way way way

back in blockchain Basics when we

learned about public and private keys

and hashing and all that stuff it has a

nuns which again we learned way back in

blockchain Basics which is going to be a

sequentially incrementing counter which

indicates the transaction number aka the

ID of the transaction it has a value

which is that message. value the amount

of money sent with the transaction you

have input data which oh we've we've

seen that before right if I call deploy

get this crazy hex data down here this

is the input data for the transaction

you have gas limit which we have gas

limit and Max prity fee per gas and Max

Fe per gas which is related to all the


gas stuff and if you scroll down a

little bit more you'll see the

transaction object will look something

like this and this is kind of a minimal

example of a Json or a JavaScript object

notation transaction it has no real

inputs or anything here having done this

such a long time I can very briefly tell

you exactly what this is doing all this

is doing is sending this much way to

this address from this address that's

pretty much it this is an unsigned

transaction here there's no signatures

this is basically a regular transaction

object that somebody would then need to

sign an ethereum client like G would

usually handle the signing process or

your mamass will handle the signing

process or our python would handle the

signing process so in gu you would call

this account sign transaction which

would go ahead and sign it and result in

this signed transaction we aren't going

to use gu we're going to use Python to

sign our transactions here let me zoom

out just here oh my God that's also

terrible we're going to use Python to

sign our transactions but it'll result

in this signed transaction so if you


scroll down in here this is an example

of a sign transaction which has pretty

much all the exact same pieces right it

has nuns Max for gas Max party f for gas

gas blah blah blah but then it has this

other stuff like v r and s now this VR

and S are the components of your

signature once you sign a transaction

you get these VR and S's and these are

the things that we learned way way way

back in the public private key signing

these are what people use to verify that

it was indeed signed by whoever is

signing it I know it's a little bit

confusing if this goes over your head a

little bit right now don't worry too

much about it and the hash is obviously

the hash of the transaction and then the

raw section right here is the the

recursive length prefix or the rlp

encoded form that you can learn more

about here now this is kind of a lot of

low-level signy stuff and there's kind

of a lot here now there's a lot of kind

of this lowlevel stuff here and this

vrns thing can be a little bit

overwhelming and confusing at first but

we're going to make it really simple

basically for us to construct a trans

action we want to create this object


with a from gas all these gas parameters

input NS to and value so we want to set

up and create a transaction with all of

this stuff in

here so to get started creating our own

transaction let's create an object

called transaction and we'll do equals

and then we'll just make it be blank for

now do a little print line saying

building the transaction dot dot dot so

what are some of the things that we need

in this transaction well looking back

here okay we're probably going to need a

from from we're going to skip this for

now you'll see why in a second okay what

else do we need okay we need a two who

are we going to send this

two uh okay that's a little confusing

what what address are we sending this

this to well well we're going to come

back to that as well what else do we

need okay we need we need gas okay

that's something I understand we need

gas okay um but but but how much gas do

we want to we want to send well so this

is where I'm going to help you out a lot

we could 100% manually create our

transaction like this but since we have

our favorites contract set up in this


web 3. contract we can cheat a little

bit what I can do is I can say

transaction equals favorites contract.

constructor. build

underscore transaction and what this

will do is it'll help automatically

populate a lot of those fields so let's

do a little breakpoint here and let's

run python deploy favorites.

piy uh oh we ran into this issue nonone

type object was not iterable candidates

equals ABI for ABI in contract type if

ABI equals Constructor oh well we for

well we we gave our contract the bite

code we forgot to give our contract

object the ABI remember that application

binary interface we can get that pretty

easily by backing the compilation

details we can just do comma excuse me

we do comma ABI and then in compilation

in the creating of the contract we can

do comma Abbi equals compilation details

ABI and then if we print um excuse me if

we print the compilation details again

let me clear run this again let me

scroll out we're still going to run into

issue and we're going to fix that in

just a second if we scroll up at least

well scroll up pretty far we can see ah

okay we have the bite code and now We


additionally have this ABI section oh

okay now it's formatted horribly but at

least this is the ABI now in this ABI

there's a Constructor object somewhere

um there's kind of a lot of words in

here and I'd have to take some time to

look through it ah okay right here

Constructor and when we call this

Constructor function on our contract

it's going to help us build the

transaction with the Constructor for us

and this eror down here is telling us oh

uh I couldn't connect to this endpoint

this is because we shut down Anvil so

I'm going to hit this little plus to

create a new terminal I'm going to type

in anvil in here go back over here I'm

going to clear we going to run this

command again and okay now we have this

printing out we have the ABI we don't

have any errors and we're in this little

breakpoint section here if I copy paste

transaction and paste it in here you can

see I have this object with a lot of

values already populated here let's take

a look what is already populated here

with this build transaction function

which takes our Constructor and turns it

into a transaction so we have value of


zero because we don't send any value

with this we have gas so it's estimating

how expensive it is to send this

transaction how much gas is it going to

cost to deploy our favorites contract it

has Max parity fee gas Max fee per gas

which is more gas stuff it has the chain

ID which it actually got from our Anvil

instance and if you look at Anvil you

might even see this eth chain ID so and

any time you see any of these lines pop

up under that listening on 127.0.0.1

blah blah blah any line or any word is

representing us interacting with the

blockchain so these are some of the RPC

calls being called on Anvil you don't

really need to know what these you don't

really need to know what these are but

just anytime you see stuff pop up on

this screen and Anvil it means that

somebody started making calls or

interacting with this blockchain or

interacting with our locally running

Anvil node and we see all these lines

here because it was us interacting with

the blockchain node so our python code

actually said hey uh Anvil what is your

chain ID can I get that please oh oh

it's

31337 great this data field that we have


here this is exactly the bite code that

we gave to our favorites contract object

and then our two field is kind of

confusing our two field is just B two

quotes what's going on here now if this

breakpoint thing is confusing to you by

the way you can just quit

out uh and then just

type print transaction instead

clear clear terminal and then rerun and

you know just get an output like this if

that's if that's simpler for you than

using the breakpoint

here so why is this B empty well

whenever you want to deploy a contract

in the evm ecosystem you just make the

two section of your transaction blank so

if I were to take this transaction

object I could even update my two here

so I could say transaction of two equals

and then I could even you know grab this

address in my metamask I could say 2

equals this and then print the

transaction let's clear the terminal

rerun now in my transaction object the

two has this address since we've updated

the two in our transaction object this

would no longer deploy a contract it

would send this random jarble of data to


this wallet address and this wallet

address would go uh cool bro like uh I

don't what you want me to do with that

and we would not deploy a contract so

let's delete that line let's rerun this

in order to deploy a contract the two

field of your transaction is going to be

blank this data in here defines all the

information needed to deploy this

contract and there's a lot of really

cool stuff in here that we won't learn

in this course if you want to learn

what's going on at the hex level at the

super super low level you want to go to

cyphon updraft you go to courses the

assembly and formal verification course

will teach you more about exactly what's

going on at the hex and the bite code

level so great we're getting set up here

with a actual transaction let's clear

the terminal and let's go back up

here now it might be a good idea to

update some of the parameters in this

transaction for example one of the

things that we're going to need is this

nuts right where is it it's this nuts or

where's is this nuns which is the unique

number or the unique identifier

associated with this transaction so what

we might do to help customize this


transaction and make it actually work is

we could get the nuns by saying NS

equals and then actually let me just run

this again as of right now there's no

nuns in here so we're going to need to

give it a nuns we could say nuns equals

count of whatever your address is so in

order to get the nuts we need to get the

address that we're actually going to use

to deploy this so for now I'm going to

make your life a little bit easier we're

going to go over to Anvil and if we

scroll up in here it actually gives us

this available account this address here

and for now we're going to use this as

our address we're going to change this

very soon so this is a temporary measure

we're taking at the top of our code in

all caps we'll say my address equals and

then paste this string in here and to

get the nuns of this address you just

say nuns web3 or w3g transaction count

my address and now that we have the nuns

let me delete this we can now say

transaction

of

nuns equals n NS like this another thing

we can do is we can actually do that

directly in this build transaction


function we could put the little

brackets in here and we would just say

nuns is set to nuns now I know this is

not the equal sign this is a colon but

this is a dictionary object and this is

how you kind of set stuff off as a

dictionary you'll use this pretty often

the more you use Python the better

you'll get here now if we print out the

transaction down here we go back to zsh

We Do a little clear run python deploy

favorites. py pull this up we scroll

through here we now see that we do

indeed have a nuns of zero now it's

important that we do this web 3. E.G

transaction count instead of just

setting the nuns directly to zero here

if we were to switch chains what do you

think would happen well on different

chains you're going to have a different

nuts you're going to send a different

number of transactions on different

chains so you always want to do this web

3. that get trans action count and most

tooling most monitor day tooling

automatically does this whenever you

send a transaction with metamask under

the hood it's automatically grabbing

this nuns itself and that way we always

have a dynamic nuts now in here we would


also want to do finally from my address

oops from should be in quotes from my

address it's probably a good idea as

well to set a gas price which we can get

again from this tooling W3 e. gas price

or if you want to manually set a gas

price because you're certain the gas

price is going to come down soon or if

you want to send make your gas price

crazy high you know you can do whatever

that you want but it's usually most

advised to just do it like this we could

also manually set the chain ID if we

wanted we could change the chain ID to

something crazy our transaction would

fail so we probably don't want to do

that but if we wanted to we could this

is where you can customize your

transaction to do pretty much whatever

you want and this is some of the power

of doing this manual transaction

building at the low level is we can

customize our transactions to do

whatever we want but again let's just

run this one more time we can see the

transaction object that we've created so

far value gas train nuns from is now

this new address gas price data gas

price and then we finally have data here


oh gas price and it's giving us what's

probably going to be a good gas price

here and if you go back to Anvil it's

figuring out that gas price by doing

this estimate gas function here and

again this data is going to be the raw

compiled data of our Viper contract if

we were super hardos we could even

manually create this and just you know

I'm even just going to copy this we

could just say transaction equals and

then boom and then paste it in like that

we could 100% manually create our

transaction object like this but that's

kind of silly so we're going to do it

like this because this code creates a

lot of the transaction data for us a lot

more

autonomously okay great so we've created

our transaction object which is going to

include the code for our Viper contract

we're going to send it to the zero

address because on the evm world that's

how you deploy smart contracts and we're

ready to go well almost what do we need

to do we need to sign it remember that

that's how this whole blockchain thing

works is you sign your transactions with

your private key so we're going to use

the web 3 tooling to automatically sign


this so we'll do W3

doe.

count. sign transaction and we'll add

our

transaction action object in here and

now we're going to have to sign it

finally with the private key now as as

of right now we don't have a private key

but I'm going to do something horrible

that we're going to do just for now and

then I want you to never ever ever ever

ever do this again it's okay that we're

doing it for now because we're using an

anvil private key and these are very

well-known private keys but we're going

to copy this private key and right in

our code we're going to do private key

equals paste it in here and then now

down here to sign our transaction we're

going to say web3 e. account. sign

transaction transaction comma private

key equals private key like this and

we're going to set this to a variable

called signed transaction now what we

just did was something that if you

continue to do this you will get

destroyed in web 3 just full stop I

don't make the rules that is just what

will happen guaranteed which was first


off code our private key right into one

of our scripts and then number two leave

it in plain text it's okay for right now

because this is an anvil private key and

these are well-known publicly known

private keys so it's fine for now but we

should never do this again and I'll

explain why in a minute but let's keep

going let's do print signed transaction

so we can see what this transaction

object looks like now that it's actually

signed let's pull upart terminal let's

go over to the zsh do a little clear

here pull this up up up we'll run uh I'm

in my virtual environment so I can run

python deploy favorites sty hit

enter now we can see building the

transaction and we can see this sign

transaction object which has this raw

transaction of hexes which has all this

raw data here and then at the bottom we

see this R this s and this V and these

are the three components of the

signature that allow the blockchain

network to verify that this transaction

was actually s sent by this address

whose private key is this private key so

these have the same private key same

thing with you know one and one this is

the address this is the private key you


know two and two so on and so forth so

now we have a raw signed transaction

what's even more cool about this is we

just have assigned transaction but we

haven't actually sent it yet we haven't

sent it to the blockchain it's literally

just like it's l just like sitting in

our terminal here like anybody could

literally take this transaction now that

it's signed

and go execute it so Additionally you

don't really want to have sign

transactions lying around so try not to

do that as well

but let's talk about what we just did up

here and how horrible it is and how can

we fix this now like I said in the last

lesson we never want to have number one

our private Keys directly in our scripts

and then number two we never want to

have them in plain text either having

them in plain text basically just means

not encrypted because if we accidentally

push this up to GitHub if we

accidentally show our screen for a split

second to somebody else they will take

our somebody could take our private key

and essentially steal all of our money

again this one that I'm showing you


right now it's not the end of the world

because everyone knows about this one as

of 2024 the number one attack Vector in

all of web 3 was Private key leaks

according to Peter and block threat

intelligence stolen private Keys

accounted for half half a billion

dollars in 2024 half a billion dollars

of damage and actually that ticker is

still rolling because I a recording it's

not the end of 2024 so we want to make

sure we don't add to that statistic and

we don't expose our private key and lose

our funds so now I want you to do

something for me I want you to create a

new file called Promise promise. MD and

in here I want you to write this I know

this is kind of silly but I'm being

serious you should actually write this

down and you should write I promise to

never place my plain text private key

associated with real money anywhere I

will always encrypt my private keys and

never share even the encrypted Keys

write this I want you to write this

because this is incredibly important I

want to drill this into your head so

that you do not add to the statistic of

stolen money and stolen private keys

half a billion dollars has been stolen


from people exposing their private keys

and I've seen new developers who have a

lot of money and not a lot of care for

where their money goes lose a lot of

money so we're doing this for now but

very soon we're going to change

this to help make this at least a little

bit better but still terrible I'm going

to show you what most tutorials today

are going to tell you what to do and I'm

going to tell you you should recognize

that they're doing this and that you

should not do this so what most

tutorials are going to tell you to do is

they're going to tell you that you

should make something called a EnV file

and they're going to tell you place all

of your sensitive information in here so

for example I'm going to copy paste my

address in my private key and I'm going

to place it into here do the toggle word

wrap I'm also going to take this and I'm

going to place that into here as well

under RPC URL equals and paste this in

here oh and you can't have spaces here

got to have these be right next to each

other now to pull out these what's

called environment variables up at the

top of our project we're going to import


we're going to download this package

called load. EnV or python. EnV we're

going to scroll down figure out how to

install this pipol python. EnV so since

we're using UV we're going to go ahead

and do clear um UV add paste this in

just to make sure it's actually getting

installed to a virtual environment UV

sync as well okay great now you'll

notice that this is kind of this gross

white color and there's no real nice

formatting here well we can change that

let's go to the extensions tab we'll

look up toml and we'll get this even

better toml vs code extension which

we'll go ahead we'll install this we'll

close this and now we see our p project.

toml is highlighted very nicely cool and

now that we have that up at our top here

we can say from. EnV import load. EnV

and right at the top of a file we can

say load. EnV like this and to get all

of these variables now we can say RPC UR

equals os. getv RBC URL we have to

import OS as well we can say my

address equals os. getet EnV my address

like so and we can say

private py equals os. getet

EnV private key like this so typically

this EnV will be someplace separate from


from the rest of your project and it'll

be included in your dog ignore and if

it's not in there add the

dot EnV into yourg ignore right now as

well and if you're following along and

this is a real private key I'm telling

you delete it right now do not use a a

private key associated with real funds

do not ever have a private key

associated with real money anywhere in

plain text I want to protect you I

really do anyways so this is what a lot

of tutorials are going to tell you what

to do and I'm going to tell you that

that is is for noobs and you are not

being taught how to be a noob you're

being taught how to become a pro you're

being taught how to become a badass so

what we can do is back in this deploy

favorites.i we're actually going to

rename this to deploy favorites

unsafe. py because this is an unsafe way

to work with private keys and in fact

we're even going to delete this file

delete the EnV at the end of this

tutorial and you should never ever ever

put your private key in aemv file ever

again got it makees sense great that's

my quick rant
here so we still haven't even learned

how to send the transaction yet all we

do all we have right now is a sign

transaction so now I'm going to show you

how to send the transaction and then I'm

going to show you how to encrypt the

private key so let's just go ahead let's

finish up sending this transaction then

I'm going to show you how to encrypt the

private key so that you never do this

ever again let's go ahead now we have

our sign transaction now we want to go

ahead and send it to send it we would

say uh we would do

w3.css response with a transaction hash

and we can say print my TX hash is and

I'm going to use an F string for this TX

hash and then this is just when we send

the transaction we actually have we

actually have to wait for the

transaction to complete to be included

in a block so we would say TX receipt

equals W3

do.we for transaction receipt of the TX

hash and once it's confirmed we can say

print F done contract deployed to txor

reed.

contract address and boom so let's go

ahead let's pull up our terminal make

sure our virtual environment is up make


sure Anvil is up and running and we can

run python deploy favoritz dopy no

switch fileer directory whoops let's do

python deploy favorites unsafe. py

because I just changed the name deploy

favorites unsafe. py we'll hit enter we

will now get this kind of crazy output

so we get the sign transaction yeah

we've seen that now we'll see the

transaction hash is this is the bite

code of the transaction hash we could

convert it from bytes to like a regular

transaction hash that we're familiar

with but whatever and then we see done

contract deployed to here and we have

successfully deployed our contract now

that it's actually deployed we could

then go ahead and interact with it and

learn how to build transactions to

interact with it but those are going to

be pretty much very similar to what we

just did here so you should be

incredibly proud of yourself for

deploying your first contract but don't

log off yet because I need to teach you

how to never ever ever do this again so

let's learn how to encrypt our private

key so that we do not ever do this again

moving forward we will be working with


tools that will automatically do this

encryption for us but let's learn how to

do it manually so that we know at least

how we can protect ourselves so like we

said as of right now our private key is

stored in this EMV file and this is not

good we do not want our private key

stored anywhere in plain text and what

say it should never be stored in plain

text what I mean by that is that your

private key should never be in a place

where if a human just reads it or a

human reads the file or a computer reads

the file they will get the private key

it should always be stored in a manner

where if a human or a machine reads that

file they don't immediately get the

private key so we want to encrypt it we

want to shroud it we want to we want it

to be such that if somebody does come

across this file or you actually

accidentally do show the file where this

key is stored they just see garble deg

and they can't extract what the private

key is by looking at the data so what we

can do is let's create a new file called

encrypt key dopy and we're going to

write a script to encrypt our private

key ourselves like I said later on we

will have tools that will do this for us


but you should absolutely be good at

encrypting your private key so we have

this encrypt uh key. pi and let's go

ahead and let's do some basic python

stuff like if uncore uncore name uncore

equals equals uncore maincore uncore

Main and we'll create a new def main

function like this and we'll just say

pass for now now this encrypt key. Pi

python file is going to be how we

encrypt our key to encrypt it we're

going to use this python built-in tool

called get pass which is a portable

password input we're going to have our

terminal actually ask us for the private

key so that we don't ever have to store

it in aemv in fact right now take it out

get any get rid of any reference to your

plain text private key anywhere get rid

of it great now back over here we can

use this get pass library in our code by

saying import get pass we don't have to

install anything because this actually

comes directly with a lot of more modern

versions of python what we could do in

our main function is we could say

private key equals get pass. getpass

enter your private key and this is very

similar to the input command in Python


where it's going to prompt us to input

our private key and then it's going to

store it like so so if I save this let

me clear this out and now I run python

encrypt and I hit tab again encrypt key.

piy just says enter your private key I'm

going to just type a bunch of nonsense

and we hit enter and it looks like this

what's cool is that it hides whatever

you type in here so let me clear it out

python encrypt key. I'm literally

smashing my keyboard with my face you

guys can't see me because I'm off screen

I hit enter nothing was shown this is

what we want because we don't want to

accidentally show or expose our private

key if someone is looking at our screen

that we don't want looking at our screen

enter your private key then we're going

to transform this private key from a

private key into a eth account and we're

going to use a library that's going to

help encrypt it for us so when we

installed web 3py it came with this

thing called eth account and we can say

from eth account import account and then

we can

say my account equals account. from

Key private

oops private key like so so this will


create an account for us then we're

going to want to make a password so

we'll say password equals get pass.

getet pass get

pass enter your password or excuse me

enter a password and we'll do back sln

this is the new line character so it

allow us to enter our password on a new

line and now this will mean we have the

private key we have a password for the

private key and now we're going to

encrypt the private key with the

password so we'll say encrypted count

equals my account copy paste. encrypt

with the password like this now we're

going to take this encrypted account and

save it to a file so that we can

reference it later so we'll do a little

print F saving to some key store path

some path some file some directory I'm

going to say key

store path

equals. key store. Json and we're going

to make this a path

object so path is a very helpful tool in

Python to work with different paths and

it comes directly with python we don't

have to install anything we just say

from path lib import path


and I'll explain kind of more what this

means in a second so we'll do saving to

using an FST string key store path dot

dot dot and we'll say with keystore

path. openen W this do open means we're

going to open this doke. Json file which

we are basically going to create with

this command here the w means write as

FP which is going to stand for file path

we'll say Jason

dump encrypted account

FP and we're going to import Json as

well import Json this comes directly

with python out of the box as well so I

know I just kind of talked a lot and

this might not make a ton of sense so

let's go ahead and let's run this

command we'll see what happens and then

I'll explain again what's going on here

so pull up the terminal python

encrypt key. piy hit enter it's going to

say enter your private key we'll go over

to Anvil here we'll scroll all the way

to the top almost all the way to the top

we'll grab this private key we'll go

back to python python terminal we'll hit

command V or control V we'll hit enter

it won't show anything we want that then

we're going to give it a password I'm

going to give a very crappy password of


password and then it'll say saving

to.key store.js and then it will finish

now if you look in your files over here

you'll see there's this key store. Json

and if you hit command shift p or

control shift p and type format format

document you can see this Json object

here and this is your encrypted private

key all of this stuff in here has is

related to encrypting the private key

the only thing that's not encrypted is

we have its address right at the top of

the file however all this other stuff is

the encrypted private key

now even the encrypted private key you

don't want to expose so if you are going

to manually do encrypted stuff if you

are going to manually encrypt Keys be

sure to add these to theg ignore file

and ideally you want to take them out of

the directory again we're working with

an anvil private key right now and

everyone knows them so it's not the end

of the world and there's a good chance

you don't even know what the dot get

ignored does but I want to start

drilling good habits into you right now

so so let me just kind of re-explain

what's going on here so first we enter


our private key when it prompts us we

then stick it into this account object

which has some helpful methods for

encrypting Keys We input a password as

well using get pass. getpass and we use

that password that we just got to

encrypt our private key and then since

we made this what's called a path object

we can call this open command directly

on a path object and we can just dump

this encrypted account which is

essentially just this Json object which

is essentially like what this is this is

known as a Json object we do json. dump

the encrypted account into the file path

into this dokey store. Json and now this

is the encrypted private key which is

much much better because again it's no

longer in plain text and that's what we

always want to avoid if you ever see a

private key like this

anywhere your heart should start to

flutter a little bit again this is the

Anvil private key so it's

okay so now that we've encrypted the

private key how do we actually use it

how do we actually decrypt the private

key thanks Patrick for for doing all

this crazy work but like what do we do

now well let's go back to our deploy


favorites unsafe file and let's scroll

to the bottom and let's create a new

function we'll create def decrypt

key so what we want to do is we want to

grab this key store path and decrypt it

so the first thing we're going to need

is that key store path and we can

actually import it from this encrypt

key. py file we can import this key

store path from here into this file we

could say from encrypt key right because

the name of this files encrypt key. we'd

say from En encrypt key import key store

path and down in our decrypt key

function we could say with open key

store path comma R which stands for read

as

FP encrypted account equals

fp.jpg

pass .g get pass enter your password

like this and that means we have to

import get pass we'll scroll back up to

the top we'll say import get pass we'll

scroll back to the bottom great password

equals get pass. get pass enter your

password this will prompt us for the

password here once we have the password

we could say key equals account. decrypt

and this account. decrypt is going to


again come from this eth accounts thing

so if you even just want to copy this

line come over here paste it in from eth

account import account scroll back down

to the bottom key equals account.

decrypt we'll pass in the encrypted

account and the password and then we'll

say print

decrypted

key we'll have this function return the

key and if we want to do some typ pints

in here very similar to Viper we can say

returns s strr which means returns

string so this function is now a way for

us to decrypt the key let's scroll up

and let's see where we're reading in the

private key this is how we're reading it

in we no longer want to do that what we

want to do instead to get the private

key is we're going to do RP crl like

this we're going do my address like this

what we can do is before we need the

private key which I'm going to go ahead

and toggle word wrap again in here I'm

going to say private key equals decrypt

key oop decrypt key we're going to make

it lowercase because it's no longer you

know like a constant variable

essentially at the top of the file and

then we're going to say private key


equals this lowercase private key and

now we should be good to

go before I run this I'm now going to

change this from deploy favorites unsafe

to just deploy favorites because now it

is much safer I'm going to pull up the

terminal Anvil is still running going to

clear the terminal I'm currently not in

my virtual environment so you know what

I'm going to activate source. VMV bin

activate and we're going to run python

deploy favorites. py I'm hitting tab

once again now we're getting print out

let's read the Viper code and deploy it

it's printing out the compilation

details we have building the transaction

it says enter your password and here's

where I'm going to use the same password

I used to encrypt it and you'll notice

once again it doesn't show up on the

terminal here once it's done I hit enter

and boom we get decrypted key we get the

sign transaction printed out with the

where is it the r s and the V we get

done contract deployed to blah blah blah

if we go to Anvil we can also see a

successful transaction has been posted

the reason went through this is because

I want you to always know that there is


always a way to encrypt your private key

you will get people who tell you oh it's

too hard to encrypt your private key so

we're just going to skip it and your

alarm Bells should go crazy and you

should go this person is a noob they are

a noob I need to encrypt my private key

I'm not going to leave it in plain text

how dare you recommend that I do that

okay there's always a way to encrypt and

decrypt your private keys and if a tool

doesn't have support for it that's an

issue so I would like you to I would

like you to not be part of the half a

million dollars that has been lost and

exposed private Keys

great so once again I know I'm

belaboring the point here I know I'm

going over and over and over again on

this but this is the statistic this is

the reality almost half a billion

dollars this past year was lost in

private key leaks and I want to drill

this in so hard that if you go over to

the Maas andf course or the GitHub repo

associated with this course you go to

the discussions tab there is a pledge

called the Dov pledge and I'm going to

read it to you here yes I'm going to

literally read this to you right now


because I want you to understand every

single line of this pledge every single

line in here and then additionally after

you have after you've understood every

single line in here I want you to scroll

to the bottom and accept this pledge by

saying I will be safe and commenting on

it here this is a brand new course this

is a brand new tutorial so as of

recording I'm the only one on here

however we also have a version of this

Pledge on The Foundry full course or the

solidity full course and if you scroll

down in here you can see this has 355

comments 143 replies there's almost 500

developers who have taken this pledge

and I have a version of the pledge in a

JavaScript Edition in a JavaScript

edition of this course and another

edition of this course so there's

several EnV pledges out there where

hundreds and hundreds of developers have

taken this pledge saying I will be safe

so I'm going to read this to you now and

I want you to really ask yourself do I

understand this if you don't understand

this you might want to make a discussion

yourself and say hey I didn't understand

this line of the EnV pledge because if


you don't understand every single line

in this pledge that potentially could be

how you slip up and how you expose your

private key and we as developers we need

to be good at storing and securing our

private Keys it's going to be a little

dry here but here it goes I solemnly

swear that I will never place a private

key or secret phrase or pneumonic in

aemv file that is associated with real

funds basically that means in your

metamask here your private key of your

metamask or your pneumonic associated

with all your accounts you will never

place anywhere I will only place private

keys in aemv file that have only

test at eth link or other

cryptocurrencies when I'm testing and

developing I will use a different wallet

a different wallet than the one

associated with my real funds I aware

that if I forget a DOT get ignore and

push my keyphrase up to GitHub even for

a split second or show my keyphrase to

the internet for even a split second it

should be considered compromised and I

should move all my funds immediately

we're going to learn about what dog

ignores are very soon once we start

working with GitHub if I am unsure if my


account has real funds in it I will

assume it has real funds in it if I

assume it has real funds in it I will

not use it for developing purposes I

aware that even if I hit add account on

my metamask or other eth wallet I will

get a new private key but it will share

the same secret phrase pneumonic of the

other accounts generated in that

metamask or other eth wallets these are

some additions that I added on later for

this course I will only use the the

funds associated with a brand new

neverbe used metamask or other eth

wallet I'm aware that my account

associated with my private key is the

same on test Nets as it is on Main Nets

if I must use a private key associated

with real funds in the future until I am

100% sure of what I'm doing I will

always either encrypt the private key

myself in such a way as what Patrick

taught me which is what we just went

over use the built-in functionality of

moccasin to encrypt private Keys once we

move over to moccasin we'll see how to

encrypt private Keys using the moccosin

tool and finally use the command line

way to pass private keys and delete my


command line history right after only as

a last option so this should be the last

option ideally you're using encrypted

Keys If I never actually deploy anything

to M my myself or work with a private

key with real funds I do not need to be

concerned this final line is basically

to tell you developers who are saying

like hey Patrick like I'm broke should I

panic no like you'll be fine if you

don't have any money to lose then like

it doesn't matter just know that this

metamask this wallet that you're using

for this course is a test is a fake

wallet and you should never ever ever

put real funds in it if you want to make

a new wallet it's usually a good idea to

maybe choose a different browser choose

a different profile in a browser choose

a completely brand new metamask or

wallet specific for real funds or even

better maybe a hardware wallet or the

likes so come to down here type in I

will be safe either as a reply or as a

comment whatever works better for you

and then I highly recommend if you've

taken this fund I would love if you you

know were to copy the link go to x.com

or Twitter or whatever post a little

tweet saying I will be safe I have


decided to take the EMV pledge and then

you know tag me at and then you know

maybe tag me at Patrick ALC maybe tag

Cypher aits or whatever you want to do

here so anyways now you know once we

move on to occas we will probably come

back to this again very briefly just to

again reiterate this dog ignore stuff

and make sure we understand the new

pieces but anyways thank you for taking

this pledge and thank you for taking

yourself seriously all right I'm going

to go ahead and delete my

terminal now for the most part we are

all done we're all set here we have

officially pretty much finished our

final project here the only thing we

didn't do do was we didn't actually

interact with the contract itself from

web 3py I originally said we were going

to do that but I decided not to cuz when

we move on to titanoboa we're going to

interact a little bit differently than

what's happening here and what the

really important thing was is I just

wanted to show you what signing and

sending a raw transaction looked like we

sent a transaction that deployed a

contract and remember everything that


changes state anything that updates the

blockchain is going to be sent in a

transaction action that you have to send

to the blockchain whether we're

deploying a contract we're calling a

function that updates some State on the

blockchain we're sending somebody else

value they all are just a transaction

and a transaction is basically just kind

of this this object here well there's

more than just what's in here if you if

you want to come back to say hey what's

a sample transaction look like you can

come back here maybe just type in print

transaction rerun this and see what it

looks like what I want you to do for

your Workshop here if we come back over

to the mckas and full course we'll

scroll on down where is it to the scroll

on down to the section for the web 3 Pi

favorite list I'm giving you a workshop

I want you to to deploy the favorites.

contract to your tenderly RPC URL using

this setup in here we just taught you

how to do it to deploy to Anvil with the

RPC URL being the Anvil RPC URL to

deploy to tenderly there's going to be a

couple things that you need to do

obviously you want to look at the RPC

URL here you want to make sure you're


working with a correct wallet and you

should see the contract deployed in the

contracts tab or in the Explorer Etc

optionally if you want to go the extra

mile you can also deploy this to spolia

and if you deploy it to spolia you

should see it on spolia ether scan or

another popular Explorer is going to be

the block Scout Explorer so your

Workshop that I want you to do on your

own is to deploy figure out how to

deploy the favorites. vi contract to the

tenderly RPC URL and as you're doing

that I want you to scroll on down here

and you should look at these transaction

objects right as you're deploying them

you should look at them hey what's this

transaction object what's the nuns

what's the address what's the gas price

is it different than it was on Anvil

really absorb what it feels like to send

this contract to a different network so

that's going to be your Workshop that's

going to be your exercise for this if

you want to go ahead and pause the video

feel free to do so however if you're

tenderly uh free trial rent out then the

workshop is to deploy favorites. VI

contract to the Anvil locally running


chain with a different wallet address

and a new encrypted key try to deploy it

yourself using a different wallet

address maybe if you even want to maybe

CH try to change some of the parameters

which parameters can you change why can

you change them can you change any of

them can you change all of them what if

you change the gas price to one fiddle

with this do something yourself and then

come

back all right welcome back were you

able to successfully deploy to Anvil or

to tenderly I hope you were and if you

weren't that's also okay be sure to come

to the discussions tab ask questions ask

your AI friends Etc because you really

want to understand this so that you can

go out and you can be successful as a

smart contract developer so it's okay

that you couldn't do it but don't give

up you should definitely do it you

should go back and figure out how to to

do it but it's okay if you get stuck

because that happens in coding you get

stuck it's okay ask questions ask your

AI Friends Ask discussions ask forums

Etc jump into the Discord and persevere

so now we learned a lot of stuff just

here and if you're new to python we also


learned a lot of python as well so

you're learning smart contract

development and python development at

the same time so let's do a bit of a

recap of all the amazing things that we

learned in this section because oh my

goodness there was a ton so first of all

if you're newer to python well we

learned a lot of really cool python

stuff we learned that whenever you call

a python file you're secretly setting

thisor this Dunder name to Dunder Main

and a lot of more professional python

setups will have this if Dunder name

equals equals Dunder main run some

function we learned how to compile our

favorite stuff ey contract from the

command line using the Viper command

line tool Viper favorites. we enter and

we can see the compiled code of our

favorites.i Viper Smart contract we

learn that we can also compile our Viper

contract in code we can use the Viper

package both as a command line or a

terminal utility and we can use it

inside of our python code as well we

imported this function called compile

code into our python code here so that

we could first first open up the


favorites file read the contests and

then compile the code and get both the

bite code and the API or the application

binary interface we then connected to an

RPC URL oh and I just realized this is

actually a mistake boom that should be

like that whoops well we connected to an

RPC URL which in this case was Anvil

which we got from

ourv and we also got our address from

ourm view file which these are much less

sensitive information so this is is a

little bit more okay to have in plain

Tex here we connected to our blockchain

node and then we turned our bite code in

API into kind of this holder favorites

contract that wasn't deployed yet

because we haven't sent a transaction we

had to manually build the transaction we

first got the nuns which is the

transaction count or the number only

used once and we added it to our

transaction as well as we use this

constructor. build transaction to help

populate our transaction using the nuns

the from which is my address gas price

and any other customizations that we put

in here then we decrypted our private

key using this decrypt key function but

before we did that we learned how to


actually encrypt our private key now

this was the manual way that we learned

how to do it and in the future we're

going to be using tools that already

have this functionality built in but

it's good to know what's going on under

the hood of those tools as well we

encrypted our key to a.key store.js key

store pth path and then we decrypted it

right in our script we were prompted hey

uh can you send me your private key just

to show you it again we do UV run python

deploy favorites favorites. py oops I

actually have to start envelope again

that's what that error is going to be

let's hit up again rerun this and we'll

get prompted enter your password I'm

going to hit contrl C to quit out of it

because I don't really want to enter my

password here um but we had enter our

password to decrypt the key this way we

always always always keep our private

key encrypted and not in plain text once

we got our private key we can use that

to finally sign the transaction we did

web 3. eign transaction when we printed

out the transaction we saw this kind of

weird VR signature stuff we didn't

really Le learn too much about that all


we really needed to know is that those

are the components of a signature that's

how other blockchain nodes can know that

the transaction was actually signed and

we get a transaction hash as well then

we have the signed transaction we

actually have to send it to the

blockchain so we called this send raw

transaction which will send it to our

blockchain node which in this case was

Anvil and if you want the extra mile it

will also be in tenderly then we waited

for the transaction to finish and then

we looked for the contract address that

was deployed and printed it out we also

learned some really fun python stuff if

you're unfamiliar with python we learn

that we can run

uvvv source. venv bin activate to enter

a python virtual environment we learned

that whenever we do UV add and then some

python package it'll add it to our p

project. tommo and then to make sure our

virtual environment has all of these we

can run UV sync and it'll install all of

these to the virtual environment if

they're not already added then I'll go

ahead and clear if we're not in our

virtual environment and I hit deactivate

I can still run a script using the


dependencies by just doing UV run python

deploy favorites of Pi Etc so if I'm not

inside of my virtual environment I can

use UV run python if I'm inside my

virtual environment I can just use the

python keyword and for me and for me I

don't even have the python keyword in my

Global python environment but when I do

source. VNV bin activate

I do have the python keyword in my

virtual environment here we also learned

about different virtual environments we

learned that the terminal will point to

kind of the active python environment

but if we do UV tool install Viper it'll

install Viper in its own isolated

virtual environment and for sensitive

tools like a compiler like the Viper

compiler we really want these to be in

their own isolated environments we also

learn that for vs code we need to tell

vs code which python we wanted to use to

format our code here and we can do that

by just clicking this button here and

choosing The Interpreter path in this

little dropdown and for most of what

we're doing in this course we always

want to use whatever the venv is going

to be so we've learned an absolute ton


and you should be incredibly proud of

yourself for getting this far if you're

new to python we just learned a ton of

python and if you're new to blockchain

well we just learned a lot of the low

levels of what a transaction even looks

like and how the tools that we're going

to be using in the future are going to

be sending transactions under the hood

we're going to be moving on to titanoboa

to show you what titanoboa is doing and

then onto moccasin which uses titanoboa

under the hood you should be incredibly

proud of yourself for making this farm

so I want you to give yourself a little

Pat in the back now is a great time to

go for a walk grab some ice cream maybe

grab a coffee but if it's too late you

know don't grab a coffee and you should

be incredibly proud of yourself for

getting this far and I'll see you in the

next one congrat congratulations on

finishing this

section all right welcome back to the

next section we're going to be leveling

up your python skills in this one if you

are in the gabo associated with this

course we can scroll down let's go to

the next section Titanoboa favorites

list now I'm going to go ahead and show


you and walk you through what we're

going to be learning in this project so

that you can be primed with the

information of what you're going to

learn of course the full code for this

section is available here and this is

the project that we're going to be

building now this is actually going to

be very similar to what we did in the

last section right with the web 3.y

favorites list however we're going to be

moving off of web 3.y over to this tool

that I've mentioned several times now

called titanoboa so here is the

finalized code of the project here and

we're going to have two main files we're

going to have a deploy favorites pm and

then a deploy favorites so very similar

to what we did last time now the main

difference like I said is in here

instead of manually creating these

transactions we're just going to use boa

or titano boa to deploy to deploy a

smart contract with titanoboa all you

need is Alliance that looks like this

that is it no manual creation of the

transaction you do boa load and the name

of the file and boom that deploys a

contract and to do this we don't even


need to run an anvil instance if I pull

up my terminal here I'll first get

started by doing uvv EnV UV sync as well

just going to go ahead and download

everything activate my virtual

environment because of course I'm going

to do that now I can run python

deploy

bitscore Pym this will go ahead and

compile our favorites contract we have

we're printing it out here we we're

printing out some information about the

contract and that's it so just like that

we deployed it to kind of this fake

pythonic blockchain called the PM and

we're going to learn about how that's

going to be super super helpful for us

to test deploying our smart contracts

remember in the last section we actually

deployed to we actually deploy to this

thing called Anvil right remember we ran

Anvil we had this kind of fake chain if

you're going to deploy to this pibm

network you don't even need to run Anvil

which is going to make our development

process much quicker much easier to test

and much faster however we're also going

to show you how to run an anvil node and

then using boa oh let me go ahead and

activate the virtual environment here


and then using boa I'm going to run

python deploy favorites. py not to the

pi evm anymore and we're going to get a

print out like this where it says

transaction broadcasted and we did a

bunch of transactions on our Anvil chain

transaction broadcasted we mined a block

we deployed a contract and then we're

going to call some of those functions

that are in the favorites contract so

let me hide the terminal here if we look

at our deploy favorites python file here

let me zoom out a little bit we scroll

down we're going to deploy the contract

in a single line which is going to going

to be much nicer than what we did last

time then again in a single line we're

going to call the store function on the

favorites contract so let's go back to

favorites it's got this store function

we're going to call store on it in a

single line of python and this is

actually going to send a transaction for

us then we can call retrieve on our

favorit contract and again if we scroll

down we have this retrieve function then

we're going to call add person and we're

going to be able to call to the list of

people so as you can see this fun


function our main function here does a

lot more it deploys the contract it

stores a number of the contract it reads

from the contract it stores a person in

the contract and yet it's still smaller

than what we did in the last section

this is because the Titanoboa tool is

going to give us a lot of power to

interact with and test our Viper Smart

contracts so and we're using this

section as a stepping stone to go from

raw python to this more advanced tool

titanoboa to the most advanced tool next

which is going to be moccasin which is

going to use this titanoboa under the

hood so all these commands that we're

going to learn here in titanoboa are

going to be helpful and important for

you when you finally move over to

moccasin and now that you've learned a

lot of the basics as well of working

with python and working with the

blockchain this section should actually

be pretty quick because we're just going

to be learning the Titanoboa tool as

always if you get stuck if you get lost

if you have questions you can come over

to the GitHub repo associated with this

this course you go to the discussions

Tab and then additionally be sure to use


some type of AI buddy let's go to the

co-pilot chat here you can ask co-pilot

you can work with Claude you can work

with whatever AI that you prefer to work

with AI are great at understanding

python so you should use them whenever

we go over something that is confusing

or doesn't make sense and now that we're

going to be getting into more advanced

python here the beauty of AI is that if

anything we write doesn't make sense to

you you should copy that line of code

paste it into an AI and say what is this

code doing and ask an AI to explain it

to you because you need to know what

every single line that we're going to be

going over here does now I'll tell you

some sections you don't need to know and

I'll give you a heads up ahead of time

that you don't need to know them but the

beauty of AI is that it makes learning

so much easier because you're always

going to basically have a buddy who kind

of knows some stuff I think of AI like a

very dumb college graduate they know a

lot of really good stuff but in practice

they kind of screw things up but most of

the time it's still better than having

nobody by your side so use AI use these


tools to help your Learning Journey so

with that being said let's go ahead and

let's get

started all right so now I'm back in my

vs code in my MOX CU folder here if I do

a little PWD I can see I'm inside of MOX

cuu if do a little LS I can see I have

my readme where I've written my goals

I've have Python and cyphon updraft and

we have the completed section web 3 Pi

favorites Cypher updraft if you are

inside of this web 3 Pi favorites Cypher

updraft again I'm going to do PWD mine

will look a little different than yours

you can just do CD down down to CD down

a directory I'm going to type clear here

we're going to create a new folder here

with mkd which stands for again make

directory boa

favorits CU for cyon updraft and then

I'm going to hit code boa favorits

cyphon updraft or again you can do file

open and then open this folder I'm going

to hit enter since I have installed the

code command this will pop me up into a

new window here but again file open

folder open this folder works as well

now we're going to go ahead and get

started we're going to open up our

terminal here and we're going to create


create a new python project the same way

that we've been creating our python

projects so far we're going to start

with UV anit and as you can see once

again we're given a readme a p project.

toml which right now we have no

dependencies a little hello.py that

we're going to kind of ignore a. python

version which might be different

depending on what the default version of

your UV is and a get ignore which again

we'll learn about much later it might be

a good best practice for you to go ahead

and add Dot

into yourg ignore right from the get-go

pretty much always and again this is for

private Key Safety but since you just

took the pledge you're not going to put

your private key in plane text anymore

ARA so let's go ahead let's drop into

the read me and let's make a little read

me about what we're going to do so boa

favorites so this is going to be one of

our quicker sections we're going to go

ahead and learn to deploy our favorites

contract using titanoboa interact with

our contract using titanoboa deploy to

the pi evm Network also deploy to the

Anvil Network set the active EnV in boa


and then work with and switch accounts

and switch envs in Titan that probably

doesn't make sense to you right now but

it will in a minute so let's go ahead

let's set up our favorites. VI file the

same way we did it before we'll

rightclick new file

favorites. VI like so and we can go back

to the GitHub repo so assciated with

this course and I'm going to pull that

favorites. VI right from the boa

favorites you can also pull it from your

old folders you can pull it from

wherever you want we've already written

this we know what it does so I'm just

going to go ahead I'm going to copy and

past it into here and great my

formatting here is looking very nice

because I have the Viper

extension so this formats this looks

good to me okay cool I still have the

Viper compiler installed in its own

separ separate virtual environment right

I can check to see if I have it by doing

which Viper and I can see that I do have

it installed I can compile again using

Viper favorites. VI remember I'm

pressing tab to get that very quick auto

completion here I hit enter and I'm

getting the hex data for the compilation


of the contract so this looks correct to

me okay great next let's go ahead and

let's create our deploy favorites pm.

piy where we're going to learn the

basics of deploying this contract to the

PM

Network now the PM network is very

similar to Anvil when I type anvil in

here I get kind of this locally spun up

blockchain with you know all these

accounts I can cancel and you know I can

do all this stuff the pvm blockchain is

just like Anvil except I have way way

more control over it I can run Anvil I

can run Anvil here but I still have to

kind of take it of these accounts take

the private key send money around to

each other I have to get its RPC URL

down here I have to copy paste it into

my deploy scripts and stuff with the PM

you don't have to do any of that this is

kind of this very fake simulated

blockchain that exists for the duration

of a python script let me let me show

you what I mean in just a second so

let's go let's create a new file call it

deploy

favorites

pmpy and let's let go ahead let's get


started doing our little setup we'll do

if Dunder name equals equals Dunder

main then run main function which we

don't have defined yet we going to go to

the top we'll do def main I'll just do

print high for now to make sure it's

working pull up my terminal I'm going to

do UV venv to get a venv file here now

vs code says we notice a new environment

has been created do you want to select

it for the workspace folder and remember

how before we clicked this little button

and changed right if I click this we

changed to our we changed our venv to

this VV section if we had yes on that

little popup it would basically do the

same thing so I'm going to hit yes here

and now I see that vs code is going ah

we're working with this version of

python I'm going to make sure that the

syntax highlighting is correct so that's

how we know working with the correct

version of python here so anyways so we

have this virtual environment set up

here it is not active at the moment

we're going to activate it with source.

venv bin activate it looks like we are

active now I'm going to go ahead and now

run python because python comes in our

virtual environment I can even do python


D- version I can see it's python 3.13

yours might be a little bit different

but I'm going to run python deploy and

then I'm going to hit Tab and it just

autop populates and then we get the high

output here okay great so main is print

high let's change this print to let's

read in the Viper code and deploy it

like this and now what we want to do so

we want to import this titanoboa tool if

you're looking for a link to it on the

gabbo associated with the course you can

command click or control click to open

this up in a new tab and we have pip

install titanoboa we're not going to use

pip we're going to use UV so we

do UV add I'm going to paste it in

Titanoboa and this is going to add this

to my virtual environment here you can

of course do pip install titanoboa if

you're familiar with working with Pip

and if that is your preferred

methodology here so we have titanoboa in

here we can look in our P project. we

can see it's in there and we can make

sure that our virtual environment has it

synced up by just running UV sync and it

looks like it's all good here now that

we have this package what we can do is


we can import it in here with import boa

so the name boa is different than the

package name which is titano BOA but

this is how we import it here and then

all we have to do to deploy this

contract is do

favorites contract equals bo.

load favoritz Dov

so this load function is going to look

for a file name and our file name is

favorites. VI it's going to load this

contract and then it's going to deploy

it with this load function and we're

going to get this favorites contract

object that we can actually interact

with so if I pull up boa and I scroll

down to the boa documentation and click

here to look for the documentation this

is the current documentation as of

recording I'm pretty sure this is going

to change very soon because this is kind

of gross but if we go to API reference

in here high level functionality could

read more about this load function in

the boa dolo section of the

documentation we see here it just

compiles Source from disk and returns a

deployed instance of the contract so if

we even did a little print type

favorites contract we could see what


type our favorites contract is so let me

go ahead and clear I'm do python deploy

I'm going to hit tab so it auto

completes I'm going to hit enter here

deploy favorites PBM it's going to read

in the Viper code into playy and we see

this is a type class boa doc contracts.

Viper Viper contract. Viper contract

favorites contract is a type Viper

contract so just like how you know my

num could be of type int equals 1

favorites contract could be of type

Viper contract now if you try to do this

type hinting like this you'll get this

little yellow squiggly saying uh what's

this Viper contract I've never heard of

that before and to get it we would do we

would just do from and actually the type

is right here from Boa doc contracts.

viperviper contract import Viper

contract and boom the Squiggy lines go

away and this is how you can add type

hints for your different contracts and

your viper contracts but again type

hints are not required in Python we will

be using them more heavily later in the

course but for now you can go ahead and

ignore it so that's it we've printed our

favorites contract to the blockchain we


deployed our favor contract to the

blockchain let's actually now learn how

to interact with it so we have store in

here which updates the favorite number

which it looks like our favorite number

is going to be private so we can call

the retrieve to view it so what we could

do is we could do a little print line

here let's do print

starting

actually let's do

starting

favorit number equals favorites

contract.

retrieve and boa is smart enough to know

that when we call retrieve it see sees

that it's a view function and so boa is

smart enough to go hey this is a view

function I don't need to send a

transaction so if we call favorites.

retrieve it's not going to send a

transaction we can then print do a

little F string here the starting

favorite number and my giup co-pilot is

basically telling me what to write here

which is great is starting favorite

number let me put this little bracket in

here so that we point to this one now

let me clear the terminal run this again

the starting favorite number is seven


does that make sense let's go to

favorites STP ah so I have currently

self. my favorite number equals 7

whatever you have for your self.

favorite number in the deploy SL the

init slth Constructor that's what your

favorite number is going to start off so

that looks correct now we

do favorites contract. store let's

change it to

five so if we change our favorite number

to five we can then copy this

line paste it here and say this is now

the ending favorite number so ending

favorite number equals favorite equals

favorite contracts. retrieve so we're

going to update it and then we're going

to get that number that we updated it

with we can then run

print F the ending favorite number is

and then do this ending favorite number

now when we run the script

now this sends a transaction right

because the store function is not a view

function right retrieve is a view

function so boa goes oh okay I don't

need to send a transaction for this I'm

just going to call it I'm just going to

read it myself I'm just reading data I'm


not changing any state of the blockchain

whereas the store function actually is

changing state right the my favorite

number storage or state variable is

getting updated to whatever you told it

to change it to so now if I pull up the

terminal let's clear it out I'm going to

hit up twice to rerun this we now see

let's read the Viper code and deploy it

starting favorite number is seven ending

favorite number is five now we still

didn't see any transaction information

in here and that's because we're using

the pavm you'll understand what I mean

in a minute but boom We Were able to

update our starting favorite number from

seven to five in this tiny little script

we don't have to manually create the

transaction or anything like that BOA

under the hood when it calls load it

does that whole build transaction thing

Constructor thing sign thing all of that

under the hood for us additionally when

we call store it does the same thing it

does all of the sign transaction build

transaction all that stuff under the

hood for us now you might be asking hey

Patrick I didn't add a private key in

here how is it actually deploying with

how is it actually signing anything


without a private Key Well boa defaults

to this thing called like I've said

before this Pym kind of this virtual

fake blockchain and boa is smart enough

to know that H well if if we don't

specify a real Network we probably don't

care to actually send real transactions

so it's just going to simulate the

transactions it's going to simulate hey

well what would happen if somebody did

sign this transaction what would that

look like so when you don't give a

network to titanoboa it does kind of

this magic where just if you don't give

it a ton of information it'll just

simulate

everything now you might be asking okay

Patrick well then who is the message.

sender and well this is where we can use

a very cool Viper feature where we can

actually do print statements directly in

the code directly in our Viper code now

this is specifically for debugging you

do not want to have these in real smart

contracts but if I wanted to see who the

message. sender was when we called the

store function I could do print message.

sender right in my store function now

when I pull my terminal let me clear it


out and I compile this contract Viper

favorites. VI I get everything but I do

get this warning a warning just means

means that hey um you might want to

check this out it's still going to

compile but the warning says print

should only be used for debugging

because yeah we really shouldn't deploy

this to the blockchain deploy this print

statement it's a waste of gas it might

result in some weird Oddities but we can

add this print statement in here and

then what we can do let me clear the

terminal now when I call store when I

call a store function here our favorites

contract is going to call store and it's

going to print out the message. sender

and then it's going to do the update

here so let's go ahead and run this I'm

on my virtual environment Great Python

deploy I'm going to hit tab deploy

favorites pbmp enter we get this warning

once again the same one print should

only be used for debugging we see the

starting favorite number is seven we see

this address here and then the starting

favorite number is five let's type clear

let's actually run it again we see the

same address here so when we don't

specify an account to work with pivm


poooa will actually just give us a sort

of random one it'll say yeah sure this

is who's sending the transaction

whatever it doesn't really matter it'll

automatically assign this user to send

in the transaction because again it

knows that if we don't specify this

information we're probably testing we're

probably debugging it's way too

exhaustive for us to have to deal with

private keys and RPC URLs and blah blah

blah so Teno is smart enough to just be

like you probably don't even care about

the private key here's a fake account

here you go have fun which is very nice

for

us now if we run this again let's run

this again we still see the starting

favorite number is seven the ending

favorite number is five huh so uh but

wait what what if I run it again well

the starting favorite number is still

seven and then the ending favorite what

why isn't the starting favorite number

now five well so here's what happens

when we actually run this script when we

call python deploy favorites pbmp the

first thing titanoboa does is it says

hey let's spin up this fake PM chain


it's smart enough to know oh okay we

didn't give give it an RPC we don't have

any accounts let's just we'll make a

fake chain like it's fine then we do

this favorites contract equals bo. load

favorites. VI and in this PM chain in

this kind of fake chain it'll deploy the

contract with whatever the variables are

in here right so we have my favorite

number equals 7 so it'll go great my

favorite number is seven in here or

favorite number is seven then we go hey

favorites number. store 5 and it goes

great no problem and it updates my

favorite number to five and then the

script ends and titano goes okay great

let's delete the chain everything's

deleted so that means the next time we

run the script we'll do the exact same

process we'll spin up a fake chain we'll

deploy the contract we'll store and then

we'll delete it so this is why every

time we run the script the favorite

number starts with seven now this is

because every single time we're running

this bo. load in the future you'll

probably not want to deploy the same

contract over and over and over and over

again to a real chain you'd probably

just want to interact with whatever


contract was deployed most recently and

we'll learn some tools to interact with

and get the most recent deployed

contract but again for now since we're

just testing this is what the process

looks like boas spins up a new chain we

deploy a contract to it we update the

storage or the state value favor number

and then we delete the whole chain okay

great now here's the cool part that's it

that's all I wanted to show you with

titanoboa this is how you store this is

how you send a transaction you literally

just call the function on this contract

object if you want to read from a

contract you just call A View function

or a pure function and titano will take

care of the rest this makes interacting

with your contracts incredibly easy to

do so now let's move over though and

learn how ptin works with real networks

because like we said this is kind of

this imaginary fake PM Network that that

says oh okay you didn't give me an RPC

you didn't give me an account I'm just

going to kind of make those up for you

but if we actually want to use an RPC

and we want to use real accounts we do

have to modify this a little bit so this


is the deploy favorites pm now let's

create a new file just called

deploy favoritz dopy like so and let's

learn how to actually deploy with an RPC

so we can actually copy some of this

boiler plate if Dunder name equals

Dunder main run main we'll do def Main

and we'll just do print high from

deploy favorites like this just to make

sure it works I have my virtual

environment up here remember I'm going

to run python deploy favorites and I hit

tab there and then Pi Pi for deploy

favorites okay great let's clear out the

terminal here so now we're going to go

ahead we're going to start up our Anvil

chain like so right here and once again

we're going to copy this endpoint this

RPC URL and we're going to go and we're

going to create a EnV we're going to

create a new file. EnV and we're going

to do RPC URL equals quotes and then

this is

HTTP colon slash like so we're going to

have a RPC URL to actually connect to

now to connect to this RPC URL with

titano boa and our deploy frites we'll

do import boa let's also once again use

our python. to auto automatically pull

in our EMV file so I'm going to copy


python. EMV go back over here open up a

new terminal here and I have to run

source. VMV bin activate to activate the

virtual environment let's now do UV add

paste python DMB in there let's just run

UV sync to make sure it's up to date and

it sure is great now what we can do is

same as what we did before from DMV

import load. EnV and just right at the

top of our contract we'll run load. EnV

to pull in all of

ourv environment

variables now in our main function we're

going to use some buil-in titanoboa

stuff to set up what's called an EnV or

a network EnV so I can't just import boa

I also have to do from bo. Network

import

two things Network EnV and ethereum RPC

so this network EnV object is an EnV

object which can be swapped in with bo.

setv it runs non-mutable viewer P

functions via eth call mutable functions

and contract Creation with an eth send

raw transaction and the way I got to

read this little description here was I

hit command click on network EMV or

control click windows or Linux if that

command doesn't work there might be


something wrong with your there might be

something wrong with how vs code thinks

you're connected to the virtual

environment but but it's not super

important that you know how to do this

fun little command click trick that I

just did this way we'll pull in the RPC

URL we can even you know we can even

double check to make sure it works by

doing RPC equals os. gmv RPC URL which

means we have to import

OS and we can do a little print RPC the

reason we're putting this in an

environment variable down here is

because when we do add a regular RPC

like a tenderly or an Alchemy or

something like that we ideally do not

want to have this in our source code and

as you get better at engineering that'll

start to make more and more sense we

want to just test that this is actually

getting pulled in correctly pull up our

terminal we'll keep our Anvil running

and we'll run this with python deploy

favorites. pi and boom okay that looks

correct we are pulling that in correctly

so now that we're getting the

RPC what we can do is we can create this

EnV object so we'll say EnV equals

Network EnV of ethereum RPC of the


RPC now this command might look a little

confusing let's break this down we go to

the titano documentation which we can

see that that over here please see the

documentation and again this will

probably look very different by the time

that you reach it go to the highle

functionality we go to EnV this is the

global environment object it's this boa

Dov that represents what environment

we're going to be working with and

according to boa different blockchains

or PM are going to be considered

different environments this ethereum

RPC object or class here just

essentially wraps our RPC URL in a nice

helpful function and then we're passing

this as a parameter to our Network EnV

object once we have this EnV object what

we can do then is do boa do

setv to that EnV and this is essentially

how we connect or set up titanoboa to

connect to this RPC now the next thing

we'd want to do is add an account to the

bow environment since now we're

connected to a real Network Bo is going

to go oh okay you're connected to a real

Network now I'm also going to need a

real account so we're going to have to


give it a real account as well and we

can do that by creating a new account

say my account equals and we'll do that

same thing that we did from the last

project from eth account import account

we'll say my account equals account.

from Key and we'll add in a private key

which again we can add to ourm which we

should never do but we're going to do it

here because we're working with Anvil

right so Anvil is running I'm going to

grab this Anvil key minimize my terminal

I'm even going to make it obvious this

is the Anvil

Key by calling it The Anvil key in myv

here Anvil key equals this then in the

deploy favorites we're going to get it

we're going to say private or actually

Anvil key equals os. getet EnV and Bill

key like so now we'll say my account

equals account. from Key Anvil key now

that we've added an account what we can

do now is also tell boa hey this is the

account we want you to use so we'd say

boa EMV add account we'd add my account

and then we'd also do Force eoa equals

true this is going to tell titano boa

to use this as the active account or the

active private key so that anytime we

call a function like store or deploy a


contract it'll automatically use this

account because this account has the

private key but will go great great

you've given me an account with a

private key I can take this Al I'll

handle all the signing of the signatures

and everything you got it so we've given

it an RPC and we've given it an account

now that it has both of these things boa

knows okay anytime you do anything with

boa moving out I'm going to send it to

this RPC and I'm going to use this

account so now if we do that same line

we did back over here bo. load

favorites. VI I'm even going to copy

this line I'm going to paste it in here

this should deploy our contract so let's

go ahead back to our terminal and this

should deploy it to the Anvil Network as

well so if I button let me even drop

this down a little bit here python

deploy I'll hit tabpy I'll hit tab enter

we see transaction broadcasted contract

deployed at here and if we go to Anvil

let me pull this up a little bit we

scroll the bottom we see a whole bunch

of stuff happening on our amble chain

including this transaction going through

you'll notice this is very different


than what happened when we did the PM

Network right so this one says Hey

transaction broadcast contract deployed

let me do a little clear if we do python

deploy I'll hit tab underscore I'll hit

tab again enter say let's read from the

Viper code and deploy it starting

favorite number is seven the ending

favorite number is five nowhere in here

does it say transaction broadcasted this

is because for titanoboa if you don't

give it an RPC it doesn't send a real

transaction it basically simulates the

transactions on this fake chain that it

comes up up with however when we send to

the Anvil chain titanoboa has no idea

that the Anvil chain is our fake chain

it just knows it's not the pums fake

chain so according to Anvil this

contract still exists right so this

contract that was just created this

contract still exists and we could

interact with this contract later on if

we wanted

to okay great so let's keep going so

we've learned how to deploy this

contract let's let's now do the same

thing let's go ahead and interact with

it so we'll do a little print storing

number and then actually let's even do a


another starting favorit number equals

favorites contract.

retrieve like so we'll do a little print

starting favorite number is then we'll

do a little curly brackets here starting

favorite number I'm going to hit tab now

we'll do storing number we'll just call

Favorites contract. store five and then

we'll do

ending

favorite number equals

favorites contract.

retrieve like so and then print little

print F ending favorite number number is

ending

favorite number like so now let's go

ahead let's run this again I'm going to

keep my Anvil chain running going to

clear this our make sure our virtual

environment is up we'll do python deploy

faval Ritz dopy we'll see transaction

broadcasted contract deployed here

starting favorite number is seven

storing a number storing number also

sends a transaction and then the ending

favorite number is now five now if we

type clear and we run this again we'll

get the exact same output right we


deployed a new contract and we stored a

number to

it now what if we wanted to interact

with one of these contracts that we've

already deployed so right here on this

line it says contract deployed at blah

blah blah blah blah with a starting

favorite number of seven that we updated

to five what if we tried what if we

called retrieve on this contract now

assuming we don't delete our Anvil

instance right because this contract is

deployed at this address on our Anvil

chain if I hit contrl C or I stop this

Anvil this Anvil this fake chain that

contract is going to get deleted right

so as long as this is running while we

deploy this let's go ahead and let's try

to interact with this so I'm actually

going to create a new file called

interact. pi and I'm going to right at

the top I'm going to say my contract

equals and then paste in that address

between these quotes then I'm going to

grab a little boiler plate let me grab

this line here I'm going to paste it in

here and I'm going to create a little

main function def main now what I want

to do is I want to use titanoboa to

interact with this contract address


deployed onto Anvil to First connect to

to the Anvil chain we have to do exactly

what we just did in deploy favorites

right so we're going to have to do these

this set of commands we're going to have

to get the RPC and set the EnV then we

have to get our private key and set it

into Bo as well so I'm just going to

copy those two or those two sections

those AKA this six lines and we're using

a whole bunch of stuff in here so I need

to import this I need to do from bo.

Network

Network import ethereum RPC comma

Network

EnV like so and then I also need to

import boa and then from eth account

import account like this and now what I

can do is I can use this titanoboa

function called at so titanoboa has this

class called a Viper deployer or this

object called a viper deployer well I

can call an at and get returned an

address string where I can pass in an

address string and it'll give me the

Viper contract add that address so if we

scroll down we can see something kind of

similar here we can see contract Factory

equals bo. loads partial oh that's a


little bit different than what we saw

before SRC INF Fu and then we have this

and then we say contract factory. and

then we give an address so what we can

do is instead of calling load right

right in our deploy we call load where

is it load and this actually deploys a

contract this load function deploys the

contract what we can do instead is we

can call load partial which will not

deploy the contract but it'll give us a

Viper deployer so let me just show you

what this looks like so I'm going to

call in our inter up high I'm going to

say bo. load partial partial partial

partial did I spell that right

and I'll do the same thing I'll do

favoritz

Doby and now this won't deploy the

contract but I'll say

favorite

favorite deployer

equals B outload partial

favorites. and then I can say favorites

fave

favorit

contract equals favorit deployer do

employer. my contract or what do we call

it yeah my contract now we can once

again get the favorite number by calling


favorites contract. retrieve so what

this is and then uh then let's print it

out print FST string favorite number is

Curly brackets copy paste favorite

number so what this script is going to

do is we're saying hey Ty tanoa we have

a contract at this address here and what

are the two things you always need to

interact with a contract you need the

address okay great we have that here and

then you're going to need the ABI now

whenever we compile a contract we get

the ABI this loads partial function is

able to basically compile our favorites.

VI which has the ABI because it has a

list of all the functions and how to

interact with it so it gives us the a bi

and then when we do favorite deployer do

my address it gives us a favorites

contract object that we can actually

interact with so let's go ahead and try

this and yes we need Anvil up we need to

make sure this is the same Anvil that

has our contract deployed on it

currently so we've deployed something at

0xcf 7e blah blah blah let me scroll up

in here uh 0x 70 Okay cool so I do see a

contract that was created here if you

don't if you deleted the terminal and


you uh came back to this later you can

just go ahead restart Anvil redeploy it

and then you should get a contract

address but so now let's go to this new

shell now let's run python interact. piy

uh whoops uh we forgot to we forgot to

do the load EnV so let's do from Dov

import

load. EnV and then do the

like this so we're getting this error

invalid URL none no scheme supplied and

that's because this was probably

returning a blank because we forgot to

load the so let's clear let's run this

again and we get favorite number is

five oh and that was because the

favorite number got updated from 7 to 5

when we ran our deploy favorite script

which is very cool now we can even go a

step further so favorite number is five

we could update it again now that we

have this favorite contract object we

can do favorite contract favorites

contract. store we could update it to

22 we could get the new favorite number

we do favorite

favorite number updated equals favorites

contract.

retrieve

retrieve like so and then print


F favorite number is now little squiggly

favorite number updated like this I'll

clear the terminal I'll make sure my

virtual environment is up and then if

it's not deactivate I can always

deactivate it and just run UV run Python

interact. piy and we get favorite number

once again starts at 5 we update it and

now it's 22 now now if I hit up and run

this again you'll see the favorite

number now starts at 22 and then we

updated it to 22 which means we updated

it to nothing and this is all because

this Anvil chain is still running right

boa doesn't know this is kind of our

locally running chain so now if I were

to kill it with contrl C I deleted it

now I hit clear now I go back over here

I hit up again and I run it now I'm

going to get this here uh hey um first

of all HTTP connection to

127.0 One Max your tries we failed we

couldn't connect I don't know how to

connect to this thing it's like oh well

of course you couldn't connect the envil

chain isn't even running so we could

rerun it with Anvil now again we could

hit clear run this command again and

it's still going to fail it's going to


fail a little bit more bizarrely and

this is where AIS can really help you

help to bug some of these errors so you

might see this you might go ah I don't

really know what this is doing um so if

we go up to the trace back

this this Trace back is basically like a

list of where this error came from so

it's saying okay in our interact. piy

file the main function okay interact. Pi

the main function failed okay what line

in the main function okay it says this

favorite number equals favorite

contract. retrieve that's line 25 so

let's scroll down Okay so this failed

okay cool and then we see in this kind

of really bizarre file this failed what

so when we so when we call Favorites

contract. retrieve under the hood

titanoboa is calling a whole bunch of

other functions for us in order to get

the value very easily know it's a view

function know not to send a transaction

and do all this stuff so the rest of

this at first glance is going to be kind

of jarble to you all we know is we

failed on this line in our script and

the reason we failed on this line in our

script is because we back to Anvil uh

there's no smart contract deployed in


here right if we look at all these

little commands that were run on the

Anvil none of these have transactions

sent this is a brand new blank chain so

we've told Anvil we've told titanoboa

hey there's a contract at this address

on this blockchain can you call the

retrieve function on that contract and

tanabo goes absolutely yes right away I

will do that uh hey um I I just tried

and I couldn't do it I I I got this

weird response and this error decoding

0x as you 256 value length is not the

expected size of byes 32 this is because

Anvil said hey uh I don't have a smart

contract at that address I'm going to

return I'm going to tell you zerx I'm

going to give you like a a blank

response and Titanic Bo goes oh I got I

got a weird blank response from the

blockchain I don't know what's going on

and again it's because this contract

doesn't exist so let's go ahead let's

kill Anvil here let's clear the

terminal and now we know how to set the

RPC RL add an account deploy a contract

interact with the contract and then

interact with the same contract later on

assuming that address exists now luckily


blockchains don't just get deleted so so

when we interact with ethereum or ZK

sync or like a real Network once an

address is deployed it's there forever

so typically we won't have to worry

about running to erors like that except

for when we're testing and when we're

loading stuff like this now let's come

back over to deploy favorites and let's

just do one more thing so we've been

working with this store number a whole

lot right this if we go back to the

favorites. vibe we've been working with

this store function which is cool but

like what about this add person this is

a little bit more complex it takes a

name and a favorite number and a name is

like a string array like what how how do

we how do we call this how do we

interact with this well let's go ahead

let's get rid of some of this store

stuff here right let's not even worry

about that now instead let's now

do

print storing a person that sounds a

little weird but all right sure storing

a person and we'll do favorites

contract. adderson let's call this ad

person function which takes a name and a

favorite number so let's give it a name


as a string we'll do Alice and then a

favorite number as 25 now this is just a

regular python string and python strings

are actually Dynamic by default whereas

Viper strings are not Dynamic so we gave

our string a maximum size of 100

characters so if we tried to add you

know 101 characters in here this

transaction would fail let's go ahead

Let's test it out with just one person

and then we'll do we'll say person data

equals favorites contract Dot and let's

scroll up to list of people because this

keeps track of the person's array so and

it's a public variable so we can call it

directly with list of people so

favorites contract. listof people again

we can call list of people because it is

public we cannot call my favorite number

directly which is why we've been calling

retrieve so we can do list of people at

index zero since Alice is the first

person that we added they should be at

index zero then we can print it out we

can do print F person little squiggly

brackets person data so now back in our

terminal we have to pick up Anvil again

because this script is working with

anvil
let's pop open a new terminal and let's

go ahead let's run this we could either

you know do source. EMV we could kick up

our but I'm just going to do UV run

python deploy favorites. piy like this

and we'll see transaction broadcasted

contract deployed storing person that

sends another transaction and then we

have person 25 Alice returned from the

blockchain

right cuz down here we have person

person data the person data is going to

be 25 and Alice cuz we go back to the

favorites. vi we have a list of person

structs right and a person struct is

made up of a favorite number which is a

number and a name which is a string so

we're giving back the favorite number

and the name exactly as Viper have told

us nice

all right now to finish this up I have a

little bit of a workshop for you a

little exercise for you to pause a video

and go start coding yourself and as well

be sure to take the quizzes in cyphon

updraft these are going to help ingrain

this knowledge on you remember

repetition is the mother's skill you

cannot start to problem solve until you

have the prerequisite knowledge


ingrained in your bones so here is your

Workshop that I want you to pause the

video and go try to do yourself I want

you to create your own contract your own

Viper contract that you will deploy to

your local Anvil instance I want you to

give this Viper contract a function

called set bull which can change a

variable named my bull to the Boolean

you pass it so You' call like set bull

true or set bull false then you should

call a function called get bu which will

return the value of my bu and then then

finally you can deploy this contract to

your local tender delete network if you

still have the free trial now here's

what I don't want you to do I don't want

you to just copy paste this prompt into

chat jbt and have it give you an answer

and then run away with it I want you to

try to do this yourself feel free to use

AI to ask questions to help you

understand the things that you learned

in this section and then at the end if

you want to copy paste this into chap

gbt to get a sample solution then feel

free to do so so pause the video try to

do this Workshop yourself and I'll see

you in a little
bit all right welcome back did you

actually do the workshop if you didn't

pause the video stop taking the course

and go do the workshop if you don't do

the workshops you're not going to get

this information drilled in what do I

always say repetition is the mother of

skill and we want you to be skillful so

if you into the workshop go do it if you

did do the workshop congratulations and

welcome back

so we learned a lot of things in this

section even though this is probably one

of the quickest sections we have in all

of the cypron ofd draft curriculum let's

do a quick refresher of all the things

that we learned in this section so first

off we started with our favorites.

contract the exact same one we've been

working with this whole time however we

learned how to deploy it using this tool

called Titanoboa and this is going to be

the tool that we're going to be using a

lot moving forward because this is the

tool that the professional smart

contract developers use we were able to

deploy our smart contract in a single

line of code favorites contract equals

bo. load favorites. VI this compiled the

contract deployed the contract sent the


transaction and did everything for us

now on this script here it deployed it

to this imaginary fake Pi evm chain

which we learned a little bit about as

well we learned that this is is a chain

that is spun up in the background that

titanoboa spins up allows us to run our

script and do our stuff and then at the

end of our script once our script

finishes it just deletes the whole chain

it throws the whole thing out so we

deployed this contract to our high evm

chain we called this retrieve function

on it which titano went oh that retrieve

function that's a that's a view function

right okay I don't need to send a

transaction I don't need to spend any

gas this would be a blue button in remix

I'm just going to read the data directly

off the blockchain then we called

favorites contract. store which does

send a transaction and Titan Boa is so

smart that behind the scenes it did all

the stuff that we did in the last

section it created that transaction

object it signed it for us creating

those VR and s's it did all of the stuff

it did all of the complicated ethereum

stuff under the hood so that we could


just call Favorites contract store in

one very simple function then we call

Favorites contract. retrieve again like

so this was deploying it to the pvm

network but we also learned how to

deploy it to a more real Network where

we used the Anvil fake chain to simulate

deploying to a realish network because

Anvil isn't a real network but it's more

real than the pvm network and we got our

RPC URL from

ourv we got our private key from ourv as

well which is a bad practice we don't

want to do this in the future but

because we're working with Anvil we let

it slide this time in the future we will

never do this again we will use the

encryption methods we learned in the

last one mouthful there we said hey

titanoboa from now on work with this RPC

from now on work exclusiv with this RPC

and set it and also set this as the

default account this way when we call a

function that would send a transaction

send it to the RPC that we sent you and

with the account that we told you to use

so this way we never have to worry about

setting accounts or ipcs once we call

these functions once we call these lines

of python boom we can just say bo. load


and it'll deploy with this account to

this RPC then like normal we can go

ahead and call functions and again

because boa in the background has it

setup to be this RPC and set up to be

this account we can call AD person and

then additionally we can call the view

function and then additionally we can

call list of people again we can call it

because list of people is a public

variable which means essentially it's a

view or a readon function we can call

list of people at index zero because

list of people again is a person array

so we'll get the zeroi person from that

array and then we'll print it out

additionally we learned okay well cool

so we learned how to deploy contracts

but how do we actually interact with

contracts that already exist well all we

need as always is the address and the

ABI we get the address because well our

script told us where the address was and

this address will probably be different

for you depending on how your Anvil is

set up and how your code decides to

deploy it but all we have to do is same

thing we'll get the RPC we'll set up the

account to deal with it and instead of


doing load we do load partial which

returns this deployer object where this

deployer object has a function called at

where we say favorite deployer do and

you pass in the address and that gives

us a favorites contract the exact same

way exact same way our deployment work

right so when we did bo. load favorites.

VI it deployed a brand new one but when

we do uh favorite deployer but when we

do bo. load partial it just gives us a

deployer it compiles us it gives us an

ABI and we do favorite deployer at we

get the actual contract object then we

can interact it like we normally would

as if we had just deployed it ourselves

great as always we worked with UV we had

a p projecto we had a venv and we had a

EnV as well which again once we move

over to moccasin we will not be doing

this anymore and you'll see the much

better methodology that we use in the

future so we just learned a lot in this

very short section but you should be

incredibly proud of yourself now is a

great time to take a break because your

brain will do a much better job

absorbing the information if you take

breaks so now's a great time go for a

walk get some ice cream or go to the gym


take that break and I'll see you in the

next one congratulations on finishing

titano boa favorites

list all right welcome back to the next

section of your viper and python

blockchain development smart contract

engineering and security researching

Journey we are now on what I think is

going to be one of my favorite sections

of the whole course because now we are

going to be introducing you to the

moccasin tool which is a smart contract

development framework which is going to

help us deploy test maintain and write

incredibly professional code if you

scroll down in the list of sections here

again they're not populated with

information because I'm updating them as

I'm recording moccasin is the main tool

we're going to be working with

throughout the rest of this course and

then Advanced moccasin as well there

will be a brief stop when we learn about

html/javascript just kind of as a crash

course for how websites work when it

comes to Smart contract development so

let's take a look at what we're going to

be learning here and why we're doing

this final step to learn and grow as


smart contract developers so here is the

final code of this section here you can

read all of it in here there's a lot of

information on the readme if you want to

go ahead and follow along with the

readme but I have all the code written

in front of me here now now in the last

couple of sections we ran into a few

problems first we said okay let's deploy

our smart contract in raw Python and we

saw how much effort that actually was

right there was a ton of effort we had

to build our transactions we had to

figure out the NS we had to encrypt

private Keys we had to do all this extra

information we had to do all these extra

steps and then we said okay well let's

use this tool called titano now and that

was a lot more helpful and that was a

lot easier we were able to very quickly

and just a few lines of code deploy run

and move forward however we still saw

that there was kind of some annoyance

right we had two different scripts we

had a script for actually if we scroll

back up to this we actually had two

different scripts let me let me scroll

down here we had deploy favorites and

deploy favorites PM so for each

different network we actually had a


different script that we wrote and

that's really annoying additionally we

didn't have any tests in here we don't

have any way to actually test any of the

smart contracts that we wrote and that's

a big issue because if you don't test

your smart contracts they might have a

bug in them and then if they have a bug

in them you could potentially deploy a

smart contract and lose millions of

dollars and we don't really want to do

that so we're going to be teaching you

finally how to use this tool called

moccasin and if you're on the GitHub

repo associated with this scroll down

let's click this moccasin link we'll pop

up to the moccasin GitHub repository and

you can click the documentation over

here to see what the documentation looks

like here so this is the documentation

for the mckinon tool and it's going to

be a command line tool very similar to

Viper that we can use to compile deploy

test and work on different networks when

in our Python and with our Viper Smart

contracts now there's a whole lot of

stuff that the moccasin tool can do for

us and if you want to pause and take

some time to read the documentation feel


free to do so but let me show you what

we're going to be doing in this section

now I'm still kind of soft balling you

information we're still going to be

working with this favorites. VI I know

very simple contract but this stepping

stone of a project is going to make your

life a lot easier because we're going to

train you on moccasin with something

that you're already familiar with right

we've been working with this favorites.

VI contract for several contracts now

for several sections now so a lot of

this section because we already know

this Viper code is going to be giving

you the power to do all this tooling to

test your contracts to deploy your

contracts more professionally and all of

this as you get better and better at

coding you'll see why this is so much

easier to write professional code now

there's a whole bunch of stuff on the

left hand side here we're going to go

over everything in a little bit but if

we pull up our terminal here right now

we are once again we're connected to

Anvil we have a little Anvil chain

running if I open up a new terminal I

can first run a deploy script so in here

I have this deploy deploy script where I


have whoa I've got a whole lot of extra

stuff well that will we be explaining in

a little bit but some of this looks

pretty familiar we have this favorite

contract equals favorite St deploy hm

this thought deploy is a little

different I wonder what that looks like

okay we have some new stuff in the top

that we're going to be working with but

we have this favorite contracts ah

favorites contracts. store looks like

we'll update our favorite number H we

got some new weird stuff on maybe

verification but okay so we can actually

deploy our contract to the pvm Chain by

just popping open terminal and running

MOX run deploy and it'll run the Run

command it'll run this run command it'll

say currently on network PM starting

favorite number and ending favorite

number so it deployed our contract to

the pvm started with a favorite number

and ending with the favorite number now

unlike way back when we did our python

or our boa or our python right when we

had to have two different scripts for

working with different networks if you

want to change networks here for example

let's say we want to deploy to this


Anvil chain or in the future maybe ZK

sync or ethereum or sapoia Etc all we

have to do is do MOX run deploy --

Network Anvil and that's it we can keep

the exact same code for every single

Network and just switch networks just by

adding D- Network and then the name of

the network we want to switch to so we

see at the top here currently on network

the name of the network we see the

transactions broadcasted again similar

to what we saw in our last couple

sections we see starting favorite number

which started at seven for this some

transactions were broadcasted and it

looks like it ended up updating and

changing the number to seven so we're

going to learn a lot of tooling that

will make our smart contracts work no

matter what chain that we're working on

additionally we've got this section here

this is to actually verify our contracts

on a blockchain Explorer so if you go to

any contract for example for example

let's go to the curve Dow token right

again we're going to go use curve a lot

as an example because curve is Viper go

to the curve Dow token if you go to the

contract section on ether scan is scroll

down you can see all the code that's in


here this is because this contract is

actually verified now when you deploy

your contracts they don't automatically

get verified on ether scan you have to

usually manually do it yourself and I

didn't walk you through that very

painful process of manually verifying

smart contracts but normally you have to

do it yourself however moccasin comes

built in with some tools to

automatically verify your smart contract

so you don't have to do any work you

just deploy to that Network and if the

network has an Explorer you

automatically verify it back in our boa

and pyth back in our boa and web 3py raw

python examples of working with

favorites contract we would have had to

code this functionality ourselves and

I'll show you in a little bit that that

can actually get very tricky

additionally we have this new concepts

of tests in here now tests are obviously

incredibly important to Smart contracts

and we haven't been testing any of our

smart contracts up till this point

because well again we'd have to write a

lot of test Frameworks and i' didn't

want to have to teach you the pain of


writing those test Frameworks and in

this section we'll just learn how to

write them directly in Moccasin so in

here we have a couple of different tests

and we can test all of them in one Fell

Swoop just by writing MOX test boom

that's it and it runs all three tests

almost immediately we can also run

something like

test- n Auto which is going to run our

tests in

parallel which it has a little bit of

extra startup time but when you have a

ton of tests it runs them way faster

additionally we're going to learn a lot

more about setting up professional

python projects because yes like I told

you at the beginning of the course not

only are you going to become a

phenomenal smart contract developer but

you're going to learn a ton of advanced

Python and good python coding practices

as well so at the end of this section

you're going to learn how to write tests

for your smart contracts you're going to

learn how to write scripts using moxin

that allow you to switch between

networks very easily you're going to

learn the basics of working with a py

project. tommo file you're going to


learn some more tools with working with

the py project. tommo file and we're

going to learn how to add different

network information save it into a

config so that we don't have to hardcode

URLs and stuff right into to our scripts

so with that being said let's get

started learning moccasin learning this

tool that's going to take you from and

okay python smart contract developer to

a phenomenal one let's jump

in now to get started here if you're on

the moxin full course Cypher updraft

let's go ahead and scroll down once

again to this section this is section

where is it section 4 moccasin favorites

list now before we actually start going

into the moccasin favorites list we

first need to install the correct

version of moccasin now I've gone ahead

and I've actually added a whole bunch of

features that only work with a very

specific version of moccasin so I'm

going to be teaching you the command now

to install a specific version of

moccasin on the gab repos with this

course the command can be found right

here so if you want to just copy paste

it and run it go for it when you watch


this video the command in here might be

different than what I'm showing you

right now so be sure to use whatever

command the GitHub repo and cyphon

updraft tell you to use not necessarily

what you're seeing on the screen in this

video so what you're seeing here is a

more advanced way to install a package

because we're installing a very specific

pre-release of moxin because like I said

I added some features that I want to

teach you on and by the time this course

comes out it probably won't be a

pre-release anymore and I have to type

and we have to have this Dash

pre-release equals allow cuz the UV tool

typically doesn't allow you to install

pre-releases because it doesn't consider

them production already but add agress

so for us this is what we're going to

use to install moccasin however you can

also click this link down here which

will bring you to the GitHub repo

associated with moccasin and then click

the documentation on the right hand side

here and typically in here if you go to

the installing moccasin tab it'll have a

couple different ways to install

moccasin and we can scroll down and and

see the install moccasin in an isolated


environment and typically this is how

you would install moccasin just UV tool

install moccasin the exact same way we

installed Viper but like I said we're

going to be doing it with this command

for this video because this has some

extra features and some added quality of

life improvements that are going to make

your life a lot better so I'm going to

go ahead I'm going to copy this line I'm

going to go over to my vs code I'm in my

MOX CU folder right if I do PWD if I do

LS I can see all the different folders

in here doesn't matter where I run this

command because we're going to install

moccasin globally in its own isolated

environment so we're going to go ahe and

run it and it very quickly adds

everything and you can see right here it

says installed two executables moccasin

or MOX now to make sure that you

installed it correctly I'm going to do a

little clear here right now I am not in

a virtual environment although it

doesn't really matter at this time but

if I do which mocks I see that I do

indeed get a response I can also do

which moccasin and I get a response here

so Mox and Moccasin are both going to do


the exact same thing the reason we have

two executables is because UV has this

tool called uvx and um it only works

when the package name is the same as the

command name but I digress so to start

exploring moxin we can do Mox d-el and

we'll see the output of all the

different commands we can run with this

moccasin thing we can do a knit compile

test run deploy wallet console install

Purge config there's a lot of different

commands in here and we're going to be

learning how to use these commands to

make amazing smart contracts so let's go

ahead and

clear now that we have moas installed we

can start creating our project already

so I'm in my MOX CU folder and hopefully

you should be too right with all your

projects that you're working on so far

let's go ahead and create a new folder

we'll do

mkd Mox

favorites Cypher updraft now we're going

to go ahead and do code MOX D favorites

Cypher updraft I hit tab so it autocom

completed and again if you do not have

the code command you can also do file

open folder that should work as well

let's go ahead let's open this up zoom


in a little bit and in our last section

and in our last section we use the UV

anit tool to get started with a python

project but moccasin actually comes with

a tool as as well to for us to create a

new project we can run MOX init now if

you want to see what this command

actually does before you run it you can

do Mox andit d-el and it'll print you

out a little help of what it's going to

do it's going to this will create a

basic directory structure at the path

you specify whoops looks like that's a

little grammar bug which looks like this

and it gives you a little sample output

here and also it has these different

options at the bottom one is --vs code

which says add a. vs code settings Json

file and IT has-- py project to add a py

project. tomomo file so we're working in

vs code so I'm going to do this-- vs

code if you're not working in vs code

you don't have to and I do want a p

project. Tomo file because that's how

professionals write python packages so

I'm going to do MOX anit --vs code just

like it shows here and then

also-- py project like this and now it

says project initialized at and it gives


you the directory that the project was

initialized in so let me clear my

terminal now and hide it let's go over

to the explore here and now we can see

all the different files and folders that

it populated with us here let's do a

brief walkthrough of what these folders

and files do so this vs code folder

comes with this do settings. Json now

this is only going to make sense and

work for people who are in vs code but

basically it's a way to help our syntax

highlighting in our vs code actually

know what it's doing so there's a couple

of there's a couple of lines in here

that we'll explain in a little bit this

lib folder is where we're going to

install packages where we're going to

install dependencies on our project next

we have script this is where we're going

to add any types of deploy scripts for

example in here we have a little deploy

script and we have this little yellow

underscore which we're going to fix in a

bit we have a little deploy script to

deploy a counter contract oh that's

interesting oh so if you look in SRC it

actually comes with a little counter

contract here we're given some simple

dummy tests for us to use as well and


even right now this is kind of a very

very minimal project for testing

deploying and working with this counter.

VI that were given we could even do a

little MOX test to test everything in

here and you'll see that it runs and

completes our test we could do MOX run

deploy as well and we would deploy our

counter contract and we would run our

deploy script here so this deploy script

will first deploy the counter contract

using this deploy keyword that we

haven't used that yet but we will and

then it'll call this increment function

and it'll check the starting count and

ending count of this increment function

because and if we look at this counter.

VI contract it's it's very Min well all

it really has is a set number and an

increment and then this number as a

public variable at the top now if you

want to go ahead pause the video pause

the course right now and play around

with this repo you can absolutely do so

but for now what I'm going to do so I'm

going to command click or control click

going to command click this one this one

this one and this one command click or

control click these ones right click


select delete I know it's a little it's

off the screen my delete um is but I'm

going to move them M the trash so I get

started here with a blank project so I

don't have any files I don't have really

anything in here now after we ran MOX

test you might also get this pest cache

in here this is just a a place that when

we run our test files the testing tool

that we're using is this thing called

Pest and it saves some information to

make the test run quicker the next time

you run them in this little folder here

we also have this coverage file so let's

keep walking through what the rest of

these files are we have this coverage

file which you'll understand what this

is much later we have these git files as

well which will'll explain these later

we have this moccasin DOL which will

which will spend a lot of time

explaining and we have our Pi Project

which is something that we're familiar

with and then of course we have our read

me over here which gives us a little

little helpful command here which tells

us basically how we can go ahead and get

started with MOX run deploy and it tells

us we can run mock help or visit the

mockasin documentation to learn more SRC


this folder here is going to have all of

our Viper contracts script this is going

to have all of our Python scripts and

then test this is going to have all of

our tests for our Viper contracts now

for us to get started here we're just

going to go ahead once again and we're

going to add our favorites contract to

this SRC which stands for source so

we'll go back to the gab repo associated

with this course you can either grab it

from the mock favorite Cipher updraft or

whatever or you can grab it from your

last project whatever you want to do I'm

just going to copy paste it directly

from get up here I'm going to I'm going

to right click over here new file

favorites. by hit enter paste it in like

so all right so we have our favorites.

VI in here with pragma version 0.4.0 we

have the contract in here now typically

we would compile this with you know

Viper SRC SL favorites. VI right this

will run the Viper compiler to actually

compile this but if we go ahead and

clear we can also compile every single

every single file in our SRC which is

mock compile this will compile one

project to an out directory which you


can see in here and that's it so if we

look in the out we look in this

favorites. Json zoom out a little bit

this has a ton of compilation details

about the favorites contract it has the

bite code that we're used to seeing now

it has the ABI if I scroll over to left

here I can even click this little drop

down to see what else we have and then

we have VM which is the evm or the

ethereum virtual machine so that's great

and if we were to have let me just copy

paste this in here A whole bunch if we

were to have a ton of contracts in here

same thing we could just run MOX compile

compile every single project to the out

folder and be good so I'm going to go

ahead and delete all of these now now

what's cool about moccasin is that you

don't even have to compile when you run

your scripts if they don't compile well

the scripts will just break so compiling

is actually optional it's just that if

you do want to compile so that you have

these different so that you can actually

see you can inspect the bite code and

the AI Etc you can see that in the out

folder

there now that we have our favorite SV

in here let's learn how to actually


deploy this let's learn how to deploy

this first to the p m to the Titanoboa

fake Network and then we'll learn how to

deploy it to Anvil to a local more

realistic Network so I'm going to go

ahead I'm create a new file called

deploy dop and this is where we're going

to add our code to actually deploy this

contract so to get started let's write

our deploy script now this is going to

look pretty familiar to what we did in

our last section but with some nice

additives so in every section so far in

our python code we wrote If

Thunder name equals equals main you know

write some do some function like deploy

we've been using main a lot now this

works in Moccasin but typically what we

use in Moccasin is this concept of

moccasin main so if you go to the

moccasin documentation here and you look

up moccasin main you'll come to the

scripting documentation to learn about

moccas and Main in your scripts the

moccas and main function is special if

you have a function with its name in

your script moccasin will run this

function by default after running the

script like a regular python file for


example you could also do this so this

would also be valid moccasin code this

is also valid moccasin code or this is

also valid moccasin code let's go ahead

and set this up to do the moccasin way

so we'll say

def moccasin

main deploy so and then if we do print

high in here we pull up our script now

if I try to run this like a regular

python file like UV run python script

deoy nothing's going to happen because I

don't have this like if Dunder name

equals main run mockus in main if I were

to add that in clear the terminal rerun

that command I would now get high so

really it's up to you to decide what you

how you want to set up these python

files later on in the course we'll learn

about some of the Cool mockasin Tools

where this moxas and Main comes in handy

to run some really nice functionality so

for now I'm just going to leave it as

moas and Main but you can do whatever

you want to do here so how do we

typically deploy a contract in boa well

in Tiano boa we would do like you know

import boa bo. load and then the path of

our contract you know blah blah blah

well in Moccasin what you can do is you


can import these contracts directly

using the python import system so what

we can do is we can say from

SRC import

favorites like so moccasin is clever

enough to know that you're in a moccasin

project and that it's going to have

viper contracts in it so this favorites

object if we go ahead and place it in

here I'm going to even do a little

breakpoint breakpoint I can actually

inspect what this favorites object is

that we just imported here now let we

pull up the terminal here me do a little

MOX

d-el to run a script we're going to use

this run command it says runs a script

with the Project's context so for me to

run this deploy upy in Moccasin let me

clear the terminal I would do MOX run

let me pop this down here MOX run deploy

I don't even have to put deploy dopy I

don't have to do Sr or script deoy dopy

Mox and smart enough to know oh your

deploy script is in the script folder

that's probably your script let me look

for a script named deploy piy and great

you could still run script deoy dopy you

know that'll work too whatever you want


to do but we'll hit this breakpoint and

now we can type in our debugger here we

can type type paste in favorites hit

enter and we see this is a type Viper

deployer we saw this before we saw this

in our last section where we did the

Viper deployer do command to work with a

specific contract this Viper deployer

also comes with another very nice

command comes with a deploy command so

let me go ahead and quit this debugger

here let me clear it out to deploy this

favorites contract since this favorites

is of type Viper deployer we would just

do favorites.

deploy and then I could say

favorites

favorites contract equals favorite.

deploy and once again I could do a

little print line what was it uh

retrieve is that what we're looking for

retrieve okay yep retrieve then I could

do uh

starting number equals

favoritz contract. retrieve then a

little print line starting number is and

then I'm going to do an F string because

that's what I like to do

starting number I can clear my terminal

can run this again let me show you the


whole script I would do MOX run deploy

and it's going to say starting number is

seven because it's going to deploy this

automatically deploy it to the pi evm

exactly like we saw before now if we go

back to our our boa favorites Cypher

updraft project we scroll down we had

deploy favorites pvm we had this as a

command and this looked very similar

right we just had bo. load uh which was

essentially the deploy command and then

we called retrieve here we did something

very similar we imported that favorites

contract which this favorites keyword is

of type Viper deployer and then we

deployed it using the deploy command and

then retrieved a starting number like so

so just like this you've learned to run

a deploy script using the moccasin CLI

using the moccasin tool great work

so now that we learned how to to deploy

this pretty simple script here to our

pvm let's actually learn how to deploy

it to a different network so let's try

to deploy this to our Anvil Network you

know our locally running Anvil Network

because that's going to be a little bit

different than deploying like this right

mockerson doesn't know about Anvil so if


I run if I open a new terminal me clear

this out and I run Anvil like this by

run MOX run deploy again it doesn't know

about Anvil if we go to Anvil I don't

see any activity at the bottom here it

has no idea that Anvil exists but if I

do MOX run-- help me let me just pull

this up here I can see kind of all the

different commands in here there's a

number of different commands that we can

see to interact with the Anvil chain we

have this network which is some name and

yes I know in the little demo at the

beginning of the section we just said

daset Network and B the most important

flag or the most important option is

going to be this network flag which

stands for the Alias of the network from

the moccasin dotl so let me hide the

terminal here we go back to my files we

briefly mentioned it but we have this

moccasin doomo file in our project here

now this moccasin Doo file comes with

some boilerplate stuff but this is how

we can customize our moccasin instance

and work with different Networks in fact

mine came defaulted with this little

networks. Anvil section here with a URL

already so I want you though I want you

to go ahead and I want you to delete


everything in here for now except for

project SRC so we're going to build

everything from scratch in here now this

moccasin doomo this is the configuration

file for all of our networks and any

type of settings for moccasin and this

is how our lives are going to be made

really easy now if you copy paste this

link that it gives you you as well this

will give you a list of all the mock and

Tomo parameters in the GitHub

documentation if we scroll down in here

it'll give you all these different

options that you can use to customize

your Mox and instance and it has like a

lot of little comments in here about

what each thing does so for us we're

going to create a new network because

what we want to do is we want to make it

super super easy to deploy our contract

to different networks we want it to be

as easy as MOX run deploy -- Network

Anvil that's what we're looking for we

want it to be that easy to deploy our

contracts so to create a new network in

the Mox and Tomo we would make this

little square bracket here and we would

say

networks. Anvil so this is how we're


saying okay we're going to create a new

networks object that's named Anvil and

the first thing we want to do is give it

a URL so we'll say our URL equals

HTTP call SL slash what is the Anvil URL

again let's copy this minimize this

paste it in here great that is the Anvil

URL I'm going to give you one other

setting I want you to add in here it's

not going to make sense for a little bit

but for now just do save to DB equals

false so now that we have these two in

here let's just try to deploy our

contract with this so we'll do MOX run

deploy D- Network Anvil hit enter we're

get given a little prompt the

transaction run on this will actually be

broadcast SL transmitted spending gas

associated with your account are you

sure you wish to continue so moccas

doesn't know that this Anvil URL is kind

of like a fake URL so anytime we put a

network in here moccasin will say hm

you're running on a real Network are you

sure you want to spend money and it will

ask you to go ahead and hit yes so I'm

going to hit yes and we're going to

airror for a different reason I'm going

to hit yes but if you don't want to be

prompted anymore we can say prompt


live equals false and this way let me

clear the terminal if I run this again

we're not prompted we're just

immediately hitting the error here great

now this error this is an error that

you'll probably see a lot we're going to

see bo. network. network andb object.

blah blah blah eoa not defined so this

is a pretty classic era that you're

going to see in here and you can

actually also see this in the common

errors of the documentation of moxin

this is the most common error you'll

counter and it means you'll need to add

an account in your m. file you can do

this by following the wallet guide oh

that's so helpful there's a little

wallet guide here as you can see there's

no private key information in here o so

how can we run this deploy command with

our private key now I'm going to show

you the bad way to do this and I'm going

to show you the way that a lot of other

tutorials will tell you how to do and

then I never want you to do this again

so if we hit up a couple times MOX run

deploy Das Network Anvil I can also go

back to Anvil let me scroll up and I can

grab one of these private keys and then


I can do just do-- private key and paste

the private key in here and it will run

successfully so this is the easiest way

to deploy and run some commands you just

add your private key in like that

however this is obviously terrible

because you took the pledge and you know

you don't want to do this so there must

be a better way way for us to work with

private Keys rather than just H sticking

it right into the command line

there now a quick side tangent here

anytime you put your private key in the

command line it actually is saved in

your history right if I tap up right now

this private key is saved somewhere in

history and if an attacker gets access

to your computer they can actually type

history in your here and they can see a

history of all the different commands

you wrote including singor private key

so if you ever do add your private key

to the command line you want to make it

a force of habit to delete all your

history now there's a couple of ways a

couple of different ways to do this so

I'm typing history right now and you can

see my my whole history here I'm on a

zsh remember if I do Echo shell I'm on a

zsh type terminal if I do history P for


zsh and then I type history again it

deletes my history for bash it's history

history- C ask your AIS or Google what

the command is to delete your history

there but there's also a file me clear

this out let me do a little less hilda.

zsh history this might not make sense to

you there's also this zsh history or

bash history file that will with your

product as well that you're going to

want to delete and there's a few other

commands as well for removing your

private key from caches and histories

Etc a lot of people think I might be

being overly cautious here but but again

if you're going to use private keys in

your command line be sure you know how

to delete it from your history be sure

you know how to delete it from your

cache like I said every shell is a

little bit different so there are

different settings you can set up and

that might be you know 20 to 30 minutes

of me talking so for now I'm just going

to say again if you're using a real

private key don't have it in plain text

don't just drop it into your command

line makes sense okay great let's keep

going okay so the question is then okay


how do I deploy this contract how do I

deploy this contract without just

sticking my private key in plain text

here well we learned way way way back in

the python section to encrypt our keys

well moccasin actually has a way to

encrypt our keys for for us so if you go

to the documentation in here me scroll

down a little bit one of the first

guides is going to be encrypting a

private key so you can encrypt a private

key using the wallet import account name

command this will create a key store in

the default key store directory and it

will prompt you to enter your private

key and password so we have a little

example here MOX wallet import my

account if you want to see all the

different commands MOX wallet can do you

do MOX wallet

d-el and we can see

there's a lot of wallet management

Utilities in here we can list all of our

accounts we can generate a new account

with a random new private key we can

import a private key into an encrypted

key store we can view the Json of a

keystore file we can decrypt we can

delete blah blah blah so what we want to

do is we want to run MOX wallet import


and then whatever name you want to give

this for me I want to use this Anvil

private key and this is the the zero

withth private key or the first index so

I'm going to call it Anvil one which is

arguably kind of confusing because this

is the zero withth Anvil key but I'm

going to call mine Anvil one here when

you hit enter going to say running wall

command importing private key says

please enter your private key so I'm

going to go here copy my private key

paste it in and you'll notice that when

you paste it in it looks like nothing

happens but it's because it's hiding the

private key so once you hit paste go

ahead and hit enter enter a password for

your private key I'm going to do a very

lame password but you should do a very

good password I'm going to just type the

word password and then double confirm

your password and then we'll see saved

Anvil saved account Anvil one to key

stores now if I clear my terminal and I

do MOX wallet list I can now see a list

of different accounts that I have

installed into my mockasin project I can

even view it by saying MOX wallet view

Anvil one and I can see the address of


that Anvil one right let's go back to

Anvil look like private key0 scroll on

up is Ox F39 blah blah blah F39 blah

blah blah okay and then the encrypted

version of the key in

here now that I have encrypted a private

key right in Moccasin what I can do is

let's try this again I can now do MOX

run deploy D- network network Anvil I

can also do-- account Anvil one since

Micon knows that Anvil one is one of the

accounts that I have encrypted when I

hit enter I get prompted enter your

password for keystore Anvil one I'll

type in my password you'll notice that

it is not showing my password I'll hit

enter and then it decrypts my key right

in the command line and sends my

transactions stting number seven and we

go to the Anvil we scroll to the bottom

here we can see we do indeed have some

transaction activity down here this is

so

exciting now I don't know about you but

I am incredibly lazy and I like to work

really really hard to be really really

lazy so even just adding this D account

Anvil is very tiring for me I don't want

to have to do that so what I can do let

me get rid of this and I'm using a fun


little control W to very quickly delete

it here is in the networks. Anvil here I

can also add a default account so I can

say default account name equals little

quotes here Anvil one and this way now

all I have to do now in my terminal is

hit enter and it's it's going to

automatically use my Anvil One account

so if hit enter now it says enter your

password for key Anvil one I can type my

password in and boom it sends it through

so this way when I use networks. Anvil I

automatically work with my Anvil one key

now like I just said we like to work

incredibly hard to be incredibly lazy so

there's one more thing that we can do to

make this command even easier to run

right so we did MOX run deployed Network

anvil we hit enter we're now prompted

for our password for our Anvil one

command here well we can do one more

thing and if we go to the we go copy

paste this into our search bar and we

scroll down in here we can see there is

this unsafe password file where we can

add a password file that has our

password for a different account now

it's very specifically named unsafe

password file because you really don't


want people getting a of your password

file so you want to put it in a location

outside of your project here so we can

actually just save a password in a file

and then add it again where is that that

keyword here that unsafe password file

and then save it as a parameter in our

moccasin dotl now a lot of people are

going to be tempted to just do oh okay

cool you know password dot password

password.

text P P it in here and then you know

print it in here and then set it here

I'm going to recommend not doing that

because you might accidentally go to

share your project with somebody and oh

Whoops a Daisy your password is still in

your project you know how we do all

these GitHub repos right we do all these

these GitHub repos with kind of our our

full code if you go to share your

project which you should share your

project but you forget to take the

password file out uh well that would

that would be pretty bad so what might

be a nicer thing to do is is if you type

CD into your terminal here and if you do

um CD do moccasin you'll notice that you

have a new file new folder called

moccasin in your home directory mine's


obviously users Patrick user will be

users wherever you are if you type LS in

this folder you'll see a couple of

different folders in here you'll see you

have this key stores file and you might

have some other folders and files in

here as well well but what might be a

better thing for you to do is in this

moccasin make a new directory called

unsafe

passwords CD into this unsafe passwords

file and add this password into this

unsafe passwords folder so to add some

text in here what you can type is you

can enter some bash text editor like Vim

VI or something like that but I'm just

going to make your life a little bit

easier we're just going to use an echo

command here this is a bash this is a

Linux command if you're not familiar

with how it works this is where AIS are

very helpful uh if you run this command

you should definitely ask an AI what it

does and how it works but we can run

Echo

password and this little Carro command

here means to like dump it in Echo

password into Anvil one now if we type

LS we have this Anvil one file in our


unsafe passwords folder and if I type

cat Anvil one cat is a command to help

like print out whatever is in a file I

can see my password is in Anvil one so

again this so again this is okay for now

because we're because Anvil one is a is

a dummy key right like it's just comes

default with Anvil but ideally you're

not saving your passwords for actual

private Keys like so but we're just

doing this to make life a little bit

easier or our dummy account so now what

I can do let me CD back to my directory

I'm going to CD to MOX Cypher updraft

and then CD to mock favorites Cypher

updraft okay great I'm now back in this

directory I'm going to hide my terminal

here now I can say unsafe passwords file

equals this little Tilda stands for the

home directory you could also do home or

dollar home whatever you want to do sl.

moccasin SL unsafe passwords SL Anvil

one so now I have a default account name

and I have an unsafe password file which

is going to point to this Anvil one so

now let me pull up my terminal again I'm

back in my MOX favorite Cypher updraft I

can now do MOX run deploy D- Network

Anvil I'll hit enter and I don't get

prompted it automatically decrypts my


Anvil account using the password we gave

it here so so very exciting here just by

learning this you are learning much much

safer ways to work with your private

Keys you just learn how to encrypt a

private key using moccasin into a key

store file then decrypt it by being

prompted or using an unsafe password

file you should be incredibly excited

and Incredibly proud of yourself because

like I said the year

2024 the number one attack Vector was

leaked private keys so you're going to

learn how to encrypt your keys and work

with keys in a much safer way than the

rest of the industry does as of right

now and this is both very exciting and

very sad to hear as of right now you are

more knowledgeable than half a billion

dollars worth of money in the blockchain

industry because you know how to encrypt

your private keys and not share them in

plain text you should be very

exciting we have our contract what we

haven't done is test it now testing is

probably one of the most important

things any smart contract developer

needs to get good at and I will say

though that AI has made testing


phenomenally easier and you'll see what

I mean by that in just a minute so let's

go ahead let's learn how to write a test

for this now moccasin has a testing

framework built into it called py test

and this is a very well-known where very

well-used testing framework so if you're

already familiar with working P test

you're actually kind of already familiar

with doing moxin test as well so to

write a first test we're first going to

create a new file we're going to call it

test favorites favorites. pi and let's

go ahead let's make a really basic test

in here so first I'm going to say def

test starting values we'll do a little

pass just to get it set up and in Pest

and therefore in moxen as well pest

looks for this test keyword on different

functions in a test folder so you have

to have a folder named tests and each

one of your tests must start with test

in order for pi test to know that it is

actually a test maybe we want to test

that hey when we deploy our smart

contract we want to test to make sure it

does indeed start with the number 7 so

what we can do is in our test favorites.

piy we can go ahead and do exactly what

we did in our deploy script we can run


from

SRC import fav rits then we can do favor

Ritz favor Ritz contract equals paste

that in favorites.

deploy and to do an actual test we could

say assert this is very similar to Viper

assert favorites contract.

retrieve equals equals 7 test this we

can open up our terminal once again

and we can just run MOX test and this

will run all of our test suite and

actually let's go ahead and close the

Anvil instance now as well this will run

our entire test Suite since we only have

one test test starting values we see

this one little Green Dot here if I were

to copy paste this and make another test

boom I'll say test starting values you

know two or something un open the

terminal run MOX test again you would

now see two dots these dots mean that

the test has indeed passed so we have

two tests that passed here

great now what I don't like about these

tests right now is that our deploy

script could do some other weird stuff

you know for example maybe I said maybe

in our deploy script after we go ahead

and deploy our smart contract we go


ahead and we say Okay favorites

contract. store 77 or something right

right and then we would say ending

number equals favorites

retrieve like this we did a little print

line then uh

F ending number

is number with a little curly brackets

let me actually open my

M.O but if I clear my terminal let me

pull back up the deploy if I run deploy

the ending number is going to be 77

right so if I do MOX run deploy it's

going to run our deploy script starting

number is seven ending number is 77 when

I actually go deploy my smart contracts

this is the function that I'm going to

use right I'm going to do MOX R deploy

right like why am I even writing this

script if I'm not going to use it

however in my test here are we testing

our deploy script no we're not testing

our deploy script and that's an issue

because if our tests are saying hey yep

the starting value is seven yep you did

it you did a great job and then we go

and deploy using the deploy script the

starting number is going to be 77 so we

want to make sure that we're testing our

scripts we're testing our deploy scripts


however we're going to deploy this

contract we want to make sure to test it

as well so instead of doing from SRC

import favorites what we can do instead

is we could say from

script.

deploy import and then what's the name

of the it's just called deploy I'm going

to change the name of this to deploy

favorit I'm going copy this paste it

down here deploy favorites it's going to

be the name of my function from script.

deploy import deploy favorites and I'm

going to comment all of this out and

explain kind of what just happened here

so this is a concept that's really

tricky for a lot of people to understand

is the python import system so the way

python works with Imports is it looks

for something called modules right and a

module can be either a folder or a file

okay what this is doing is we're

basically saying from the script folder

inside the deploy file grab that deploy

favorites function so we're literally

almost the same as like copying this

line and pasting it in here now this

script folder also has this init.py

which is a very explicit way to tell


python that this script folder is a

module and you can do Imports from it if

you don't have that nit file it's known

as a namespace package and imports

should still work but if you want to

make sure that they work and you want to

be more explicit we add this little init

file in here but anyways so we're going

to import this function in here and now

for our deploy favorites function we

should use the contract that this deploy

favorites deploys so back in our deploy

piy we'll notice that we deploy a

contract but we don't actually return a

contract we don't get a contract from

this function so at the bottom then we

probably want to write return favorites

contract this way this deploy favorites

function now returns something so what I

can do now is I can say favorites

contract equals deploy favorites like

this because now this deploy contracts

actually returns a favorites contract

here we can save it to our favorites

contract variable like this and then run

favorite contract. retrieve equal = 7

now if I pull out my terminal I run MOX

test we

successfully get an error actually it

says test starting values it says this


line failed with an assertion error in

the print line from our deploy script we

could see starting numers 7 ending

numers 77 because our deploy script

updates to

77 so instead in our test instead of

checking to see that we're seven let's

update it to 77 it's clear run our test

again and now it successfully passes

excellent so now let's go ahead let's

keep going let's write another test and

you can see here's where AI can be

really helpful AIS are typically really

good at understanding what type of test

you want to do so for example if I wrote

def test can

change values it's already pretty much

given me a sample solution for what my

test should be I'm going to go ahead and

hit tab but I can see okay favorites

contract equals deploy favorites

favorite contract. retrieve equals 42

once you write a couple of tests AI will

start to think one step ahead and all

you have to do is typically write the

title of your test and AI will jump in

and take over so this test actually

looks good to me test can change values

if you do not have gi up copilot


activated you can go ahead pause the

video go Ahad write this out but we have

very favorites contract equals deploy

favorites favorites contract. store 42

assert favorites contract. retrieve 42

we can go pull this up we'll clear the

terminal run MOX test and we see those

two pass as

well now this is known as the

arrange act and assert set up for a test

here first we arrange

all the stuff we need to set up in order

to run the test we act the thing we are

testing here is this store functionality

are we successfully actually updating

the value when we call stor and then

finally obviously the assert so you

might see like arrange act assert in a

lot of my tests as well and this is

because I like to kind of mentally

separate the three into these three

buckets first is the setup then is the

actual act that we're trying to test the

actual function that we're trying to

test and then we run the assert now

let's add one more test and then we're

going to refactor

everything so let's do test can test can

add people if we go back to our

favorites. VI we scroll down we


obviously have this add person Let's

test to make sure this is doing what we

want it to do so let's start with our

arrange so we're going to say new person

person equals Becca Becca we'll say her

favorite number is going to be 16 so now

we'll do the ACT we'll say oops sorry

we're not finishing arranging yet we

still have to deploy the contract as

well favorites contract equals deploy

favorites now let's actually do the ACT

here we'll say favorites contract. add

person add person

with the new person person and the

favorite number right because the ad

person of our favorites. VI is a new

person favorite number great then we can

run our assert which is going to be by

running assert favoritz contract do list

of people at index zero and we've done

this before we know this actually turns

two values right the list of people is

an array or a list of the person type

and the person type has a favorite

number and a name it should return the

favorite number and the name so should

return 16 and Becca so let's go ahead

Let's test all of these as well let's

run MOX test again we get three dots


three pass well done now what you're

going to want to do a lot of the time is

you're going to want to test only only

one of your tests you're not going to

want to run your whole test Suite if you

have lots and lots and lots and lots of

tests it might take a long time for all

those tests to run so to run just one

test we can use the dash K Flag so I

could say MOX test- K paste test can add

people hit enter and now it says one

past two deselected so this was our way

of just running the test can add people

deselect or ignoring this test and then

deselecting or ignoring that test so

just like this you actually have a

decent test set up here well

done now let me tell you something here

on every single one of these tests here

we ran this deploy favorites function so

in every single one of these tests here

we kind of did a little extra work every

single time these tests ran we deployed

favorites now if we had a th tests and

every single time we were deploying this

favorites contract that could be a lot

of work that we don't really have to do

we just want to run this once and then

whatever the output was from running

this once just like always use that so


what we can do is use a concept called a

fixture so at the top of our test here

we can first import import itest because

fixtures are a concept of this pest test

thing and you'll actually get a little

squiggly line here saying P test could

not be resolved because in our P

project. toml we don't have a p test and

therefore in ourv andv we don't have a

py test and in fact we don't even have

Ave EnV here so you don't have to do

this but if you want what you can do is

you can do UV ADD py test this will add

py test in here and then to make sure

that P test is in our V EnV we could do

UV

venv we don't even have to run bin

activate but we do want to make sure

that our vs code is pointing to that

area so now and then I'll just run UV

sync to make sure it installs py test

and great and now that little squiggly

has gone away now you don't have to do

that because moccasin has py test built

in but if that's really those squiggly

lines are annoying to you you can go

ahead and add it to your be EnV but so

now I have pest in here I can do at

pest.
fixture def

favoritz

contract like this and I'll say return

deploy favorites and now what I can do

is I can take this fixtures favorite and

I can on all of my tests I can delete

this line and I'll pass it in as a

parameter to our test function so I'm

going to do this for all of them I'm

going delete that line too pass it in

here and I'm going to delete this line

here I'm going to pass it into here now

if I run all my tests again with MOX

test MOX test I can see they're all

still passing so fixtures are going to

be ways for us to write our tests and

write our and deploy our contracts more

efficiently so you didn't really see a

speed up because we only have three test

here but this is going to be a much

faster and much more effective version

to do our tests now all fixtures have

something called a scope and by

definition they start off as scope

function which means we can Define our

fixtures to only run at certain times or

only run a certain amount of times when

we have scope equals function this

fixture function will run in between all

of our test functions so you can think


of like okay defa test starting values

happens then it says okay deploy the

favorites contract so it says okay it's

going to call this fixture and run

deploy favorites when we go when we run

def test can change values we say this

is a new function so this is also going

to say oh okay deploy the favorites

contract and then same thing with down

here actually I just said hey fixtures

are are a faster way or more effective

way of writing our tests but since this

is function scoped this is going to run

after every single function it's

basically the same as what we just did

but we can change the function to

session or module or there's a couple of

other keywords here that we can use if

we say this should be a session what's

going to happen is this will run exactly

one time for our entire test session

right so when I run MOX test this will

run exactly one time for all three of

these tests and what it'll do is it'll

run it kind of behind the scenes is

it'll run deploy favorites it'll save

that to

favorites contract equals deploy

favorites and then it'll secretly it'll


secretly just have a global variable

favorites contract that we use in all of

our functions so instead of deploying

the favorites contract every time it

says okay let's grab the contract we

already deployed so when we have this as

session scoped and then I I still need

to return favorites contract we're

almost secretly setting this variable at

the top of our function to this favorite

contract this will run one time for the

entire session and then we can work with

this as a variable if our deploy

function was like super super super time

intensive if it took like an hour to run

a deploy function we would have to wait

an hour in between all of our tests and

in fact ready let me let me visualize

this for you so let's put this as

function scoped okay in my test here you

don't have to do this I'm going to say

import import time and right before I

return the contract I'm going to say

time. sleep five this is a way to to

sleep or wait 5 seconds in a test let me

pull back the terminal back up now when

I run MOX test watch how much slower my

tests run okay we have a Green

Dot now I have to wait 5

Seconds we have another Green Dot now we


have to wait five more seconds

now we have three Green Dots between

every and you can even see it took 15.5

seconds for this to run between every

single test every single deploy we had

to sleep or we had to wait 5 Seconds now

let's go back to our test favorites if I

change this from function scoped which

again having this as function scop would

be equivalent to literally like having

this this line in the test here if I

change this from function scope to

session scoped well what happens now let

me pull up the test here let's run MOX

test we'll see we did have to wait 5

seconds again but then all the tests

immediately ran right afterwards that's

because since this was session scoped

this ran one time and then anytime we

wanted to grab a favorites contract

after that we just grabbed from a

variable that this set up behind the

scenes so these fixtures are going to be

incredibly incredibly helpful and I'm

going to go ahead and delete this now

these pictures are going to be

incredibly helpful for us writing faster

tests more efficient tests and smarter

tests and this way as well we know


exactly what contract that we're working

with and like I said we're also going to

be able to test our deploy scripts are

the exact same as what we think they

should be all right you should be

incredibly excited for doing this

because you're learning some really

Advanced python really early in your

Python and your viper career so be

excited

now typically you can 100% code your

contract like we just did here or you

code your test like what we just did

here have your fixtures right at the top

of the file however what a lot of python

developers do and this is typically what

we see is instead you know I'm going to

go ahead and I'm going to copy this and

delete it in your test folder create a

new file called com

test.py I'm going to paste this in here

I that means I got to import Pest and

then I also got to

import um then I got to do from script.

deploy import deploy faval rits like

this and they put their fixtures in here

this is a special pest configuration

file that allows you to share fixtures

Hooks and some other configuration stuff

so if I save this and I can delete back


in my test file I can delete this import

P test I can also delete this Top Line

and it seems a little odd that I'm

passing this favorites contract variable

to my test functions here but my test

file here is smart enough to know oh

okay like there's this favorites

contract thing here that's probably a

fixture let's look for that in the com

test.py ah okay here it is I'm going to

use that and then once again we can run

Mock's test and everything passes

successfully great work

all right our project is starting to

really shape up here we still have a

couple of files in here that we're not

really sure what they do and that's okay

we're going to learn in later sections

but we have a deploy script that looks

really good we're able to deploy a

contract doesn't matter what chain it's

on because we can use the Das Das

Network flag to very easily switch now

kind of like our Viper code our Viper

code is what's known as statically typed

or strongly typed because every single

variable in Viper has to have a type

associated with it this is incredibly

important for smart contracts because


smart contracts are very specific if

something goes wrong or unexpected in

your smart contract you could lose a lot

of money our python code by contrast

doesn't have to have types now if you

went through the python crash course at

the beginning of the Python fundamentals

you know that we did talk about that

python does have a type hinting system

now I'm going to go ahead and and say

that we should do the same thing we

should add type hints to our python

however this is 100% optional so this

one here is 100% valid python but we

could also add typ hints the reason that

I like typin in Python is because this

favorites contract object we might not

know what functions are associated with

it or you know maybe we' run like

favorites contract equals 7even and then

I try to do favorites contract. store

you know 42 or 40 and this no longer

works because favorites contract is now

a number and it's no longer a contract

object so I like adding typ hints and

additionally typ hints make kind of

debugging and working through your code

a lot easier sometimes so this will be

optional but I am going to go ahead and

take this time to add some typ hints to


this so let's go ahead and let's get

started so this favorites contract right

here from SRC import favorites we know

that this favorites object is of type

Viper deployer and anytime we import

some contract like this we know that

this is going to be a Viper deployer

when we call Viper deployer do deoy it's

going to return a type Viper contract or

this is how you do or to do different

types or ZK sync contract but for us

we're just going to do a a Viper

contract now you'll get this little

yellow squiggly line because VI because

our python is going hey uh what is this

Viper contract you're talking about I

don't know what this is now we can get

this Viper contract from a couple

different places we can get it directly

from titanoboa or moccasin has actually

some builtin ways to get this Viper

contract much quicker so we can say from

moccasin booat tools import Viper

contract and you might even get this

little yellow squiggly line because our

VV if we go back to our P project. toml

we don't have moccasin in here so we

could just simply do UV add moccasin if

we want to be more specific we could say


moccasin equals equals and then you know

whatever version what version do we have

in here and then scroll

down this 0.3 Point whatever enter oh

and then for this one in particular I

have to do this-- pre-release allow you

might not have to do that okay we add

that in here now in our deploy upy we

see that those little squigglies go away

because our python project now knows

that this moccasin tool exists so cool

so this is of type Viper contract and in

vs code if you hit command click or

control click like I said you can

actually see the code of the Viper

contract or the class Viper contract

which if you took the python crash

course you haven't learned about classes

yet don't worry about it okay next

starting number this favorites contract.

retrieve this is going to be what it's

going to be an INT great favorites

contract. store there's no typing there

ending number is going to be an INT okay

great and then we return a favorites

contract so since we're returning

something we should add a type hint to

our function definition and actually

just like Viper how Viper does this

little arrow and then the type we're


going to do the same thing we're going

to do a little arrow and this is a Viper

contract so we'll say Arrow Viper

contract like this and even if we wanted

to we could have our moccasin Main

return a Viper contract and we can just

say return deploy favorites like this

great and now we have typin in

here okay so now I'm going to deploy to

the seoa test Network and if you were

able to successfully so we we showed you

guys how to get our fake chain back in

blockchain Basics we also showed you how

to get some test net sapoia if you were

able to get some test that sapoia eth

we're now going to deploy a contract to

sapoia and we're going to verify it now

verifying a contract is a process of

basically publishing the source code of

your smart contract since the source

code isn't stored on chain it's only the

bite code so an unverified smart

contract on a block Explorer like ether

scan would just look like this

completely unreadable or if you're

looking at block Scout scroll down we

could look at the contract as well this

this one is an example of one that is

verified instead of just a bunch of


garbled hex we actually see the code

down here we actually see what this

smart contract looks like because this

one was actually verified however these

are actually the same address it's

verified on block Scout but not verified

on ether scan there's a number of

different solutions to this but what I'm

going to be showing you is how to verify

the smart contract on block Scout block

Scout is an open- sourced block Explorer

and we love them for that so we're going

to do two things now first we're going

to deploy to sapoia and if you do not

have any sapoia test net or you're

having a hard time getting it don't

worry just watch and follow along and

then we're going to verify on sapoia at

some point I'm imagining that tenderly

is going to have this access but for now

this is what we're going to do so for us

to deploy on sapoia what do we need to

do well in our moccasin DOL we're going

to have to add the seoa network here so

let's go to the moccas and.mo let's

create a new network for spia we'll do

networks. sapoia and the first thing

that we're going to need is a URL and

the URLs we've worked with so far we're

going to be Anvil right which is this


URL and then we also worked with

tenderly now to actually connect to

sepolia there's a couple different

things we could do we could go to a site

like chain list.org and we could look up

sepolia wow there's a lot of saolas

these days well we'll look up siia um

right here and if we hit this little

drop down you can see a whole bunch of

public rpcs these aren't great to use

because they can be slow have pour up

time Etc so we want to use our own

dedicated RPC connection to seoa you can

of course run your own seoa node as well

or your own ethereum node but that's a

much longer topic much longer

conversation so what we're going to do

so we're going to come back to the gabo

associated with this course and if we

scroll down a bit and we scroll down to

where are we now we're in the moccasin

favorites list there's this new section

called sign up for Alchemy where I want

you to click this link to open up

Alchemy for us to sign up now again not

sponsored by Alchemy but if you all sign

up through this link hopefully we can

ask them to help sponsor us because

we're getting them signups so Alchemy is


a platform which has a ton of developer

tools one of the best ones is that they

allow us to create rpcs they allow us to

get rpcs to connect to different

blockchains and the these are going to

be professional with high quality uptime

rpcs so I can go ahead I can hit sign up

or get your API key to sign in and I'm

going to go ahead I'm going to sign up

like this and we'll sign up with Google

or sign up with SSO or however you want

to sign up and then once you started

logging in you can just kind of fill out

the information here I'm doing what are

you building cyphon updraft tuto or

Viper that's what I'm building what

chains you're building on ZK sync is the

sponsor so we're going to do ZK Sync

here next we're going to choose free

next I'm not going to add a credit card

here last thing how did you hear about

us cyphon updraft hell yeah let's build

and so now we're given a little welcome

to Alchemy I'm going to go ahead and

access because I already know what I

want to do so it says Patrick's first

app and it actually gives us ZK sync

setups here but I'm going to go to

networks and I'm going to look for

ethereum and I'm going to configure this


let's look for ethereum I'm going to do

ethereum saoa I'm going to hit save and

now back in my app here if I click this

I can choose ethereum spolia now I have

a network information for ethereum

sapoia I can scroll over to networks and

I'm given this HTTP SN point4 suboo I

can go ahead and copy this go back to my

code and say URL equals this now this is

kind of sensitive and because if

somebody else gets access to our API key

they can kind of spam our our Alchemy so

this is better to have this either as an

environment variable or a secret or

something like that now I know I told

you environment variables are terrible

and they are for your private key

especially they're not great for your

sensitive information like this but this

is much less sensitive then your private

key so what I am going to do I am going

to go ahead I'm going to create aemv EMV

I'm going to say sepolia Poli RPC URL

equals and paste this in here so now

that I have this and Moccasin is smart

enough that allows you to create your

own files so you can even Dov equals EnV

or if you're doing a more professional

project you can change this to some


other location not right here um so that

you don't accidentally share this thism

file with other people now unlike your

private key the worst case scenario that

happens though is if you expose your DMV

you just have to you know change all

your API keys and that's kind of

annoying but it's not the end of the

world so now we have this spolia RPC RL

in my M.L I can just put dollar sign

suppo crl and Moccasin will pull in ourv

know this is an environment variable and

use this and anytime you're using aemv

you want to at least check that the EnV

is somewhere in yourg ignore so again

again this isn't the best but it's not

the end of the world if somebody gets

access to this API key anyways so now we

have URL let's just put save to DB as

false for now we'll understand what the

DB thing does later for a default

account name we probably don't want to

do envil one here we probably want to do

our seoa account so we start using our

more safe setup here right I can grab my

private key from my account here I'll do

a little the three little dots I'll do

Account Details show Private key I'm

showing you the private key because

again this is just a test account and I


don't really care there's no money

associated with this but I'll pass in

our password you'll put in your password

hold to reveal the private key then you

can copy the private key and we can go

forward with the same process that we

just did for the Anvil so we'll do MOX

wallet import and I'll call this default

but you can call it whatever you want

paste the private key in give it a

password another password saved account

to default key

stores so now in here I can do default

account name

equals default with a new wallet I can

do box wall list amble one and default

now in order to verify this I'm going to

need some verification details so if we

go back to this it's all mockas Ando

parameters we scroll down in here we

have explore URI Explorer API key and

Explorer type this is where we enter our

Explorer information and if you want to

just kind of get this very quickly we

can just run MOX Explorer list and it'll

just list a massive chunk of default

explorers for us to use and I know

there's kind of a lot of information in

here but we should be able to find kind


of near the top sepolia where we have

this Explorer URI so we going to copy

this and in here I'm going to say

Explorer URI equals paste that in we

also need Explorer type which is going

to be block Scout so I'll do explore

type

equals block Scout like this and that's

it and with these two lines we now have

the configuration to actually verify our

smart contract onto sapoia to finalize

the verification process we just need to

add a little section to our deploy

script moxton comes with a tool that

allows us to like get the parameters and

get the information about whatever

network is active so at the top of our

codebase we could say from moccasin doc

config import get Active network and

it's this command that allows us to get

the Active network so we can say Active

network equals get Active network I can

even do a little print Active network

like this me pull up the terminal I'll

just do MOX run deploy to show you what

it looks like starting number is seven

ending number is 77 and then we have all

this information about our Active

network it's a type Network it has a

name called pvm No URL no chain ID all


all this other information in here we

spin up a new terminal I'll run anvil in

here if I were to do MOX run deploy D-

Network Anvil it's going to print out

information about Anvil and so for this

one the network name is Anvil URL is

here blah blah blah all this other

information so once we get the Active

network what we can do is we can say if

active

network. has Explorer so this is a

command that comes with every network

has Explorer literally just says hey

does this Explorer URI exist if we have

an Explorer we're going to do result

equals Active network

dot moccasin

verify favorites contract and

technically this is all you need to do

to verify your contract if you want to

wait for the verification to go through

you can also do result dot oops wait for

verification so this is basically

requesting the verification and this is

waiting for the verification to actually

finish so with all of this we should

have enough information to deploy to

spolia and then verify on sapoia now for

spolia we're going to pretend that this


is a more serious blockchain and because

of that we're not going to do an unsafe

password file we want this to prompt us

and we want to actually enter our

password so that we don't have our

password saved someplace now granted for

this tutorial I'm using a very crappy

password because I'm teaching you all

but you should be using good passwords

so moment of truth let's deploy this to

sya like I said you do not have to do

this getting sya test at eth is often a

huge pain in the butt and I'm aware of

that oh let me turn off Anvil here and

I'm aware of that so if you were

unsuccess uccessful in getting test net

sapoia don't worry about it but just

watch and follow along here so we're

going to do MOX run deploy -- Network

sepolia we should get prompted since

we're using-- sepolia we're going to use

this sapoia RPC URL which we've set up

in ourv here which we're using from

Alchemy our moccasin pulls in the EnV

because that's what we've told it to do

and so replaces this seoa RP crl with

this dollar sign here with this value so

this dollar sign is what signifies that

this is an environment variable we're

going to use the default account it's


going to prompt us for our password for

the default account and then it's going

to deploy the contract it's going to

update the value of the contract and

then finally it's going to check if we

have an Explorer which we do this is the

Explorer and then it's going to verify

it on block Scout and it should print

out the final verification link so let's

go ahead MOX run deploy D networks polio

I'm going to hit enter here this

transaction will run and actually

broadcast trans transmitted blah blah

blah yes I would like to run this and to

your password for key store default I

entered my password I hit enter and the

transactions are going through so we

have a transaction here I can even check

on block Scout aoia let me paste in the

transaction here we're seeing this is a

test net transaction only we can see it

pending I'm creating a contract exactly

like what something like ether scan

would show us and we're going to have to

wait a little bit for this to go through

I'm getting this user warning because

I'm using a version of alchemy that

doesn't have this keyword but that's

fine it's going to keep going it was


mined contract was deployed here

starting number is seven transaction

broadcasted any numberers here we even

get a little print out contract

verification started contract verified

and it gives us to a link to sepolia blo

scount which we're going to go ahead and

we're going to open it up I used command

click to open it up but you can also

copy paste this bring us to the contract

address here I can scroll down in here I

can see the contract has a little check

mark which means it was verified and we

see the contract code right here on

block

Scout if you followed along with me here

and you successfully deployed this seoa

and got it verified on sapoia you should

be incredibly proud of yourself and if

you didn't because you're having a hard

time getting testet tooa eth that's also

okay getting test Neta can kind of be a

huge pain in the butt so that is all

good

now this verification process will also

work for smart contracts that have

already been deployed you know since

favorites is of type deployer what also

we could do is we could say like

favorite contract equals


favorites. and then you know uh where's

the and then grab the copy the address

here paste it in here and then just do

the exact same thing we just did so you

wouldn't even need to deploy it right

you could have a function that says oh

you would you would need this line

though you could literally just have

this and you could verify your contracts

as well without having to deploy it this

is how you would verify a previously

deployed smart contract and that's

it all right so our codebase is looking

great for working with evm equivalent

blockchains and layer 2s remember if I

go to L2 be.com we can see a lot of the

different l2s like arbitrum bass op Etc

most of these are evm equivalent and

deploying to them would be as easy as

you know popping into Alchemy and going

to networks and configure and just

adding another Network grabbing the

endpoint and as we just showed you you

know adding a new Network's endpoint in

your moccasin doin however for some of

these it might take a little extra step

a lot of these ZK rollups might take a

little bit extra work because they're

not exactly perfectly evm equivalent


ballic the co-founder of ethereum has

tweeted IMO in 10 years all rollups will

be ZK and will commit blocks with

finalized State routes to L1 every slot

and then some other stuff here as well

so metallic has basically said that he

thinks the future of blockchain is on

these ZK rollups so as of today there is

a little extra work to work with them

but by learning it now you're getting in

on the future of what the blockchains

are going to look like so we're going to

teach you how to deploy to ZK sync using

moccasin which does require a couple

extra steps a couple other installation

steps but once you install everything

once you get it down it becomes just as

easy as what you see here now to get

started here we're first going to learn

how to deploy to a local ZK sync

instance very similar to Pym you know

how we run let me zoom in here MOX

deploy deploy or excuse me MOX run

deploy which runs our deploy script like

this this runs on a pi evm network but

it's still evm we want to do the same

thing but on a what's called an era VM

so ZK sync runs on What's called the era

VM it's the bite code of ZK sync is very

different than the bite code of ethereum


however Viper is a really cool language

because we can compile this Viper human

readable code down to both ethereum and

to ZK sync so to get started working

with Viper let's go over to moccasin

once again so usually I Google moccasin

cyphon GitHub to get to the GitHub and

then we can see the docs in the top

right here so in the Mo and

documentation there is a tutorial for ZK

sync that we're going to follow and to

get started with ZK sync we need to

install these two additional tools one

is an era test node and one is the era

compiler Viper now we're going to be

installing a bunch of stuff as I've told

you a 100 times installing things is

usually the hardest part of programming

just hands down so if you haven't taken

a break in a while take a break before

jumping into this and be sure you've set

aside plenty of time to run into and

deal with some of the issues that you're

going to run into cuz you're going to

run into some issues but persevere

because just doing a lot of this

installation will also train your brain

what to look for when it comes to

installing things because we're going to


be installing things we're going to be

installing some stuff from this raw

releases page where it's just like a

whole bunch of binary stuff that we need

to install and learning how to install

stuff from Pages like this is going to

be incredibly helpful now I will say

typically you like as you get better and

better you're going to want to start

being cautious about where you do

install stuff from because if you just

start getting really willy-nilly with

installing anything maybe you

accidentally install a virus and we

don't want to do that so take your time

going through this installation process

remember the reason we're going through

this is because we want to unlock the

power of these ZK rollups which are

going to be more gas efficient they're

going to be more performant and as alic

said these are the future of ethereum

and I want to give you the keys to the

Future here once you have both of these

tools installed now it's going to be

like C deploying smart contracts and

working with ZK sync so take your time

installing these tool tools know that it

might take a little bit of time be ready

to ask questions and it's okay like I


said like I always say installing tools

is often the hardest part and these are

some of the most badass cool Cutting

Edge tools out there period and you're

going to learn how to install them so if

you haven't taken a break take a break

before installing these come back make

sure you have plenty of time to try to

install these and once you install them

take another break and you should be

incredibly proud of yourself once you do

have these installed so the era test

node if we click this link it brings us

to this GitHub repo and this will give

us an anvil right so we have Anvil here

this Anvil is evm this era test node is

basically the Anvil of ZK sync so it's a

little bit different so we want to go

ahead and we want to First install this

era test node so I'm going to scroll

down I'm going to look at the

documentation here it's got a whole

bunch of limitations and features if you

want to read those and the first thing

that we're going to need to do is ensure

that you have rust installed on your

machine so depending on when you watch

this video the installation instructions

for this might be a little bit different


so be sure to follow along the

installation instructions here

as best you can and as always use your

AI friends to help you get past and

through the installations once again CLA

v3.5 as of recording is my preferred AI

tool so let's go ahead and download rust

and to download rust all we have to do

is run this Command MAC Ox Linux or

other Unix like OS and if you're on a

Windows you're using Windows WSL so

everyone is just going to use this exact

same command here so we'll paste it in

we'll download the installing we're

going to proceed with the standard

installation and we've gone ahead and

we've already installed rust now it says

to get started you need to restart your

current shell this will REO your path

environment and blah blah blah so I'm

going to go ahead hit the trash can to

restart my terminal pull my terminal

back up and we should have rust

installed if you want a more detailed

walkthrough you can go through the

getting started as well to get more

information to see if we have rust

installed we can run rust up-- help and

we should see an output that looks like

this rust up blah blah blah the the rust


tool chain installer and blah blah blah

all this stuff down here to make sure we

have the most upto-date version of rust

we want to run rust up update and this

will make sure we have the most

upto-date version of rust we going to go

ahead and clear so great we have rust

installed okay what's next other

dependencies this crate relies on

rocksdb if you face any compile errors

due to rock DB install the necessary

dependent with this so this is a Linux

command this is only for people on Linux

on Linux or yuntu so if you're on

Windows WSL or a Linux environment you

might need to run this as well however

if you're on Mac OS there might be some

other Oddities so be sure to check the

update section of this video to see if

there's any weird Oddities that you need

to install for working with Mac Ox here

so if you're on Linux you can go ahead

and run these install these packages

into your environment then we need to to

run the installation script so we're

going to run this installation script

here I'm going to go ahead and copy it

paste it into my terminal here boom

that's it so this just downloads this


install.sh and actually if we look in

our folder now we now have this

install.sh file in here it's kind of

this very long file I'm going to delete

it in just a second now we want to run

it if you're on WSL or Linux run sudo

install that sh if you're on a Mac you

can do that too I'm going clear going to

run this It'll ask you for your password

put in your password hit enter it'll say

installing script for era test node

it'll give you the operating system the

architecture download the binary blah

blah blah ah and since I'm on a Macos

this W command this W get command does

not exist so we actually need to install

this WG to go back to the GitHub repo so

with this course we can install W get if

we install this package called Homebrew

so if you want to install W get into

your Macos you can first install

Homebrew by clicking this link and then

pasting it into your shell you can make

sure you have it by just running Brew D-

version and if you get a response like

this you have home brew installed so

again this is Mac OS only and to make

sure we get this WG get command we can

just do Brew install WG

like so and it'll download this and


install this so and it might take a

couple minutes again this is Mac OS only

for again for Mac OS users once you've

installed it you can run wg- dhel or

version like this and you should get an

output like this or actually let's do

wg-- version wow what a long version

here huh that's pretty annoying then you

can run this command let's copy it paste

it in enter your password hit enter

and now we get we don't get that error

anymore we get successfully prepared

binary error test node has been

successfully installed to make sure that

it's actually working we get this

command now era test node we can run

let's do a little clear we can run which

era test node and we see it has been

installed to our computer then we do era

test

node-- version and we get the version of

it and if we do error test node run

oh we get something that looks very

similar to running Anvil so we get a we

scroll up to the top we get starting

network with chain ID L2 chain ID 260 we

get a whole bunch of Rich accounts with

which have private keys and pneumonics

and this is essentially the same as


Anvil but for a ZK sync Network we even

get this little RPC URL at the bottom to

kill it we're going to do control+ c

once again and I'm going to clear it out

but great we now have this installed you

can also install this optionally if you

want manually as well I think it's a

little easier to do it this this way

using the installation script but up to

you so now that we have the era test

node installed and again we're able to

run this you'll know you done it right

if you can run this and we are able to

run this the next thing that we're going

to need is the era compiler Viper so

let's go ahead and click this link from

the documentation and it will bring us

to the era compiler Viper GitHub

repository from matter Labs we can

scroll down and same thing we'll look

for the installation requirements here

are the supported platforms so if you're

not supported if your machine isn't

supported if you run into an error

unfortunately you'll have to skip this

section and you won't be able to use the

power of ZK sync but I'm sure your

platform will be supported if it's not

please make an issue on this GitHub repo

now in order for us to download this


again this is where your AIS are going

to come into help you if you run into an

issue we're actually going to go to this

release Tab and we're going to use

1.5.7 but feel free to use whatever

version is the latest if there's an

update to the version that we need to

install it'll be in this section of the

GitHub repo associated with this course

and it'll also be under this video in

cyphon updraft we're going to go ahead

we're going to install this version and

if we scroll down if we go to this

releases tab we scroll down we can see a

whole bunch of different files for this

each one of these files will work

depending will work on your operating

system depending on what your operating

system is so for example if you're on

Mac OS you can see there's a couple of

different Mac OS versions for us to use

and you might be asking uh I'm not

really sure which one to use if you're

on Linux or WSL these are the ones for

you to use and this can be a little

overwhelming to know which one to work

with so here's my recommendation just

copy everything like this go to Claude

and I'm going to say or what whatever AI


that you're working with I'm going to

add my name in here

Patrick uh yeah I acknowledge and

continue yeah sounds good let's begin

Claud Hau I'm using the free plan here

and here's what I'll say I'm looking to

download a package here are my options

I'm on a Apple

silicon Mac OS which do I download I'll

hit enter for your Apple Apple silicon

Mac OS you should download ZK Viper Mac

OS arm64 v1.5 package which is blah blah

blah blah blah blah and they are correct

if I go back over here I go back to the

releases if I go back to the

releases boom this is indeed the one

that I want to install cuz I'm on an

Apple silicon now let's do that same

prompt here let's go ahead I'm going to

copy this paste it in here say I'm

looking to download a package here are

my options I'm on a Windows machine

running

WSL windows

subsystem for Linux which do I download

for your Windows machine running WSL you

should download Z for Windows thatc

package okay uh this time it actually

got this wrong so that's not what you

should install um you should actually


install one of these Linux ones what

about if I'm on a Linux machine do I get

the musl or

gnu and this time it actually got it

correct for Linux machine I would

recommend downloading CK Viper Linux AMD

64 G blah blah blah which was blah blah

blah blah blah this is the correct

answer so if you're on Windows subsystem

for Linux or if you're on a Linux

machine this is the one that you should

install and if you're on a Windows

machine to make sure that you install it

in the correct place what you can do is

first select the one that you want to

download and normally if you just click

it it'll give you like a download option

we're not going to do that we're going

to uh we're going to rightclick it I'm

going to rightclick mine I'm going to

select copy link address and we're going

to go back to our terminal here and

we're going to type w

get- o which stands for output and we're

going to call it ZK Viper and then we're

going to paste that link in here so what

this is going to do is it's going to

download this call it ZK Viper and

download it into this folder here I'm


going to hit enter might take a few

minutes for it to download and it looks

like I've gone ahead and downloaded it

on the left hand side here we now see

this ZK Viper thing and it's going to

say hey this isn't supported because

it's binary right so this is actually

going to be a command line tool for us

if we run do ZK

Viper ZK Viper D- version just going

give me do slash oh and actually we get

permission denied because our operating

system denies access by default but we

can make this executable by doing CH mod

or pseudo which stands for super user do

chod plus X ZK Viper like this and then

it'll prompt us for our password and now

if we run SL ZK Viper D- version we get

a version out here

now the final thing we want to do here

is we don't want our zik Viper just kind

of hanging out in our repo here we want

to move it to a location where a lot of

our other executables are installed for

example if I type which Viper we see

it's stored at user users patrick.

local.

binv we could move our ZK Viper to this

location as well so I could run move CK

Viper to this location the exact same


spot that Viper is in slash like this

and now if I do which ZK Viper I get

user uh users patrick. local bin ZK

Viper and I can do ZK Viper d-el or

Viper Das Das version you could also

move it to one of these spots so this is

from a different Claud uh Edition user

local bin this is typically the spot

that I recommend for Mac OS and Linux

user local bin so you can move it there

instead if you want I might even move

users patrick. local bin to user local

bin oh and I got to do super pseudo once

again and now if I do which ZK viiper I

see it's at user local bin and I can do

ZK Viper D- version so AIS are

incredibly helpful for helping you

download stuff here and if you download

something and you run like ZK Viper D-

version and it's it's like and and you

get like an error like ah what are you

talking about there's a good chance that

you downloaded the wrong version so

you'd come back here maybe select the

other one and try to run that instead so

please take your time trying to install

these tools now if you have a hard time

getting this command in the GitHub repo

associated with this course I've given


this

wg- output ZK Viper release version chod

move I've given these commands in the

gab repo associated with this course in

in case you get lost or you forget them

or you just want to copy paste the only

thing that you have to add in obviously

is this release version you don't need

those little brackets there right and

you get that release version by right

clicking and then copying link address

like that depending on what release

version you want to get and like I said

if you download the wrong one no worries

just download the next one just download

the right one okay so take some time

learn to download and I'll see you in a

minute

okay welcome back hopefully you were

able to successfully download this

because this is going to give you the

power to actually work with ZK sync

deploy smart contracts to ZK sync and

that was the hardest part of working

with ZK sync it's done good job you

installed the tools so just to reiterate

though at this point you now have two

things installed you now have the era

test node like this era test node--

version should give you something like


this and then also ZK Viper D- version

like this now that we actually have

these tools installed what we can do is

moccasin comes built in knowing that

you're probably going to want to deploy

to ZK sync why well it's going to be a

thousand times cheaper to deploy to ZK

sync it's going to be faster it's going

to be this that the other thing so

behind the scenes and we've already seen

this there's a

networks. Pym so whenever we deploy our

smart contracts right if I oh I still

have all my weird stuff here um let me

zoom in when I do MOX run deploy I get

starting number is seven ending number

is 77 and this is secretly on the PM

Network I could even do D- network

network

pm and I'll get the exact same output

these two commands are equivalent

because my default network is pavm and

then I specified pvm and it goes okay

cool well the default network is pvm you

also specify pvm why' you do that it's

the same thing like whatever but

additionally there's another baked into

moccasin network if I now do MOX run

deploy
D- Network era VM and I hit

enter whoa that's pretty cool so what

happened here I know there's a whole lot

of stuff that just happened so I'm going

to scroll up for a little bit so if we

scroll up a well okay a whole bunch um

what we see at the top here is we see

running run command and then inside of

moccasin it starts up this era test node

technically this is inside of titano

with ZK sync but same same right so node

is ready at some random port or whatever

and what happens is we send the

transactions to this era test node we

scroll down we can see some different

events and some ZK sync stuff happening

in here on ZK sync you'll always see

this no EIP

11559 transaction available failing back

to Legacy ignore that for now you'll

also get this method not found that's

again because of some ZK sync evm stuff

but again they're just warnings and it

continues we see another transaction go

through we see some console logs blah

blah blah scroll down to the bottom

transaction mind ending number is 77 so

I'll do a little clear here but just

like that we now can use all the power

of this ZK rollup and just literally run


our moccasin as if nothing is different

so now with that little bit of setup now

all of our deploy scripts all of our

tests will be exactly the same now

what's interesting is technically these

are no longer Viper contracts when we're

running on ZK sync they're now

technically ZK sync contracts so the

typing is a little bit different but

moccasin is smart enough to treat them

the same this is another reason why

moccasin was built so that there could

be a tool that supported ZK sync right

from the get-go so we could use the

power of the ZK l2s getting too hype

getting too excited so now that we've

done that we can also do some more cool

stuff we could run MOX compile --

Network era VM which will do ZK sync and

we'll compile with ZK sync now what's

interesting here is if we go to this out

folder if we look in our favorites. Json

we'll see the VM has changed from evm to

AA VM and the bite code looks wildly

different to what it does on the EV M

that's because again the evm and the

arvm are very different the AI though

the application binary interface will

look exactly the same now if I were to


run the skin Let Me Clear I'm just going

to do MOX compile with no network which

means we're going to do PM we going to

hit MOX compile now in this favorites.

Json we see its evm we scroll up and the

bite code looks different again this is

now evm bite code the bite code before

was Era bite code era VM inite code and

that's kind of what's going on under the

hood that's a little bit different

what's important about this is now

additionally we can test that our code

works exactly the same in the evm world

and exactly the same in the ZK sync

world so we can also run MOX test--

Network arav VM and we'll run our tests

and we'll get a whole bunch of warnings

you don't have to worry about those but

we get three past six warnings these are

all warnings related to hey like ZK snc

this is a little bit different like

what's going on but all of our tests

passed meaning that our contract our

Viper code here where is it this favorit

ofi means it'll work the same on evm

networks and AA VM networks AKA are ZKA

rollups which is so exciting so now that

we've learned to test locally we can run

our deploy scripts locally and we've

installed ZK sync into our Network so


that we can actually work with ZK sync

is there anything else in the that we

need to do nope all we have to do now is

set up our Network and right in the docs

we have this one additional keyword that

we have to place when it comes to ZK

sync networks is this is ZK sync so

let's go

ahead and let's get this set up so now

we're going to learn how to deploy to ZK

sync sapoia which is going to be

basically equivalent to deploying to ZK

sync now it's going to be now now again

if you had a hard time getting testnet

aoia you're probably also going to have

a hard time getting testnet aoia ZK sync

so if you weren't able to get that no

worries you can simply follow along with

me watch sit back relax and enjoy

however if you want to be a badass you

want to go to the extra mile try to get

that test ZK sync and follow along here

so what do we do when we want to deploy

to new network well very simply we're

going to go to this M.L and we're going

to do almost exactly what we did for

sapoia with ZK sync so we're going to

create a new network below here we're

going to do networks. seolah hyphen zync


because ZK sync also has a test Network

called seoa we're going to create a new

URL to connect to sepolia and huh what

do you know our good friends at Alchemy

have given us such a network so if we're

go back to Alchemy I actually have

already configured ZK sync right if I go

to configure we have ZK sync turned on

ZK sync mainnet and ZK sync sepolia what

I can do is switch from mainnet to

sepolia and they will give me this HTTP

URL I'm going to copy this HTTP URL go

back here drop this into

myb file I'm going to say ZK ZK sync

sepolia SE sepolia RPC url url equals

paste this in here now for our URL in

our M.O I can do URL equals paste this

in here oh we need the dollar sign to

know it's an environment variable great

uh you can also additionally do a chain

ID equals 300 I didn't do that on any of

the other ones cuz moccas is smart

enough to figure it out but if you want

to do a chanity you can do that as well

I'm going to do save to DB is false

still we'll learn about the database or

the DB in the next section here I'm

going to say our default account name

equals default this is that one that we

used to deploy to sapoia and it's the


address that I've been using for this

course as well as of right now I don't

have CK sync test net set up I think

Kira set that up for us so I'm going to

have to do a little bit of bridging and

whatnot but save to DV false I'm also

going to do I'm also going to add an

Explorer Explorer URI equals and I'm not

sure what I want to use for an Explorer

so I'm just going to use the default

let's do MOX Explorer list oh my God

there's so many explorers um and I can

see in here there's this sapoia ZK sync

era it's a little bit down the line here

but this is the explore URI let's drop

this down so Explorer URI equals paste

this in here this back up we got the

Explorer type as well which is going to

be ZK sync explor ah okay so we're not

actually using block Scout for this one

explore or type equals ZK sync Explorer

the ZK sync Explorer here the one that

we're going to be verifying on is going

to be this explorer. zync doio this is

the Explorer that we're going to be

using and then finally the last thing

the last most important thing that we

need is we just need to do is CK sync

equals true and that's the last thing


that's the only difference between an

evm chain and a ZK sync chain that we

need now just is ZK sync is true that's

it just to tell moxin hey this is a ZK

sync chain we want to be sure we're

using the ARA VM we want to make sure

we're compiling with the ZK sync

compiler here so so we went over this in

blockchain Basics but if you missed it

I'm going to go over it with you again

now just to so that you are familiar

with this and know that this is normal

seeing this can be really daunting be

really scary but I promise you it's

normal so in my metam account here I

have our fig chain I also have our if we

scroll the way to the bottom our spolia

test net where I do have a whole bunch

of test net eth right we went to the

faucet in blockchain Basics where we

gave ourselves some suppo test net and

again this can be kind of difficult to

get once we have this we can

additionally hit this little network

drop down and metamask comes default

with ZK sync era main net but it doesn't

come default with ZK sync test test net

so what we can do to add ZK sync era

main net we can just simply hit add and

approve TDA got it and now we have our


ZK sync era main net added to our

metamask however there's no support in

here for ZK sync era test net so how are

we going to be able to see our test net

funds what we can do is we can go to add

a custom Network and use our Alchemy RPC

on sapoia to add this in so oh excuse me

once again I'm going to go ahead I'm

going to expand the view here and we're

going to do click this drop down add

custom Network I'm going to call it ZK

sync era or I'm going to call it C ZK

sync era sepolia default RPC I'm going

to copy this sepolia link from my

Alchemy add RPC RL paste this in I'll

call it sepolia ZK sync ZK sync add URL

enter a chain ID so the sapoia ZK sync

chain ID is 300 and actually gave me a

different name here uh okay great I'll

change the name sure thanks metamask and

then a currency symbol it even gives me

a suggested currency symbol eth we will

do that add a block Explorer URL I'm

going to actually use the exact same one

that was given to me that we're using in

Moccasin so I'm going to add that and

we'll hit save and now we have a zik

sync era mainnet and a ZK sync sapoia

testet account in our


metamask obviously we're poor and it's

blank we have no money in here um and

that's okay because next we're going to

learn how to bridge our funds from

sapoia or sapoia testet the stuff we got

for free over to the ZK snc sapoia test

net so we again we did this in

blockchain Basics if you already know

how to do this feel free to skip this

section and just go on to us actually

deploying and verifying this on ZK sync

but if you're unfamiliar with bridging

this is something you you'll want to get

very familiar with so we'll go to ZK

sync. and we'll go to the bridge tab

here now I'm going to go ahead and

connect my wallet here connect via

metamask I'm going to hit this edit

button to make sure I'm connected to the

ones I want I really only want to

connect with uh what do I want well

ethereum main net I don't see ethereum

main net in here but well actually I

only want ZK syn sapoia test net and

seoa so I'm going to hit update and

connect and great we're connected here

in my metamask I'm on the sapoia chain

and we want to bridge from sapoia to ZK

sync and what I want to do is yep since

I'm on the sapoia Chain I'll do a little


refresh

here and it hasn't detected that I'm on

a different chain so let me hit the

little little dots here so it's going to

say Network ah here we go ZK sync aoia

test net so we're going to switch to

that okay great now now it's detected

we're on the ethereum suppo a test net

and we want to bridge funds from

ethereum to ZK sync so I'm going to

bridge

0.1 eth from suia to ZK sync I'm going

to go ahead and hit continue I

understand proceed to Bridge and bridge

now I'm going to have to assign this

massive transaction typically if this is

a real transaction I'm going to check

the address that I'm interacting with

I'm going to check the data that I'm

sending but we'll learn how to do that

much later and since I'm on a testet

this isn't real money I don't really

care I'm going to hit confirm here and

we'll have to wait around 15 minutes for

this to bridge over and then we'll have

funds on ZK sync that we can use to

deploy our smart contracts all right and

now after maybe around 15 minutes of

waiting transaction has been completed I


can drop into my metamask here you can

see I'm down one sapoia eth on the seoan

network but if I switch over to my new

ZK sync simple a testnet I got our

tokens I can now see I have 0.1 eth in

my metamask this is EXC this is so

exciting and remember too this is going

to have the exact same private key as

the private key in my sepolia these are

going to share the same private key so

back in here the default for ZK sync the

default account here is going to be the

exact same as the default account for

here so now now that we've added

everything in here we have our Explorer

we have our Explorer type let's go over

to our deploy script our deploy script

looks good we're going to even verify

this as well let's now go ahead let's

deploy this to the ZK sync seoa test

net and we can do that with MOX run

deploy D- network

network network what's the name of our

Network here again spolia

zync Network spolia zync we'll hit enter

we will get prompted are you sure you

wish to continue type y or Y and hit

enter I'm going to type y it's going to

ask me to enter my password which I've

given mine a very lame password I


entered my password and now we have

transactions being

broadcasted we have our updated amount

updated and we have contract verified

which this one didn't print out the URL

but that's okay because we have our

contract address here enter your

password uh contract deployed here so if

I take this address now let's go over to

ZK synia so let's do ZK sync ZK sync

sepolia testnet Explorer you just Google

this seo. explorer. z. that looks

correct paste in the contract address we

can see this was deployed do a little

refresh here we can see somebody but it

called the store method on our contract

and if we go to the contract tab we can

scroll down we can see our whole

contract verified on the ZK sync

Explorer and if you did this you should

100% go to the getto repo associated

with this course there should be this

tweet me link for this section as well

same as before you know log in Twitter

sign up if you haven't and be sure to

tweet at zync that you just deployed a

smart contract using moccasin directly

to ZK sync you should be incredibly

excited and Incredibly proud of yourself


that you deployed a smart contract to ZK

sync and you even verify the contract

this is so exciting now whether or not

you deployed it to ZK sync doesn't

matter if you were able to do MOX run

deploy D- Network era VM if you didn't

actually get the test Nets aoya that's

okay if this was successful for you you

should 100% come to the get AO associate

with this course click this link send

this tweet or send your own tweet

whatever you want to do because you

should be incredibly proud of yourself

because this is going to unlock your

powers and being becoming a professional

powerful smart contract developer so

share this the community absolutely

loves seeing new developers enter the

community and I want to see you as well

so be sure to shout out say hi joining

the community is an incredibly powerful

part of your development Journey saying

hi to other people I know sometimes as

developers we like to be a little

antisocial but get get out there say hi

because we are all in this together and

we want to see your progress and

celebrate the small wins with you now

let's do a little bit of cleanup here

you might have this installed that sh in


here if you do we're going to go ahead

and delete that remove that you may also

have this era test node log in here we

can go ahead and delete that as well we

don't need either one of

those now here's something kind of

interesting and this is going to be a

little bit of a primer into different

transaction types and whether or not you

deployed this to znc doesn't matter be

sure to watch this so way way way way

back when we were working with boa and

web 3. piy we learned that we learned

about ethereum transactions right

remember we came to this this page on

the ethereum org website we learned

about kind of all the different you know

from to the signature NS blah blah blah

all this good stuff in here and then

additionally we learned that to deploy a

contract a transaction without a two

address where the data field is used for

the contract code so in ethereum if we

want to deploy a smart contract we have

the two address be blank we have the two

address to be blank however let's go to

our favorites contract right so the one

we just deployed and again if you don't

have this it's okay just just follow


along with me here and you can see on

the Explorer here there's this Creator

thing with an address and then at and

then right here is a transaction hash so

this is the transaction hash of the

transaction that was used to actually

deploy this smart contract

now if we scroll down into the data of

this transaction we see okay there's a

from here and actually it looks like

this matches right I do a little contrl

F or command F to see that these two

actually do match the from matches are

account that we used to send but the two

almost looks blank but

it's

8006 so the two address isn't actually

blank at all uh what's going going on so

the way that you deploy smart contracts

in ZK sync is actually a little bit

different instead of having your two

address b blank the two address of your

transaction is actually another contract

so this is a special contract in ZK sync

known as a system contract and on zky

sync this is the contract deployer

contract and you can literally read the

code which is written in solidity read

the code of this contract so this

contract has a fun function on it called


create and it takes a whole bunch of

parameters that well to be honest that

Titanoboa zky and that moxas handle for

us natively this is another reason why

we like using Titanoboa and Moccasin

because the a lot of the the weird

Oddities under the hood it handles all

of that for us but so ZK sync is a

little bit different in the sense that

we're actually we're actually calling

the function of a contract so like if we

want to be really really hardos about it

on just the ZK sync Network in instead

of doing favorites. deploy like this

what we could do is we could you know

create that transaction object we would

say to okay it's going to be this

address here you know from is going to

be you know whoever you know whoever

sent it blah blah blah and then we would

just populate these parameters of this

create function call so we could

essentially do like you know contract

deployer do this address to get the

contract

deployer contract equals this then we

could say then we could just do like

contract deployer contract. create and

then pass in the bytes the bite code and


pass in the salt the bite code hash and

then the bytes input which we would have

to learn how to convert our you know

Viper code into the B has and blah blah

blah but that's essentially what's

happening when we deployed our contract

instead of not having a two address we

send it actually to this address with

all the data to call this function here

so that's a little bit different about

ZK sync and that's what moccasin and

titano and Titan zyn are all handling

under the hood for

us now something else I want to talk

about and and Prime you with is

transaction types so we're not going to

do a full Deep dive explainer however if

you want to read this article that we're

going to link in the GitHub repo

associated with this course you can go

ahead and do that so I kind of have been

glossing over this but again if we do

box run deploy D- Network era VM you

know we get all this stuff here but we

get kind of this warning that keeps

popping up no EIP 1559 transaction

available failing or excuse me falling

back to Legacy um so what's going on

here well in the blockchain world

there's actually several different types


of transaction types and I kind of

glossed over it here when we went over

the transaction object where we said

okay here's what a transaction looks

like it has it from to gas limit fee

blah blah blah but there's also a typed

transaction envelope we can also pass a

transaction type in that rlp encoding

now what what makes it kind of confusing

is that it's actually not in this little

little Json blob here right it's

actually outside of the the Json blob

but again we're getting kind of low

level doesn't really matter where it is

all you need to know is there are

actually multiple different types of

transactions the ethereum website does a

decent job of kind of walking you

through some of the different types of

transactions but you can also look at

them in the cyphon updraft so what's

happening is when we get this this

warning hey uh no EIP 1159 or 1559

transaction available following back to

Legacy is that ZK sync works with a few

different types of transactions like

Legacy transactions and they have a

couple of their own custom transactions

themselves the main transactions or the


new normal type of transactions on

ethereum are known as these type 2 or

EIP 1559 transactions again if this is

going over your head a little bit don't

worry about it too much but this type of

transaction doesn't exist on ZK sync

right this is essentially like an

advanced gas type of transaction and

zync has them in by default so what

happens here is that our tools try to

send a type two transaction this super

gas this EIP 1559 transaction onto ZK

sync and ZK sync says hey uh we don't

have those we're already like pretty

darn gas efficient so moccasin and

titanable will always try to send an EIP

1559 transaction first but then it'll

revert back to a legacy transaction for

ZK sync now when we're sending on

ethereum it will work with a type two

transaction it will work with a type two

transaction you can also send type zero

transactions on ethereum but you

shouldn't because they're kind of worse

for gas and like gas is money so you

don't want to spend more money so pretty

much nowadays everyone sends type 2

transactions on ethereum on CK sync they

send Legacy transactions because the gas

on zync is just better I'm kind of


glossing over the details and this is

kind of it from a high level that's why

you're seeing this era here is because

there's multiple different types of

transactions one of the coolest types of

transactions is this EIP 712 or an ox 71

or a 113 transaction which is known as a

native account abstraction transaction

action I know that's kind of a mouthful

we won't be learning about that in this

curriculum however if you want if you

want to go over it with slitted examples

we have a transaction types module and

Cypher updraft in the solidity side all

the concepts are going to be the same

just the examples are going to be with

solidity so if you want to learn more

about transaction types you can go check

that out over

there all right so you have one last

thing to do before we wrap this up I

have a little a little few workshops for

you

we have four things for you to do the

first thing is deploy your script deploy

your contract to your tenderly virtual

Network so back in our code here we

learned all about adding a new network

here right so if we wanted to add a new


network for tenderly maybe we go you

know networks. our fake chain dot dot

dot what else do you put in here how do

you deploy to your own tenderly virtual

Network so that's your first Workshop

thing so that's step one next write your

own deploy script and deploy to the pvm

network so right in the scripts area

maybe create a file called my deploy

dopy or something and in here I'll even

give you some boiler plate here right so

I'm going to do paste this in here I'll

do deploy Me Def deploy me print hello

ready and now to actually run this oh

and I'll get rid of this as well MOX run

my deploy hello so write your own deploy

script in here okay that's your little

little cheat sheet here and again do

this without the aid of AI do this all

yourself next write your own deploy

script and deploy to the ARA VM Network

although you definitely know how to do

this already-- network arvm right like

this hello deploy your contract to the

arvm and then finally write a new test

in your test file and run it so back

here in tests we have test favorites.

test favorites. py what you should do is

you should add your own new test in here

and if you do you know let me do clear


MOX test like this and you see four pass

in you know however many seconds that

means you did it successfully so those

are your four workshops be sure to pause

and actually work on them this is what's

going to drill in the skills remember

repetition is the mother of skill and we

want you to be incredibly skillful now

before we wrap up here in the GI up repo

associated with this course we scroll

down a bit we go to where are we Viper

Viper 101 remix buy me a coffee got a

little workshop for you here there's

three things that I want you to pause

the course and I want you to try to do

these on your own spend at least a half

an hour on all three of these if you end

up spending more than a half an hour

don't worry you know maybe drop into the

Discord drop into discussions or talk to

an AI about where you got stuck don't

spend more than a half hour on these

unless you're really really really close

in which case go ahead and finish them

out but these are the three that I want

you to try to do yourself so the first

thing I want you to do is get the price

of a different asset using chaining

price feeds on your fake chain so


remember when we deploy this contract

right when we compile when we deploy

this contract where is the deploy we

pass in a price feed so how can we how

can so can we get the price of a

different asset right now we have this

function down here get e to USD rate

what if we just change this to like get

rate and we passed in you know and we

passed in one could we get the rate of a

different price H remember this will

only work on your remember this will

only work with your tenderly virtual

Network so if you're having a hard time

working with the tenderly virtual

Network you can also skip this one this

one's very much optional but this second

one you should be able to do write a

function to get the total amount of

funds in the contract right so if we're

we're back here in the contract we could

100% do at at external at view def get

total and just say you know returns you

256 return self.

balance boom we'd be good to go here but

don't do that this is kind of cheating

what I want you to practice is up at the

top we have our funders Dynamic array

and the funer to amount funded I want

you to Loop through this array get the


address of every fun and then pop it

into this funders to amount funded and

just add up them manually so we've

learned about loops here we've learned

about arrays we've learned about

mappings so this one this one I

absolutely want you to go through Loop

through the array of funders see how

much they fund it and add it to some

taking up total and then finally this is

the most challenging one write a

function that allows you to change the

owner of the contract and a quick hint

remember our owner up at the top is a

mutable which means it can't be changed

so we would have to remove this from

being a mutable so some type of function

that allows us to change the owner to

somebody else now like I said I want you

to spend no more than 30 minutes on on

all three of these and if you get stuck

be sure to use your AI assistance 2 and

at the end of that 30 minutes if you

still can't figure it out go ask Claude

go ask an AI assistant where you're

going to get and and if you can't figure

it out pause take 10 minutes off take

maybe 15 minutes off take a day off

whatever you want and come back and


start working with an AI to work through

these questions and how you can solve

them so pause the video just pause the

video your Workshop is next and I'll see

you soon

and with that I have crammed so much

information into your brain that you

should be bursting at the seams with

information and we're going to take some

time to wrap up so that you can go on an

ice cream break or a gym break or a

coffee break or whatever kind of break

that you would like to go on we've

learned a ton in this section so let's

do a quick recap of all the things that

you've learned so you can take a break

first of all we were introduced to this

tool called moccasin which is this

titanoboa based smart contract

development framework which allows us to

test deploy and work with our smart

contracts in a much simpler way we spun

up a brand new moccasin project and we

learned a ton of stuff first off we

learned how to even test our contracts

which is a crucial piece of our journey

and we know that no one's going to take

our code seriously unless we have tests

tests are absolutely crucial to your

smart contract development Journey we


learned how to write test using moccasin

pest framework and additionally we

learned about how fixtures can help

write our tests to be faster and even

more proficient we learned how to write

a deploy script in Moccasin using this

native import syntax like from SRC

import favorites where we can actually

just deploy our contract with the deploy

keyword and then additionally right

inside moccasin we can verify our smart

contracts with just one or two or I

guess three here three lines of code we

learned how to switch between networks

in Moccasin if we want to work with a

different network all we have to do is

add the information about that Network

to our moccasin dotl under the networks

area and we can deploy to different

networks just by running mock run deploy

with D- Network and then the name of the

other network that we want to deploy to

if we don't specify a network it will

use the default Network and Moccasin

defaults to the pi evm which is this

fake locally run Network we also learned

that moxin comes built in with the era

VM if I do MOX run deploy D- Network era

VM I get an output where we're running


kind of a locally running Anvil but for

ZK sync directly in our terminal and we

can test and deploy to ZK sync we

learned about encrypting and decrypting

our wallets so if I do MOX wallet list I

can see a list of accounts that I've

encrypted locally so that I don't have

to expose my private key oh my gosh that

feels good that feels good and I know

that if I were to you know for example

let's spin up let's spin up anvil on

another terminal if I were to do MOX run

deploy D- Network Anvil and I were to

get rid where is it and I were to get

rid of the unsafe password file it would

prompt me for my password meaning my

keys can stay secure I will not be

sharing my private keys with you

although this one the password is just

password which is a terrible password

but you get the picture we learned how

to do that we learned how to deploy

toola and to ZK sync spolia and if you

didn't actually deploy there no worries

you got to see the process you got to

watch us automatically verify these

contracts on different explorers like

block Scout and ZK sync Explorer we

learned we could compile our contracts

and we learned we could compile them


both with evm or with ZK sync evm we

learned a little more python we added

type hinting into our scripts here we

learned about environment variables and

how ourv file can have environment

variables we know that it's not a great

place to store private Keys it's it's

more okay to store RPC URLs because

they're not that sensitive private keys

are very sensitive and we learned a

little bit more about python here where

we added some dependencies for our

project so that our linter our little

syntax highlighter worked correctly

youve learned an absolute ton in this

section and you should be incredibly

proud of yourself now if you haven't

shared on Twitter or on some social

media I'm going to just tell you one

more time you absolutely should you

absolutely should joining the developer

Community is going to a increase your

chances of getting a job if that's what

you're looking for B you're going to get

to meet a ton of really cool phenomenal

people and C give you a chance to yeah

join like-minded individuals you can

join here or if you're on cyphon updraft

you can of course join the Discord and


meet a ton of other like-minded

developers as well that being said huge

congratulations for getting this far and

huge congratulations for finishing mock

favorites all right welcome back to the

next section of this moxas Viper in

Python smart contract developer full

course we're going to keep it moving

right along oh oh we got a nice cool

little background here now repo's coming

along very well we're going to keep

moving on along here and we're going to

going to be the next section the

moccasin five more oh looks like uh repo

is slowly coming along very nicely this

is going to be the final code and this

will be the final time we work with our

favorites contract adios favorites

contract we will see you no more however

we're not just working with the

favorites contract we're going to be

working with a few other contracts here

now let me show you what we're going to

be working with but let me show you what

we're going to be learning in this

section here so I've got the completed

code ahead of me and unlike most of our

tutorials unlike most of our curriculum

this will also be the last time we don't

have any tests from here on out we will


always have a bunch of tests for you to

work with and for this one we're

actually going to be focusing mainly on

the contracts we're going to do barely

any tooling we're going to learn a

couple of really cool really important

Viper features which is brand new as a

0.4.0 which is modules so we have our

favorites contract which is once again

it's going to be the favorites contract

nothing to see here we have created two

additional new contracts and we have

this thing called an interface now I

know we've done interfaces in the past

with buy me a coffee but now this is an

interface that is its own file the major

things we're going to be working with

here is we're going to have a favorites

Factory we're going to create a contract

that can create other contracts and then

can interact with those contracts with X

call which we haven't worked with and

then also the static call and then

additionally probably the most important

contract with the most important

learnings is going to be our five more.

VI file here because we're going to

import favorites we haven't done any

Imports in our Viper yet we have done it


in Python but we haven't done in Viper

and we're going to have some weird new

things like initializes favorites and

favorites. AIT what you what and then

this exports at the bottom what is going

on so this section is all about modules

we're going to be playing a whole bunch

with this contract and everything that

we're going to be learning is going to

be in this script this one single script

where we're going to do a whole bunch of

print statements basically to learn

everything in this so This should

actually be a kind of a quick pit stop

here just to learn about modules and

then we're going to go on to the more

advanced buy me a coffee where we will

learn way way more advanced ways to test

deploy and work with our smart contracts

so let's jump

in all right we are back once again in

our main MOX CU folder which at this

point we do a little LS we're starting

to build up a nice little collection

here and we're doing this intentionally

because this is going to be your catalog

for yourself of your Learning Journey

here these are all things that you

understand that you've been through and

pretty soon we're going to start pushing


these up to GitHub if you go back to the

GitHub repost assed with this course we

have section six starred because this is

where we're going to really start to

build our portfolio because this is

where we push our codebase up to GitHub

and if we scroll down some more we have

this how to get hired which is going to

be a real quick section it's not going

to be as it's not going to be very long

but finishing this section is a crucial

crucial prerequisite for how to get

hired I know some of you are here to

learn you're not here to get hired those

of you who are just want to learn you

can go ahead and skip that section great

so we're back here we're going to do a

little clear and at this point you're

starting to know the drill of what we're

going to do which is good because again

repetition is the mother of what skill

that's right so back in here we're going

to do mkd or make directory we'll call

it MOX five more CU which stand for

Cipher updraft CD press tab five more CU

and then either code period or file open

to open this vs code up in its own

window here I'm going to zoom in a

little bit with command plus or Control


Plus or whatever you like to do so now

that we're in here if we go pop open our

terminal we should have MOX still

installed right if I do MOX D version I

have MOX installed remember we're going

to be using whatever version of moccasin

that is specified in this moccasin

version area so and then use the install

command whatever install command that

the course gives you so that you're

always working on the exact same version

of moccasin that the course supports at

the moment to get started let's run a

MOX init --vs code d-p project and

additionally you can also put the file

path of the directory that you want want

to create a new project in for me I want

to put it in the current directory so I

could just put a dot putting nothing

there is the same I could put like my

folder slashy other folder you know

whatever you want to do here I'm going

just going to put a dot here I'm going

to hit enter running command and if I

pull up my file explorer now I have all

the files and folders that I am

accustomed to okay great so now I'm

going to clear things out and we're

going to go ahead and get started I'm

going to open up test Scripts and SRC


and I'm going to click click click click

command click all these or control click

all these and I'm going to go ahead and

delete them we're going to start from a

blank setup here maybe I should add a

command tamasin like Dash d blank or

something that that might be helpful but

I have everything in here that looks

good so now to get started we're going

to First grab once again as we've done

100 times now we're going to grab that

favorites contract for the last time so

let's go over to this skab repo let's go

to SRC grab that favorites. VI scroll

all the way to the bottom copy it come

back over new file

favorites. VI paste in the favorites

contract in here oh looks like I grab

the one with evm and stuff on it okay

looks good and just to make sure that

this works well let's do a little mock

compile just to make sure it compiles

and it looks like it's compiling great

so that way we know that this cont

contract is being compiled awesome so

let's already jump into this so we're

going to create a different contract in

here that will actually deploy this

contract which sounds a little wild so


let's actually create a new file and

we're going to call it a new file and

we're going to call it

favorits because this is going to be

what we call a contract Factory it's a

contract that creates other contracts

now to do this we're going to use a

keyword now to do this let's first jump

to the Vier documentation and take a

look at this I'm going to look up this

create copy of I'm going to hit search

in here and I have this we get this

built-in functions and let me scroll up

just a little bit here scroll up Scroll

up Scroll up Scroll up chain interaction

Viper has three builtins for contract

creation all three contract creation

built-ins rely on the code to deploy

already being stored on chain

but differ in call versus deploy

overhead so this is where things get a

little bit Advanced and I'm going to be

honest with you a lot of this isn't

going to make sense until guess what all

the way down and Moccasin upgrades so if

it doesn't make perfect up sense that's

okay it will make sense way way way down

here or you can always work with AIS if

you're extremely excited to learn more

so we're not going to look at create


minimal proxy we are going to look at

create copy of we're not going to look

at create from BL blueprint and we're

not going to look at create benal proxy

2 we're going to just we're simply going

to look at create copy of So reading the

documentation here it says it creates a

bite forbite copy of runtime code stored

at Target cheap to call no delegate call

Overhead again this is a key word we're

going to learn much later expensive to

create does not have the ability to call

a Constructor performs in xcode size

again something more advanced that

you'll learn much later but it's this

keyword create create copy of that we're

going to call to literally create a copy

of another contract so as you kind of as

you can read from this first line here

it says it creates a bite forbite copy

of runtime code stored at Target so in

order for us to call this contract we

have to have deployed our favorites

contract someplace else now for a little

visualization of how this works imagine

that this is your blockchain and and on

this blockchain these two contracts are

already deployed I know we haven't

written this favorites Factory but I'm


showing you kind of what it looks like

so this favorites. VI contract exists on

the chain and we've done that maybe a

hundred times at this point right we've

deployed this contract so many times we

know what it's like to deploy the

contract this contract on chain is going

to have a whole bunch of bite code it's

going to be a whole bunch of zeros and

ones we've seen it as hex it's got all

this bite code and that bite code

describes all the functions and how it

works Etc what our favorites Factory is

going to do is it's going to look there

favorites Factory eyes it's going to

look at this data here and go oh I see

that data let me uh huh let me grab that

and it's going to store it's going to go

let me grab that and it sees this boo

here then what it's going to do is it's

going to call this create copy of

function and it sees this contracts

address here and what it's going to do

is it's going to take the favorites. vi

address pass it into create copy of and

the create copy of function is going to

take this bite code and go oh well oh

well here's how you create this contract

and so the favorites Factory is going to

deploy a new favorites. Vi at a new


address because it can see this address

as bite code so it's almost going to do

like a like aoop how do I do like a

Schoop here it's going to see all that

bite code it's going to say let me let

me let me get that bite code real quick

and then it's going to deploy its own

version of favorites. VI with the exact

same bite code so let's go ahead let's

implement this create copy of function

so remember like we said the first thing

that we're we are going to need is that

original favorite contract address so we

could save this a number of different

ways I'm actually going to save it as a

state variable but of course first we

got to do pagma version 0.4.0 woo feels

good it's been too long since we

actually coded some Viper in here huh

then at license MIT MIT like so so now

I'm going to create a state variable

called

original favorite contract of type

address so I'm going to store this as a

state variable called Original favorite

contract and right when I deploy this

Factory I'm going to pass in that

address so and

deploy
deore anit and it looks like my co-pilot

is even telling me what to do original

favorite contract address call in here

Here self. original favorit contract

equals

original

favorit contract so okay great so we

have this deploy function where we can

save that let's now create this function

where that actually creates the

favorites contract so we'll do new

function we'll do at external def create

Bal Ritz contract like this and we'll

say new favoritz contract of type

address equals create copy of and we'll

do

self. original favorite contract I'm

going to copy that and paste it in here

like that and now we should probably

save this new contract somewhere so I'm

actually going to create a list of

favorite contract so I'll do list of

favorite contracts and this will be a

public address array and you know what

we can make this a regular array I'm

going to make this a dynamic array by

doing D array of address and we'll give

it a Max size of 100 so since we now

have this I can do list of favorite

contracts dot append new favorite


contract oops excuse me self. list of

favorite contracts. you'll even see

little red squiggly pop up saying hey uh

list of favorite contracts is a storage

variable you got to access it with self

so I'll add the self here nice so this

is all you need to do boom this is how

you can create contracts from other

contracts that's it that's pretty cool

huh well let's go one step further let's

have our Factory contract be able to

interact with those contracts not only

will we be able to create different

contracts but we should be able to

interact with them as well for example

our favorites contract should be able to

call let me zoom in just a hair here the

store function the itself and that

should be able to change the variable on

the favorites contract that I just

deployed so let's go ahead let's add

this functionality so I'm going to

create a new external function called

def store from factory and we're going

to take some inputs here we're first

going to take an index of one of the

addresses in here so for example you

know at index zero would be like ox 1 2

3 4 blah blah blah whatever this would


be the first favorites contract that was

created then at index one AKA spot two

there would be a different address and a

different address so we're going to take

favorites index which will be of type un

256 and we're going to pass in a new

number which would be of Type U 256 like

this and we're going to have

like I just showed you here we're going

to have our favorites Factory call a

function on our favorites. VI similar to

what we did with the chain link price

feed now since we're going to store

we're actually going to change some

state right we're going to change some

state of the store we're going to change

some state of that contract so to do

that instead of doing static call which

we've done before we have to do X call

which means we're not just reading we're

actually going to write data we're going

to change the value of the favorites

contract but now the question is uh okay

well what what are we what are we

calling here remember what are the two

things that we always need to interact

with a contract well we need the what we

need the address and we have that that's

going to be from this array and what


else do we need well we need the ABI H

well how how do we get the ABI well last

time way way way back in the buy me a

coffee code where is that buy me a

coffee code that's way up here in the

buy me a coffee code what did we do buy

me a coffee we scroll down ah we used an

interface oh okay cool because the

interface gets compil down and gives us

the API great so let's just make a

little interface at the top here so we

can interact with our contract so let's

do a little interface

iore faval Ritz and we'll say def store

new number U

256 nonp payable right does that look

similar to this yes except for this is

non-p payable instead of view because

this is actually a function that's you

know these were all view right but this

is not a view function because it's

actually updating State great we could

100% do this however I'm going to tell

you right now we're going to do this as

little as possible and why might you ask

well because sometimes you're gonna have

interfaces that have this many functions

and you're going to come to your

contract and there's just going to be a


huge interface with a ton of functions

or you're going to have a ton of

interfaces and it will just clutter up

your code and we are not cluttering up

our code I like to be lazy I like to

have my code be very clean I don't want

that to clutter up my visual space here

so what we can do instead is we can

actually create an interface as a

standalone file as a v Yi file to

signify that it is indeed an interface

so on the left hand side here I'm going

to right click I'm going to select new

folder and I going to create a new

interface

iore

favorites.

vyi not excuse me first I'm going to

create a folder called interfaces and

then a new file called if favorites.

vyi now the Viper Community hasn't

really settled on a convention for the

naming of interface files because these

are actually relatively new in the

language but I like this iore format

here so that's what we're going to use

now the interface that we did here is

called an inline interface and that's

actually very different than an

interface that's a whole file so as a


whole file it's going to look a lot more

like it would as if it was actually a

regular Viper file so to make our

favorites interface what are the

functions that we're going to want to

get well for now let's just create these

two functions to create those two

functions I would do at external def

store and we would do actually the exact

same setup here doesn't really matter

the name store doesn't matter the name

of the variable but we'll say new number

little colon here and then we'll just do

dot dot dot remember interfaces don't

have any logic they only have function

definitions so that's it for the store

for the retrieve we would do at external

at view to signify this as a view

function then def

retrieve and it returns a un 256 like

this and then of course dot dot dot and

that's it and we can even in our

terminal clear little run a little MOX

compile we'll see compiling two

contracts this I favorites. vyi gets

skipped our moccasin is smart enough to

know that okay this is a interface so we

don't need to to compile the interface

here so now that we have that in our


Factory we can import this in here it's

also something that we haven't done yet

we're going to import this in here right

at the top of our file we're going to do

a very similar syntax to python almost

identical actually we're going to say

from

interfaces import I favorites you don't

need the vyi and now now this one line

right here is basically the exact same

as doing an inline inter face right here

right so I know in this instance you

might be saying hey Patrick uh the I

inter the if favorites. vyi actually has

like way more code the in line is like

way nicer well agree to disagree so this

line here is equivalent to these three

lines so we're going to go ahead because

what this one line is doing is literally

taking this VII file literally

converting it into this and sticking it

right in our file so we can even make

sure it actually works by running MOX

compile the terminal looks like things

compiled successfully and if you want

you can even do a little line like that

just to make sure MOX compile even works

and great it's giving us an error saying

this as DF thing is an error and that

makes sense because it is an error so


let's get rid of it so now that we have

this ey favorites we can actually call

this so we could do we could say

favorites contract of type I favorite

rits equals self. list of rits or list

of favorite contracts at index favorites

index like this excuse me we can say

address favorites address equals self.

list of favorites at the index that we

want to get so we're getting the address

from here then we're going to want to

wrap this up in this interface remember

we did this before with the price feed

stuff right down here to get to we

wrapped the price feed address in the

aggregator V3 interface to get a price

feed object of type aggregator V3

interface and that way we can call the

functions on it right so if we wrap this

address up we can call these two

functions on that address so what I'm

going to say now is I'm going to say

favoritz contract which will now be of

type I favorites equals icore excuse me

yeah iore favorites at address favorites

address and now finally we can call

store from Factory with an X

callit contract. store new number now

let's go ahead and let's test what we


have so far and then we'll add one more

function in here and we'll tweak one

more piece in here as well

so let's write a deploy script test this

out so in our script section let's do a

new file we'll call it deploy dopy but

you can call it run whatever you want

and let's go ahead let's do a little

defa moccasin main like this and we'll

call what do we want to call this we'll

first deploy that initial favorites

contract because again the favorites

Factory needs the original favorite

contract so let's go ahead let's create

a function called deploy faval rits like

this and now we'll make a def deploy

favorites and we'll do a little pass

here for now up at the top here we're

going to grab that favorites contract by

just doing from what's the name of our

folder SRC from SRC import

favorits like this then we'll do

favorites. deploy like this we'll say

fav

oritz contract of type Viper contract

yep we're going to do a little bit more

type checking here again if you don't

want to do the type inss you don't have

to I'm going to say from moccasin booat

tools import Viper contract here I'm


getting this little squiggly lines

that's going to annoy me so I'm just

going to do a little UV add moccasin

like this my vs code says hey we noce

you're doing a blah blah blah do you

want to select it yes I do and it looks

like it's gone ahead and set up my VV as

my python pass so I lose all those

squiggly because now I have a little BNB

nice again that is optional you do not

have to do that great so now we have our

favorites contract let's just go ahead

let's return it and then we'll add a

little bit of type hints to our function

here boom and that's it that's how we

deploy our favorites contract so we'll

do deploy favorites we'll say favorites

contract

equals deploy favorites I did a little

copy paste here to get it going

favorites contract equals deploy

favorites and then on a new line we'll

now deploy our favorites Factory I'm

going to do a little

deploy Factory and I'm going to pass in

this favorites contract which means I'm

going to create a new function def oops

def copy this paste this here deploy

Factory takes in a f
oritz contract of type Viper contract

like this and what are we going to do

well we're going to need to get this

favorites Factory object from our SRC so

we'll say from SRC import favorites

comma

favorites Factory like this and then

we'll do favorites factory. deploy and

we'll pass in this favorites contract

now technically the deploy function of

favorites Factory takes an address

but Titanoboa and Moccasin are smart

enough to know oh you're passing in a

contract you probably meant the address

so it just use the address but if you

want to be explicit you can also do dot

address in here so we're going to deploy

our favorites Factory with it knowing

the address of the original contract and

then all we're going to do is we're

going to call this create favorites

contract on our Factory so we'll say

favorites

Factory dot create favorites contract

and this function what's it going to do

well it's going to store a new favorites

contract in this public array so what we

can do then is we can grab that address

we can say

favorites address or better at new


favorites address equals and this will

be of type string so in Python addresses

are of type string in Viper addresses

are of type address but in Python

they're of type string so new favorites

address of type string

equals favorites Factory dot we're going

to get it by calling the list of

favorites contracts because that's a

public variable we'll say dot list of

what's it called list of favorite

contracts I'm just going to copy paste

and since we've only added one item to

the list right we only called this one

time we're going to grab the zeroth

position now something important to note

when we're calling Viper arrays from

python we use thises when we're calling

arrays in Python we're going to use the

square brackets so I know it's a little

confusing the more advanced you get with

python and with Viper the more that

distinction will start to make sense so

list of favorite contracts at position

zero we'll grab that address now we've

done this before we have an address

we're going to need to assign it in ABI

and we can do that with the at function

which we've done before form so I'll say


new faval Ritz contract of type Viper

contract equals

favorites. new favorites address so now

we have two favorites contract we have

the new favorites contract that our

Factory deployed and we have our

original favorites contract that we

deployed these are at two different

addresses we deployed this one our

favorites Factory deployed this one so

now what we can do is we can even get

this one kickstarted we could say

favorites contract new favorites

contract. store we could get started

with 77 we'll do a little print line

little print F stored value

is and then a little do the call right

in here actually we could do new

favorites contract.

retrieve like this me zoom out for a

second now if we just run this MOX run

deploy it'll run in the pi evm Network

oh Viper deployer has no attribute

create favorites contract create

favorites contract ah okay it's because

we deployed it but we forgot to save it

so I'll say F Factory contract equals

and then I'll do Factory contract.

create favores contract and this should

be Factory contract and the rest looks


good forgot to save it as a this is a

Viper contract whereas this is a Viper

deployer great so let's try that again

MOX run deploy stored value is 77 so we

have

successfully created a contract that can

actually deploy another contract and

this is a really powerful primitive that

we can use in smart contract development

especially if we want to verify that a

contract is legit we can just check who

deployed it or more importantly what

deployed it and if you're going to be

deploying contracts if you're building a

system that's going to be deploying

contracts quite often it's much safer

and more accountable to have some type

of factory contract some type of

deployer contract like this okay

great so we say okay Patrick I I see

what you're saying but can the factory

really update the number like this and

the answer is well absolutely so now

we're going to call store from Factory

on the factory contract and it'll update

the favorites contract right so watch

this okay so now we're going to do

factory contract dot store from Factory

Store from Factory 88 or excuse me we


have to do zero and 88 because store

from Factory what does it take takes the

favorites index and the new number this

is the index of the contract in the

array since we only have one contract in

the array the index is zero aka the

first one in the array and the new

number is going to be 88 now we'll do a

couple of print lines so first we'll do

print F new contract stored value is new

favorites contract my co-pilot even kind

of gave me the rest of it new favorites

contract. retrieve like this and we can

also look what is at the original one so

we'll do a little print F

original contract stored value is is and

then I get a copilot once again it's

giving me the answer I just hit tab to

figure it out now we'll clear the

terminal we'll run this again we'll see

the stored value is 77 new stored value

is 88 and the original is still seven so

this goes to show that what we did if we

go back to our little diagram here was

well we called

77 then we updated it to 88 right we

called 77 we updated it to 88 but our

original favorites VI its value stayed

at 7 the whole time because we were

interacting with this one over here now


we could update our favorites Factory to

also be able to update this one but we

didn't do that I mean we could but we

didn't so boom so what's

next well I want to do just a little bit

of refactoring here really quickly just

to show you something cool that you can

do this I favorites interface we can

also store contracts not just by address

but we can store them as type I

favorites so what I can do is instead of

storing this as an address I could store

this I could store these as this I

favorites type if I do that I'm actually

going to get to save an extra line of

code so down here when I call self.

listof Favorites contracts at the

favorites index it's not going to give

me an address anymore it's going to give

me an i favorites so I can do is I can

say instead of favorites address I can

do favorites contract of type I

favorites and then just delete that next

line additionally when we do self.

listof favorites contracts. append we

would have to wrap our new favorites

contract as type I favorites so you

don't have to do this if this if what I

just showed you is actually very


confusing to you and you're like what

the heck did you just do feel free to

just move it back to what it was right

which is which is uh this one right here

feel free to just move it back to what

it was and go with that whatever is

easier for you this is your Learning

Journey and you can come back to this

later and go okay what did Patrick mean

by that let me ask some AIS etc etc this

is another way that we can actually

store and work with these

variables now one more thing I want to

do is I want to add a little view from

Factory function this one is going to be

pretty easy as well let's do a little

external at View view from oops view

from Factory

favorites index of type un 256 it's

going to return a un

256 and we're just going to return

static

call of

self. self. list of favorite contracts

at whatever index well square brackets

again in Viper for arrays use the square

brackets do

retrieve now this is kind of a more

advanced line here I'm I'm like chaining

a lot of stuff together this one single


line is equivalent to me doing okay self

list of favorites contracts I could say

favorites favorites contract of type

iore favorites equals self-de favor

contracts of favorites index and then I

do value of Type U 256 equals X call

Favorites contract dot retrieve and then

return value uh oh value is a keyword

right is that what it's going to be mad

about oops sorry this is a static call

not an X call so I could 100% put this

into three lines but this setup that

we're doing here is basically equivalent

to chaining these all together right so

since self. list of favorite contracts

at favorites index returns a favorites

cont contract I can just directly call

retrieve on that favorite contract and

then I can just directly return that

whole thing so there's typically a lot

of ways that you can chain lines

together and it's usually up to you with

how readable you think this is a lot of

people might read this and go I have no

idea what this is doing and prefer to

use kind of this more readable setup but

then some people might see these three

lines and go oh my God that's three

lines that could have been one line so


there's this is kind of your preference

if you like the one line go with the one

line if you like the three lines go with

the three lines they both do pretty much

exactly the same thing make sense great

now I've crammed a lot of topics in your

head we've learned a lot of Viper

already here the next piece we're going

to learn is about an exporting Viper

modules and it can get a bit complicated

can seem a bit complex so if you haven't

taken a break yet now is a great time to

take a break and I'll see you in a bit

all right welcome back so now we're

going to be working and learning about

Viper modules here so we're going to go

ahead we're going to create a new file

we're going to call it f

more. VI and this is basically going to

be the exact same as the favorites

contract except the store function is

going to add five to whatever you store

so on our store function here we're

going to do we're going to basically

have this function but we're going to do

self equals my favorite number equals

new number plus 5 that's it that's

essentially all that we're doing however

we want to keep all the functionality of

the rest of this code now well what's


what's one way we could do this well we

could copy this whole thing and paste it

in here and then I could do you know

store plus 5 and then boom but this

violates a principle called dry or don't

repeat yourself ideally we want to not

copy paste other parts of our code as

much as possible this helps us refactor

much easier later on it also makes our

code more posable there's a lot of

reasons why if we want to reuse some

code we've already written it's not

great to copy paste imagine we had 20

different variations of this favorites

contract we'd have to copy paste 20

different contracts and what if we

wanted to update a function we'd have to

update it 20 times but what if we forgot

to update a function there's just a lot

of issues that can go wrong so we want

to figure out okay how how can we create

this favorites contract with this

updated store functionality without just

copy pasting everything over and making

it less modular well speaking of modular

this is where Viper's module system

comes into play so modules are a new

paradigm as of 0.4.0 of Viper and a

module is a set of function definitions


and variable declarations which enables

code reuse now if you're familiar with

class system based languages Viper

actually prefers composition rather than

inheritance so if you're not if that

line doesn't make any sense to you

that's okay but basically a module

encapsulates everything needed for code

reuse from type and function

declarations to state but it doesn't do

inheritance and you'll see what I mean

in a little bit so if we wanted to have

this five morees contracts use the code

of favorites first we would have to

import it into our five more so we could

just say import favorites and you'll see

the import system with Viper is pretty

much exactly like the import system as

python you can almost think of that

import as nearly copy pasting this

contract in here not quite there's a

couple of key differences here so this

Imports favorites what it's doing is

essentially copy pasting this in here

except well here's here's kind of the

crazy part Boop except we don't

automatically have access to all this

code we can't automatically use it we're

just importing it in here it's it's not

part of our contract yet oh and then let


me do um pragma version

0.4.0 at license MIT like that first so

it's almost like copy pasting all this

code in here but kind of keeping it

commented out we can't quite use it yet

if I were to try to do def store well

let me actually let me copy paste this

store function let's copy this we will

paste it here let's even do a uh my

favorite number you into 256 right if I

were to try compile this right now MOX

compile compile great everything

compiled successfully and the reason

this compiled successfully is because

just because we imported this contract

doesn't mean we're actually going to be

using it so we have to say how we're

going to be using this for example in

our favorites Factory we import the I

favorites and we use it to type some of

our list of fa contracts right our

favorites Factory itself doesn't have

the functions of I favorites that was a

little confusing don't don't let it

boggy down for with Viper we basically

have to tell our five more contract how

to use this favorites module now if I

were to just comment this all out let me

do a little MOX compile again let me


clear this so we imported favorites we

compiled if I go to the out folder go to

out here we go to five more Json we can

see the Avi is blank so we imported

favorites and nothing really happened so

we have to tell Viper exactly what we

want to do with this favorites

contract let's say we want to start with

just using the state of favorites so

this is all these are all the state

variables right the storage variables so

if we want to use the state in Viper we

have to say initializes

we get a little red line saying it's not

initialized I'll explain this in a

minute initializes favorites now when we

write this we get a little squiggly line

saying not initialized if we go to the

documentation says this declares the

module's location in the contracts

storage layout it also creates a

requirement to invoke the module's init

function if it has one so since the

favorite has this init function we have

to add an init function to our five more

so in here I'll say def init and we

would say favorites doore init uncore

like this so if you initialize a

contract you have to call its

initializer function or also known as


its Constructor so before when we didn't

initialize it right our five more had a

blank ABI but now if I run MOX compile

again now we do have at least one thing

in the ABI right we have a Constructor

right we can see there's a Constructor

in the five more ABI that's all it has

though what's interesting is it doesn't

have any other functions in here so if

we go back to favorites oh that's a

little odd what these are all public

variables so are you telling me that I

can't call these variables in my python

uh that's exactly what I'm telling you

so let's go back to the deploy real

quick let's do a little create a

function called deploy five more create

this we'll do def

deploy five more we'll pull this in

comma five more we'll do five more.

deploy five more contract of type Viper

contract equals if I were to try to call

five more. retrieve for example right

our favorites contract has retrieve it

also has you know index which is a

public variable actually let's even

let's try to call let's try to call both

of them we'll call five more or print

five more. retrieve and we'll call Print


five more contract. index let's try to

call either one of them ready MOX run

deploy see what happens Viper contract

object has no attribute retrieve let's

okay let's comment out this line let's

try to call index because that's a

that's a variable right huh Viper

contract object has no attribute index

so this initialized is keyword and it

adding a knit down here this doesn't

give us access to any functions and

here's what's kind of cool whenever you

wrap the public keyword around one of

these variables you're very very

secretly behind the scenes adding an

external at view for example this uh

this favorite number right here def my

favorite number returns a un

256 return self. my favorite number this

function is essentially equivalent to

this so whenever you wrap a variable

with the public keyword you're secretly

making an external view function

somewhere in the code now the

initializes keyword doesn't give access

to any functions it only gives access to

storage so when we do initializes

storage or initializes favorites yeah

there is a my favorite variable being

activated but we just don't have the my


favorite variable public view function

we also don't have the retrieve function

we also don't have ad person we don't

have any of the functions at all so what

we can do though we can access these

variables by doing something like print

favorites. my favorite number so ready

watch this now so now when I run MOX run

deploy you know we get this print should

only be us de bugging we get this value

seven down here and then I can even do a

little print high from five more save it

clear the terminal clear run this again

high from five more seven this is

because we called the init function here

which activated all these storage

variables this initialize this keyword

here is basically equivalent to like

copy pasting this in here just without

the public keyword on all these and so

now we have access to all these

variables now we do have to reference

them though by doing favor rits Dot and

then the name of the variable right so

anytime we do this initialize this bit

we're basically copy pasting all the

storage variables from here into here

and we can access them by doing

favorites Dot and then the name of the


variable if our favorites contract

didn't have a Constructor it didn't have

one of these deploy it didn't have one

of these init functions we'll get a

little squiggly red line here we can

even comment this out and this is now a

valid python contract right I'll even do

MOX run deploy excuse me MOX compile

boom and this compiles successfully you

only have to call the NIT function of an

imported module if the imported module

has an init function so initializing a

module is basically like copy pasting

all the storage variables now there's

another way of using a contract state

with without directly initializing it

and this is with the uses keyword this

is a bit more advanced this is going to

be more for Library designers and if you

want to learn about this later I highly

recommend you pause a video and try to

do some uses stuff instead of doing

initializes now the next question is

okay how do we get the functions in here

we look at five more again oh let me let

me recompile MOX compile we now have the

Constructor back but there's no

functions in here here right if we tried

to call any functions on this none of

them would work so how do we get the


favorites functions in here well we can

get them in here by using exports so

what we can do is we can actually pick

which functions from favorites we want

to be callable so we could say exports

and do a little parentheses here

favoritz do

retrieve boom now if I compile this

ready let's do a little MOX compile now

in our five more ABI we now have the

retrieve function in here and back in

our deploy script I can now do print

five more. retrieve now I can do MOX run

deploy and the last thing should be

seven because the starting value is

seven so now retrieve works oh if I

wanted to add another value in here I

could do favorites do let's do store for

example favorites. store so now my

deploy function I could do let's do a

little five more contract. store 89 and

then clear let's run this again boom now

we have store and we have retrieve so

this is how we can manually pick which

functions that we actually want our our

five more contract to be actually be

able to use now often times this is kind

of a pain in the butt and we don't want

to have to do every single function so


what we can do instead is we can do

favorites. interface and this will

export every single function including

all these public variables inside of

favorites now let me clear this out if I

run MOX compile now head over to five

more. Json we scroll down here we now

see there's a ton of functions in here

we'll see all the functions from our

favorites. VI contract now what happens

though if we do a little add external

def store

new number of type unit

256 ass if we try to compile this now

we're going to get an error here we're

going to error like namespace Collision

member store already exists in self it's

because exporting favorites. interface

our favorites already has a store

function we can't also have a store

function here because in our deploy

script if we called five contracts five

more contract. store which one would be

be calling would be would we be calling

the favorites store or this store it

would be too ambiguous so we can only

have one so I want to have I'm going to

put just these two functions in retrieve

and add person and we're going to add

our own custom store so we're going to


say

favorites. my favorite favorite number

equals new number plus five oh and me

delete all this stuff down here oh and

so the the comments thing that I was

going to show you is like oh well now

that we're exporting favorites at ad

person that's kind of almost equivalent

to now uncommenting this out of our

contract so that's that's why pull that

all in here if that helps make it

clearer so now we have a custom store

function so now we're saying store

favorites. my favorite number equals new

number plus 5 so in here now when we

store 90 retrieve should give us 95 so

let's go ahead let's run this MOX run

deploy retrieve gives us 95 now this can

be kind of confusing for a lot of newer

developers cuz before we said hey when

we're calling other contracts we're

using static call and X call why are we

not doing static call or EXT call here

well technically this you know

favorites. my favorite number or you

know if we called favorites you know

favorite on my favorite number is

technically part of the five more it's

technically part of this contract that


we're in right now you can kind of think

of it like this way if we have our f.v

favorites. VI is inside of five more or

I guess I should say parts of

favorites.i is inside of five more

depending on what we export and

depending on a number of different

things this is the basics of modules

basics of interfaces

here now there's one more thing that we

haven't gone over that we will go over

later in the curriculum is initializing

a module with dependencies sometimes

you'll encounter a module which uses

other module and a module depends on

another module what you'll do is you'll

do something like this and I know this

syntax seems a little weird you'll use

this walrus operator where we'll say

initializes the name of the module and

then we'll say this module is

initialized this module's module is

initialized by this module now that's

kind of confusing but once you see it in

practice it'll start to make sense don't

worry too much about it quite yet but

with that this is actually everything

that I wanted to show you right now

before we wrap up got a little workshop

for you this was kind of a quick section


so you should spend maybe a little extra

time on your Workshop here I want you to

spend at least 25 minutes on all the

prompts without the aid of AI if you're

un if you're unable to solve them after

25 minutes stop take a break and then

work with an AI or other discussions to

help you solve them per usual here's

what I want you to do I want you to add

a second module to five more so we

imported favorites and we initialized

favorites I want you to add another one

so you'll have to create your own other

module and add it in here yes pretty

much any contract can also work as a

module I want you to then initialize it

so we saw we initialized the favorites

contract like this and then I want you

to call one of the functions from it for

example you could have something that

looks like this test it out in your

deploy script whether or not it worked

and see if it worked the way you

expected try to export functions from

two different modules so in here we're

only exporting from one try to export

from that second module then challenging

make a contract that successfully

compiles with the uses keyword so I


didn't teach you this we didn't go over

this but remember there is this uses

statement in Viper see if you can read

through the docs and understand how to

use and make a contract with the uses

statement now this is one where I will

say say you can go ahead you can work

with AI ask AI questions to solve this

one and then once you have that make

another contract that uses the contract

that you made over here so there's even

a little example in the uses here where

if we scroll down we see this walrus

syntax so initialize a contract using

this walrus syntax here so you need to

initialize a module that initializes a

module those are going to be the more

challenging ones as per always don't

spend more than 25 minutes on it then

feel free to go ahead and ask an

AI welcome back did you do the exercises

I hope you did if you didn't what are

you even doing here pause the video go

do the

exercises now if you have gotten to this

point you should be incredibly proud of

yourself let's do a quick recap of all

the things that we learned in this

section so we can move on to the next

one because the next one is a big one


this is where we're going to really

level up our smart contract development

so in this section we learned about

first off creating contracts from

another contract we learned about a

couple of keywords that Viper has built

in to create contracts one of the

keywords that we worked with was create

copy of this takes the address of some

other contract and literally copies it

by bite code for bite code we also

learned that there's another way to

create interfaces we can have a vyi file

where we just have the function

definitions and we don't have any of the

function body and this is what that'll

look like We additionally learned our

contracts can interact with other

contracts with the static call and the X

call we learned about static call once

before but now we finally learned about

this x call which is an external call

where we're going to call a contract

outside of our contract we learned that

we can initialize those State and

storage variables with this initializes

keyword and then if that module has an

AIT function we need to call that we

learned about the exports keyword where


we can export specific functions from

any modules that we imported or

initialized we learned that if we want

to just do all of them we can do exports

uncore interface uncore uncore like so

and then we also learned that we can

have a function with the same name as

one of the functions that we export

otherwise we'll get a collision you

can't have two functions of the same

name and then finally we learned a

little bit more about chaining commands

which at this point is something that

we've we've done a few times but we made

it more explicit in this section so with

that being said you have finished the

five more section of Cypher updraft

ultimate Viper course now is a great

time to take a break to get some coffee

to go on a walk to go to the gym because

the next section is probably in my mind

one of the most important sections that

you're going to do in your entire coding

curriculum we will be putting this on

your GitHub we will be putting this will

be the start of your cyphon profile

doing projects like this showing other

people how badass you are how much of a

badass coder you are is how you're going

to be able to get hired and if you don't


care about getting hired it's drilling

these skills in that are going to make

you very skillful repetition is the

mother of skill and we want you to be

skillful so be sure to take that break

before tackling this project and I'll

see you very

soon all right welcome to the next

section where we're going to be using

that buy me a coffee project and we're

going to making it incredibly

professional and we're going to be

showing you some really really advanced

stuff here and we go to the GitHub repos

ass with this course we can find all the

code for what we're going to be working

with here so let's do a little

walkthrough of what we're going to be

learning and what we're going to be

doing because because the smart contract

side of this is actually going to be

pretty similar we're going to do a

little bit of refactoring to do some

modules to do some imports here but the

code itself is going to re remain

relatively the same the biggest things

that we're going to improve on is our

deployment process and then additionally

our tests this is where we're going to


start writing really professional tests

we're going to be working with unit

tests staging tests and also integration

tests each of these have a little bit of

trade-offs each of these have different

and you want to run these in different

scenarios additionally we're finally

going to learn what this deployment. DB

thing is and in the maxino like what

what is this save to DB thing we're

going to learn about storage finally

I've kind of been glossing it over I

keep saying like State variables storage

variables we're going to finally learn

what this storage thing is and why it's

so important for working with gas in our

scripts we're going to be learning one

of moxon's most powerful feature called

manifest named or manifest named

contract why we want to use it and why

it makes our testing so much easier and

then finally the biggest thing about

this section is at the end of this you

are going to push your code up to GitHub

and this is going to be the start of

your portfolio in order to get a job in

order to get hired you have to have ex

you have to have proof that you've built

these things you have to have proof that

you know what you're talking about so


we're going to be pushing all these

projects up to GitHub so that you can

start building your portfolio of

projects to show that well you're a

badass and you know what the heck you're

talking about that is the goal of this

section is to by the end of this you

will have this GitHub repository on your

GitHub repo and you will be signed up

for cyphon profiles with this cyphon

login because this additionally is will

be helpful for getting you jobs keeping

track of your history and so much more

so let's take a look at what these tests

look like now when I run my test here I

run MOX test and we see we get a ton of

tests run at least 10 tests we're also

going to learn about MOX test-- coverage

which looks like this and will show us

how much of our smart contracts we've

actually tested also learn about writing

we'll also learn about running Fork

tests like mock test-- network sapoia

but we won't deploy smart contracts to

sapoia we won't run any actual

transaction s I'll pass in-- Fork where

we can actually test our smart contracts

on a fork of a real Network very similar

to what we did with our tenderly virtual


networks we can also go ahead deploy

test and do a ton of work directly on

the test Nets if we want to do some type

of what's called a staging test so we're

going to be doing a lot of more advanced

tests in here so that our codebase is

way way more secure now on Cipher upd we

have a lot of advanced courses some of

the biggest ones being smart contract

security assembly and formal

verification and you know a lot of the

defi curriculum as well such as the

curve stable swap course which is in

Viper and will teach you a lot of

features of how curves swapping

functionality Works which again if

you're unfamiliar with curve unfamiliar

with swapping go take the course after

you finish this it's all in Viper it's

phenomenal and the reason again I'm

touching so hard on this testing is

because we're going to teach you how to

write very defensible code in the smart

contract world one mistake can mean the

end of millions of dollars landscape is

the most adversarial landscape on planet

Earth and you need to be able to write

very powerful very defensible code to

defend against it so we're going to be

learning all of these cool phenomenal


features you're going to become a more

badass python developer and a more

badass Viper developer by finishing this

section and then finally you're going to

push all this up to your own GitHub so

that you can start building your

portfolio so with that being said let's

jump in and let's get started

all right we're back in our MOX CU

folder here do a little LS we see we're

building up a nice little nice little

folder here filled with demo projects

that we're using to level up our career

let's go ahead let's make the newest the

next folder we'll do

mkd buy me a coffee ceron updraft enter

CD MOX tab buy me a coffee or by tab

andit enter and then code period or file

open this folder let's go ahead let's

pop this open in here like so you

already know we have MOX d-el we have

MOX installed so we can do MOX init

period-- vs code-- py project now we

haven't been using this py project

feature at all but that'll change very

soon okay so we have our project here

and we're going to go ahead we're going

to delete these files right click delete

so that we can start from a blank


project here so let's go ahead let's

grab that buy me a coffee from remix

that we did way way way back in the

Viper fundamentals section so I'm going

to scroll way up and here it is okay

remix buy me a coffee let's open this up

let's grab the buy me a coffee. VI and

this is what we're going to start from

so we'll grab grab this bring it over

here right click new file buy me a

coffee. VI enter I'm going to delete

these comments on the bottom here and

great we have our repo in here now just

a quick reminder of what this project

does this is a very simple minimal smart

contract to allow people to send us

money to buy us a coffee and then we

keep track of who has sent us money so

we have a a little fund function this is

our internal fund function and allows

people to send us money we have set a $5

minimum that we're getting the price

from the chain link price feeds once

they call fund we append it to our

funders array and our funders mapping as

well we have a withdraw function that we

can use to withdraw our money out we

have access controls so that only we can

pull the money out we have a price

converting feature we have a little


extern function to view the price and we

have our default or our fallback

function where if somebody just sends US

money we will automatically call the

fund function for them and just to make

sure this works let's go ahead do a

little MOX compile great looks like it

compiles

successfully now we've learned a couple

of things since we originally wrote this

code we first learned about interfaces

and how they can actually be in their

own file so to make this code a little

bit nicer we're going to go ahead create

a new folder called

interfaces and we're going to create an

interface called

agregator B3 interface interface. vyi

again vyi stands for an interface now

the reason I'm using camel case here

instead of this snake case right I'm

having these capital letters and no

underscores is because this is the name

of the interface in its solidity Edition

and I'm looking to kind of keep the same

name of the interface to match what

chain link Labs wrote for the solidity

edition of this but if this is confusing

you can obviously do that I underscore


or the I methodology that we did

previously what we can't do is we can't

just copy paste this in here we have to

actually convert it to its interface

Edition but oh man that's quite annoying

uh I that's quite a lot of work and I'm

incredibly lazy so let's see what our

friend Claude has to say or let's see

what our friend chat T has to say let's

give this a little prompt I'll say here

is my

inline Viper interface and the reason

that I'm going to tell you that this is

okay to do is because you actually

already know how to convert this from

its Edition here to its file Edition

right you you know how to do that

transition you could 100% do it manually

yourself if you wanted to but it's just

kind of busy work right we're not it's

not super important so it would be great

if AI could just do it so we're going to

say hey here's my inline Viper interface

do the three back ticks paste it in here

end it with three back ticks can you

convert it to a Viper file

interface here is an example and then

maybe we'll even pass an example of

we'll pass an example of one of our past

ones uh we you could also just copy


paste this from the GitHub repo but

let's pretend we don't already have the

GitHub repo so in our five more project

if we go to interfaces in here if

favorites. VI let's just grab this go

back to chbt O that's Claude let's go

back to chat jbt paste it in here and

I'm actually going to copy this whole

thing and also ask Claude so we're going

to ask both of them and see which one is

better here I'm going to hit enter clae

I'm going to hit enter on chbt so let's

see what it gives us I'll help you

convert the inline Viper interface to a

proper Viper file interface form using

external and view decorators here's your

interface converted to the Viper file

format H wrong version but that's okay

okay it's using pass instead of the

three

dots okay clearly it's a little bit less

up to date oh chat gbt though is a

little confused it's come up with a new

fake decorator called constant and it

did this at the top for some reason um

okay well uh I guess this one's closer

let's let's use this one

okay so maybe uh AI didn't do such a

great job here but that's okay we're


going to copy this we're going to grab

this um and we're just going to do a

find and replace so I did I I got this

finally replaced by doing command F or

control F depending on if you're Mac or

Windows or Linux and I'm going to say

pass and we're just going to replace

everything with three dots hit enter

save it and that looks pretty good to me

decimals description version latest

answer decimal description latest

version

answer or version latest answer okay

that looks pretty good to me okay great

so let's go ahead delete this now and

now we can do from

interfaces import I'll hit tab here AI

got this one right aggregator V3

interface and let's just make sure this

works we'll do a little MOX compile nice

okay so that worked thanks AI now let's

actually get a little bit more practice

with working with these modules let's

take out let's look at this eth to USD

rate let's take this out as an internal

function and let's turn this into a

module so let's get some practice

working with this so I'm actually going

to delete this from the buy me a coffee

going to go back to the SRC new file


we're going to

do get price

module. buy and we're going to paste

this in here what are the variables we

need we need a price feed in here so

let's actually just pass it in as a

variable the price feed is of type

aggregator V3 interface so we need that

so we'll do from

interfaces import aggregator V3

interface like this we'll pass this in

as a variable we'll say price feed of

type aggregator V 3 interface and then

we'll do static call Price fee. latest

answer buy me a coffee we also have this

Precision variable let me look for this

any other place it looks like this is

the only line it looks like it was only

used in that function so we're going to

take that out we're going to paste that

in here as well and this is looking

pretty good now what we can do back in

here is we can import this now we can

say from or excuse me we can just say

import get price module right because

these are in the same folder right so

we're just going to say go ahead just

import get price module and then down

here we're going to have this error


because we're saying self. get eth but

instead we want to do get price module.

get eth to USD rate now we know that

this function also takes two parameters

now so we're also going to want to pass

in the price feed like this and oh we're

going to want to do the same thing up

here price feed pass that in and now

we're looking pretty good here so let's

do a little mock

compile and it compiles successfully

awesome now you might be asking uh

Patrick you're a lunatic we have this

Precision variable this is a state

variable of buy me a coffee you taught

me in our last section whenever you have

these State variables if you want to do

this importing stuff you need to

initialize you big dummy you're so silly

you need to do initi

lizes get price module however because

get price module doesn't have a deploy

or an init function or a Constructor we

don't have to actually call it but you

do have to do this Patrick well I'm here

to tell you you're wrong we don't have

to do that and this is our first piece

of learning for this section we're going

to finally learn the difference between

constants and immutables and storage and


then additionally way way back when we

were in remix I told told you hey

constants and immutables are much more

gas efficient but it didn't explain why

so now it's time to explain why and

we're going to explain why by talking

about storage and then additionally this

will also explain why we don't need this

initializes piece here I'm going to tell

you right now that the reason that

immutables and constants are so much

cheaper is because reading and writing

to storage is incredibly gas intensive

whereas reading from constants and

immutables is much cheaper gas wise so

let's let me let me let's let's walk

through this storage layout and what

goes in storage and what's not in

storage for you to understand more so

let's start by taking a very a quick

look at this very minimal contract on

the right here it has one state variable

or one storage variable it's of Type U

256 now what Viper does on the back end

what the evm does on the back end is it

needs to store this variable someplace

right when we save favorite number to 25

our contract has to save it someplace

now all of our contracts have this giant


List have this giant list or this giant

array or basically this giant separate

location called storage where it can

store stuff and these are things that

need to persist these are values that

need to persist between transactions

between calls Etc it's how we can

actually update this these values and

come back to it later call retrieve and

get the same value right we need

someplace where these values can persist

and this place is storage so every

single contract in the evm and arvm

ecosystem have this storage place when

we do self. favor number equals

25 what the evm worlds and what our

contract world does is says okay from

here on out favorite number this

favorite number variable is always going

to be referring to storage slot zero so

anytime that you refer to favorite

number the contract goes ah they're

referring to that value that's in

storage slot zero and when we say okay

let's do self. favor number equals 25 it

says great let's take this 25 number

let's convert it to its hex equivalent

and we'll stick that into storage slot 0

so you see

0x0 19 which is the bytes equivalent of


the number 25 so that's what's in

storage slot zero let's say we have

another variable then like a Boolean so

Su Boolean and we set self that sum

Boolean equals true well our contract

actually assigns storage slots for the

most part in order so it says okay favor

number that was the first variable I saw

in the contract I'm going to set that to

storage slot zero some Boolean that was

the second one I'm going to assign that

to our first storage slot and a true

Boolean would be 0x00 that's the hex

equivalent of true the false equivalent

would be just straight up zero according

to the evm or these contracts or Viper

anything other than zero is considered

true and when it's zero it's considered

false so when we set self. bu equals

true on the back end Viper and the evm

world go ah they're referring to some

they must be referring to storage slot

one I'm going to change it to 0 one I'm

going to change it to have the hex value

of one because that is the Boolean

equivalent of true so now we have two

storage slots so now we're understanding

how our variables are stored so okay

cool making sense so far next we have


fixed arrays now fix arrays basically

just take up all the storage Slots of

their size so for example if a fixed

array is 1,000 slots long from since

it's the third in the list it'll be at

the third index which is index 2 here

right it'll start there it'll go from

and every single slot from 3 to 1,1

it'll just Auto default populated to

zero that's why whenever we create a

fixed array it starts with defaulted a

ton of zeros in it and every single

element inside this array for example at

slot zero if we set slot Zer to one

it'll update that to one if we were to

set slot 1000 to one then the storage

slot 10001 would be one because it's the

last one in the array a fixed sized

array is just going to take up all the

slots associated with its length now a

dynamic array is where it starts to get

a little bit more interesting a dynamic

array has a holder spot at its storage

slot so it'll its storage slot here

would be 102 because all these slots are

already taken up right favorite number

is the zero slot symbol is the first

slot our fixed array takes up 1,000

slots so my Dynamic array starts at slot

102 but this slot here actually just


holds the length of the dynamic array so

it has a maximum number of 100 slots so

the next 100 slots are also taken up by

my by our Dynamic array however that

initial slot instead of being an element

of the array it's actually the length of

the array so if we do self.y D array.

append 333 this initial storage slot

will be its length which will be one you

can see that 0x 0 one here and then the

first slot after the length will be the

first element and then it's sequential

from then on out for mappings we start

to get even more complex so favorite

numbers is going to take up one slot at

slot zero some bull is going to take up

one slot at slot one my fixed array is

going to take up a th000 slots starting

at slot two my Dynamic array is going to

take up 101 slots it's going to take up

100 slots for the element and then one

additional slot to keep track of the

length of the array now my map is where

it gets even crazier at its storage slot

after all of the slots have been taken

up it's always just going to be a blank

placeholder this tells Viper that hey

there is a a mapping here but we don't

keep track of the length we don't keep


track of anything like that the elements

inside the map unlike the dynamic array

and unlike the fixed array don't follow

sequentially they use some hashing

function to come up with the location

and I'll show you what I mean when we

move over to the scripts of working with

this contract so you can almost think of

the mapping locations the elements in

the mapping or the hashmap kind of

located essentially all over the place

in crazy crazy bizarre spots in storage

all right now here's where we get into

the good stuff constants and immutables

are not stored anywhere in this storage

section they're stored directly as part

of the contracts bite code so they don't

take a storage slot and this is also why

you cannot update them because contracts

are what contracts are immutable meaning

they cannot be changed so if a variable

is considered part of the contract's

actual bite code which storage and

immutables are they cannot be changed

and they do not go into storage and

that's also why they're so much easier

to read because it's essentially the

contracts code reading itself which is

much cheaper much more gas efficient

than the contract going into this


separate storage location and then

separately I know this is kind of teeny

tiny but memory variables are not stored

anywhere in storage so this I know it's

super tiny let me let me zoom in a

little bit so this new variable and this

other variable neither one of these will

get stored in storage if we call the

function do stuff these variables will

exist for the duration of the

transaction and then get deleted if

since they don't have that self dot that

means they're not storage variables

whereas these ones with self dot are

going to be storage variables now in

this function do stuff when we say Newar

equals self. favorite number we have to

read from Storage to read from Storage

you use something called an SL load op

code and anytime you read from Storage

anytime there's an SL loadad you should

know ah this is going to be more gas

intensive than if I just read from bite

code so same thing here self. some we're

reading from Storage saving it to these

two memory variables which again these

two memory variables go nowhere in

storage so now that we know all this now

it's starting to make sense why we did


all these differences here and in fact

once again we showed you this a little

bit before and in fact when we go run

our tests we'll show you gas profiling

and we'll show how much cheaper it is

how much quicker it is how much cheaper

it is to leave these as constants and

immutables then have them as storage

variables but additionally so we

imported our get price module but if we

look and get price module our price

module has a constant variable so

because our price module has a constant

variable this means this is not in

storage which means that looking at this

price module there's no storage here at

all so we could if we wanted do go

initializes initializes get price module

but this line would essentially do

nothing because get price module has

nothing in storage now if you go to the

GitHub repo associated with this course

in here if you go to SRC example

contracts you can see this fun with

storage in here and there's also a

script called storage. piy where this

will go ahead and it'll print out a

whole bunch of variables at different

storage slots you can read directly from

storage using titanoboa so I have this


loaded up on another window over here

and I'm just going to go ahead and show

you what running this script will look

like so I have our storage. let me show

you if do if we do MOX run storage it's

going to run our storage script and

we're going to see all the outputs so

first off we deployed our fun with

storage we didn't verify because we're

not on an actual network but we do fun

with storage. unor storage. favor it.get

so what's kind of cool is in fun with

storage favorite number is a private

variable but guess what private

variables can still be read everything

on a blockchain is public information so

we can literally just look at the

contract look through its storage and

Viper has some nice little helpers that

let us very easily read from it and we

can go great favorite numbers value is

25 because we can read directly from

private variables we can also read from

immutables so this immutable where is it

not in storage is also a private

variable but in titanoboa we can get

that contract doore immutables and read

the immutable value not only that but we

can read directly from Storage slots so


boa doget storage paste the address of

the contract you want to read storage

and then paste the storage slot so the

value at storage slot zero for our fund

with storage contract is going to be

what it's going to be 25 right cuz

favorite number is storage slot 0 and we

assigned 25 in there so we have favorite

number. getet storage and get storage. 0

are going to return the same thing

because favorite number is storage slot

zero we can also get the first element

of the fixed array that's going to be in

storage slot two right because this is

storage slot zero some bu is going to be

storage slot one my fixed array the

first element in here was going to be at

storage Slot 2 0 1 2 so down here my

fixed array will be my fixed array at

index zero AKA storage Slot 2 is going

to be 222 so if we look in here we do in

Steed see we get

222 we can then see the length of the

dynamic array right because our dynamic

because the fixed array is going to take

up a th000 slots so this is going to

start at slot 1,2 so we can do boa em.

getet storage fun with storage. address

of 102 we get the length which is just

one and that the reason is just one is


because we only have one append in here

we can also get the first element of the

dynamic array which is just one after

which is 333 we can get the mapping

placeholder which will always be zero oh

I have I wrote length of the mapping

this should be mapping placeholder

mapping placeholder I'll fix that 103

and then we can get the first element of

the mapping now this is one of the

equations to get the mapping of the

element you can see it's kind of a lot

basically you take the slot of the

mapping placeholder and then the key of

the item for example my map at with key

zero equals true we could do kind of

this crazy equation here and then we can

just do once again bo. E.G get storage

FWS uh address location and we see we

get the one because the one represents a

true Boolean and if we want we can even

print this out we could say like

print uh print F location is going to be

location and you'll see it's this crazy

crazy storage slot so this is the

storage slot and this is why it's

unlikely for there to be a collision

here it's unlikely for this storage slot

to also be the storage slot of some


other value but this is how we get the

storage slots here now one more piece

here you can also in Moccasin view the

storage of your contracts view the

storage layout so I have this fun with

storage in here um you can also do this

with your buy me a coffee but I can do

MOX

inspect fun with storage and say storage

so I'll do MOX inspect d-el first so

there's a ton of different things that

we can inspect ton of different methods

for us to inspect so I can do MOX

inspect inspect fun with Storage storage

layout

and we'll get the storage layout of the

fund withth storage we can see there's

even a code layout which talks about

some of the variables that are not in

storage and then the actual storage

layout and says okay favorite number is

at slot zero takes up one slot my

Dynamic array is at slot starts at slot

1,2 and it takes up 101 slots my fix

array starts at slot two takes up a

th000 slots my mapping takes up one slot

it's at slot 1 three it does not

increment the more mappings you add it's

always going to take up that one slot

and then some bu again that's just one


slap so I know I just dumped a lot of

information on you here it's okay if it

didn't sync in the first time we will be

very aware of storage and immutables and

constants as we progress through our

process and if you ever need a refresher

feel free to come back to this section

CU yes this is complex stuff and it's

okay if you don't understand it the

first time but if you want to go ahead

and you can go ahead and grab this fun

with storage contract you can grab this

storage. py script and start playing

with the values to see if you can get

something

different all right well uh back to our

regularly scheduled programming here we

now have a decent understanding of

storage we also understand why we don't

need to initialize the get price module

because all we want from this is what it

has this function in here

and that's all we really want we also

get this Precision variable but we get

it by default because this is a constant

variable and it's going to be embedded

directly into the bite code of this

contract and we don't have to initialize

storage at all so with that that's


pretty much all the refactoring that

we're going to do now I'm going to show

you later how we can do a little bit of

gas profiling to see how much more

expensive this would be if these were

storage variables instead of constants

and immutables but for the most part

this is looking pretty good

so with that we're pretty much done with

writing our smart contract code let's

now finally give this some scaffolding

we got to write some scripts so we can

deploy this we need to write some tests

so that we can make sure this is

actually doing what we want it to do

let's get started writing our script

first so that we can also test our

deploy script all right so now we're

going to get into actually testing and

actually deploying this and we're going

to learn a lot of features to really

really test this now when we did this in

remix how did we test it well we

deployed it and we pressed a but a

couple buttons and then we switched from

the remix virtual Network to the

tenderly virtual Network and we didn't

actually deploy it because that was kind

of scary we didn't actually want to

spend gas test that gas was hard to get


and there were a whole bunch of haziness

on how good our code was so we're going

to write a deploy script that deploys

our code base and we're going to test it

very very thoroughly so let's go ahead

and let's get started let's create a new

file just called deploy dop in here

where we are going to deploy our

contract so we're getting used to this

now we'll do a little def moccasin main

we'll pass here or actually uh we'll

call the deploy

deoy coffee coffee like this we'll do a

little deaf deploy coffee and we'll do a

little pass here let me pull up my

terminal just to make sure this is

working let's do a little MOX run what

do we call this deploy oh uh print high

from deploy clear run this again high

from deploy okay great so we have our

little high from deploy here I'm going

to clear this out again and what do we

need to deploy our contract so buy me a

coffee what is this taking in let's

scroll around in here um it needs a okay

it needs a price feed H okay so here's

where we're going to run into our first

question how do we get our price feed

what do we do to get our price feed now


you don't have to follow along with me

for just a second I'm just going to show

you what we could do so moxin has this

thing called get Active network that

comes with us and if we go to the uh and

we can pull in details about our Active

network so we could say from moccasin

doc config import get Active network

like this and our main we could do

something like uh Active network equals

get Active network then we could say if

active network. name equals equals we'

say spolia you know price feed equals

and then we would pull up you know the

go to the docs. chain. link right here

resources data feeds go to Ducks let's

go to Price feeds oh where is this price

feeds where find contract addresses

scroll down ethereum sepolia we're

looking for the ethusd feed okay that's

this one right here let me copy that

let's come back okay if it's aoia do

this one if activ network. name equals

equals uh let's say main net then we

would do price feed equals something

else and then we could just you know let

me let me I'll just comment this out

we'll say price feed equals blank then

we could pass price feed to our deploy

coffee function we'll say price feed


will be a string we could also then say

okay from SRC Dot from SRC ort buy me a

coffee then we could do buy me coffee.

deploy price feed like this right this

would work but I'm going to tell you uh

this kind of sucks right just have a ton

a ton of conditionals in here G this is

not ideal well but additionally this

wouldn't work on our PM because this

contract address doesn't even exist on

the p evm network so we have two

problems here how do we make this script

simple to pick the correct address based

on the chain and then number two how do

we test this on a pvm network also if I

were to run Anvil right if I were if I

were to try to test this on Anvil this

wouldn't exist here either there that's

super annoying so how do we solve these

issues now pretty soon we're going to

learn how to solve kind of both of these

using forked tests but those have

trade-offs as well so let's tackle this

one first how do we test this on a PM

Network now to test these we're going to

use something called mocks or mock

contracts essentially the solution is

that we are going to deploy these

contracts ourselves
we're going to deploy our own fake dummy

versions of these contracts to our own

Pi evm Network so let's go ahead let's

get started working on that so I'm going

to go ahead now you can start follow

along following along with me again I'm

going to go ahead I'm going to delete

all this here we're going to keep this

get Active network we're going to keep

some of the stuff and I want to get rid

of this I want to get rid of these

little underscores so I'm also going to

run UV add

moccasin I'm going to say yes so those

Qui these go away all right great

looking better so let's go ahead let's

make a script let's make a a script to

just deploy a fake price feed just

deploy our own price feed now in order

to deploy our own fake price feeds our

own price feed contracts we obviously

need the code for the price feed

contract itself so we could go to you

know the chain link GitHub and go

through the contracts go through the

where is it SRC V8 what is this looking

for an aggregator V3 contract where is

it price feeds we could look for this

price feed contract in here and we would

know it's in solidity so we' have to


convert it from solidity to Viper and I

would probably use like an AI to help me

out I would just drop literally copy

paste the SL in here and say like hey

can you turn this into Viper and it

would get some of it wrong but then I

would fix it but I'm going to tell you

for this this will be one of the few

times where I will say just go ahead to

the get up repo so it with this section

go over to SRC and go to Mock and grab

this mock V3 aggregator dopy so let's go

ahead let's copy everything in here

let's go back to our code base here so

in SRC new folder we'll do mocks new

file mock V3 agre

gator. by and then just paste this in

here so this is our very minimal chain

link price feed that I've Rewritten in

Viper for you and you can feel free to

use this in your tests here this is

purely a mock just for mocking not for

actually using not for actually

deploying price feeds and all it really

does is it mimics all the functionality

of a chaing price feed so if we look in

here we have some of our most important

functions like latest round data update

answer we have latest answer at the top


and this is how we're going to be

getting price feed information and if we

wanted to we could also add a function

in here for us to update an answer that

way if we wanted to test if what would

happen if the pricing went crazy we

would be able to do that in our mock

here so we have this minimal mock

contract and this is going to be how

we're going to test this locally we're

first going to deploy our own local mock

here so I'm actually going to create a

new script called deploy Mox dopy and

all this is going to do is deploy that

price feed so we'll do a little defa

moccas main uh deploy

deploy feed this so we'll say def deploy

feed do pass for now we'll do from SRC

MOX import what did we call it import

mock V3 agregator like this and what

does our mock mock V3 aggregator Pi need

for input parameters needs decimals and

initial answer like this so right at the

top here we'll say starting decimals

equals 8 the reason I'm starting with

eight is because I know that for eusd if

I look up eth eth

ethusd show more details I know that

these have eight decimal places right we

did this as well in our buy me a coffee


right if we look up the buy me a coffee

let me zoom out here scroll to the

bottom oh did we actually this is in the

new excuse me this is in the new get

price module we know that it starts with

eight decimal places and we have to add

10 more with our Precision stuff here so

we know that ethusd starts with eight

decimal places so we'll start it with

the same amount and we'll give it a

starting price a starting price of let's

say $2,000 and we want to set this to2

,000 but we know that it has eight

decimal places so we could do 1 2 3 4 5

6 7 8 but that's disgusting so what we

can do to make this a little bit more

readable is I can say

2008 and then cast this as an INT that's

essentially the same thing and then in

here let's have this deploy feed

actually return a Viper contract

contract so we'll say

from moccasin

dooa tools import by paper contract like

this and we'll say mock V3 aggregator do

deploy with these starting decimals and

I'm going to copy paste this here do a

little comma and the starting price I

believe that is the correct order right


starting decimals starting price yes

okay good and we're going to return this

return cool so now I have a function to

actually deploy the price feed what I

can do now is I can import this into my

deploy here I'll say from

script. deploy MOX import deploy feed

and to get the feed I'll say price feed

this will be of type Viper contract

equals deploy feed and Viper contract

same thing here I'll do from moon. booat

tools import Viper contract so now I

have the price feed now I can finally

do buy me a coffee. deploy with the

price feed or Price feed. address I can

say coffee coffee

equals this and then I can do like a

little print Line Print coffee deployed

at and I know I've been doing F

statements but you can also do a little

comma here that's kind of the same thing

but we could say

coffee. address cool um deploy coffee oh

I guess I kind of ignored it here well

let's let's just put it all on moccasin

main for now because we're going to

refactor this all pretty soon so to try

to run this we can do MOX run deploy

this will run on pvm and we see coffee

deployed at here great so we have a way


to deploy to our local network all we

had to do was pass it a fake price feed

in great well technically we could have

really passed in any address and it

would have worked so if I even just just

grabbed if I even just grabbed this

address here I can paste that in here

too right let's run this again and it

still worked well that's because we

actually didn't test anything right if

we deployed with this fake address here

and if we tried to do coffee dot what's

something that our coffee contract needs

the price feed for let's do look at buy

me a coffee if we tried to call get e to

USD rate right get e to the USD rate of

what

1,000 right this should break

because right this should break because

this calls the price module and if we

look at the price module this static

calls to whatever address. latest answer

and uh our account here probably doesn't

have a latest answer function so let's

go ahead let's try this hit enter and

sure enough we get an error saying hey

uh what the heck is going on we got this

revert B which means we got a blank

bytes response and mck's freaking out


cuz it's like what are you you're you're

lunatic you're crazy however if we go

back to the price feed address we can

check to see at least kind of a sanity

check if this worked the price feed.

address save it run it we see ah okay we

didn't get a revert this time but we

probably want to print this out at least

let's do a little print clear run and we

actually get a value here and we can

even go one step further to make sure or

it's calling from The Mach V3 aggregator

because in here we can even do a little

print line hello from mock aggregator to

make sure it's actually getting deployed

do it one more time oops uh mock for

deploy hello from mock aggregator okay

great so we know this is definitely

being deployed Okay cool so we've solved

it yay we know how to do it on the PM

Network now this mocking methodology is

actually relatively common when it comes

to testing this can take a little bit

extra upfront work because you might

have to like what you saw you might have

to rewrite a contract to make it easier

for you to work with you have to make

some minimal example of a chain link

price feed so we already had one which

made it pretty easy for us to work with


this but sometimes it's not going to be

this easy AIS are really really helpful

at making mocks because usually you can

literally copy paste some cod in say hey

here's my code can you make this a mock

for me and it'll be able to give you a

mock and it's pretty good at converting

from solidity to Viper usually it will

have some mistakes that it makes and you

just got to go in and tweak those

mistakes and that's why you're learning

so much here so that you can go back and

correct it when AI gets it

wrong but so this is helpful um we're

able to deploy on to the PM but this is

not very helpful when we actually want

to deploy to a real Network I don't want

to deploy a fake price feed when I'm

actually going on a real Network so okay

um do we go back to these weird

conditionals like if this then that well

here's where a built-in moxin feature is

going to have our backs here so if we go

to the moccasin GitHub let's go to the

documentation we scroll down in here

there in Moccasin there's this concept

of named contracts now named contracts

are they're very unique to the moccasin

framework but essentially it allows us


to do what we're trying to do here it

allows us to say when we're on a local

network spin up a mock when we're on a

real Network and a contract exists use

that one and it's able to differentiate

between the two so let's look at a

minimal example from the documentation

we're introducing this new section of

the docs called contracts so every

single Network can have a list of

contracts with a list of parameters

inside of it and actually just a real

quick note on working with toml if we

scroll down to the uh to the overview

toml is pretty cool where this is valid

toml and this is actually the same toml

but like with Jason so like so like

projects. networks can be kind of

thought about as a dictionary or

adjacent object inside of projects which

can also kind of be thought of looking

like this so if you're familiar with

Jason and Tomo's a little bit new weird

for you definitely be sure to read the

documentation to understand these are

kind of all the same and so when we're

looking at networks. mainnet fork.

contracts this is kind of equivalent to

looking at you know networks. main fork.

contracts. usdc with a single address


parameter in here but anyways I'd

digress so we have this new named

contract called usdc so whenever you

have a an entry in your contracts

section of your MOX Ando this is what's

called a named contract so the named

contract in this case is named U DC now

what you can do when you have such a

contract is you can do get named

contract or manifest named there's a

couple different aliases for this

function and with just this example here

you will return the address of that

contract on whatever Network so for

example this is main net Fork if you had

like three different USC's on different

networks you would return the address of

that contract so for example if you ran

you know this script here you would get

back the address and here's another

example of what I call like true tommel

versus like the ugly tml that we had

before these two are are exactly the

same right so this is networks domain.

fork. contracts. usdc versus the ugly

tml which is just networks domain fork.

contracts with usdc equals and then kind

of this Squigly bracket stuff here you

can additionally add a whole bunch of


flags inside of your contract let's look

at the uh the true tummel one of the

important ones being this deployment

script so first off you can define an

address for the contract but you can ALS

also Define a deployment script for the

contract and this is where the power

comes in if you've defined an address

and a deployment script if you defined a

deployment script what moccasin will do

is first it'll say okay is there an

address for this network if know I'm

going to run the deployment script and

you can kind of read a little bit more

about some of the other parameters in

here but this allows us to have a very

minimal deployment function or a very

minimal codebase and moccasin will kind

of almost magically just pick the right

thing you want to do do you want to

deploy a mock or do you want to get the

actual address here so let's let's

actually see this in practice so first

off let's go to our MOX and.mo let's get

rid of let's get rid of pretty much

everything let's just start from scratch

okay with a brand new setup here so

we're going to be deploying this to a

few places one of them being sepolia so

let's go ahead let's get let's first get


this set up for seoa so we should have a

networks. sapoia in here let's zoom in a

little bit networks. sapoia URL we've

done this before it'll be the sapoia RPC

URL since this is going to be an

environment variable I actually am going

to go ahead I'm going to create a EnV

let's go back to our friends at Alchemy

where is our little alchemy instance did

I get rid of my Alchemy instance I think

I did let's go back to Alchemy let's go

back to our Alchemy dashboard in here

okay I have my sapoia endpoint I'm going

to copy that and we're going to say

spolia RPC URL equals paste this in here

it's not my private key I would never

put my private key in here we have our

sepolia RPC URL we'll save save to DB to

be false still again we're going to

learn about that in a little bit we'll

say default account name equals default

this will be this encrypted private key

that we did in our last couple sections

we'll say Explorer URI equals

and I'm actually going to cheat I'm

going to copy paste this from our last

you can go ahead and do the same if

you'd like this is a block Scout explore

so we have the basics of our sapoia


section set up now what we could do is

we could then say contracts and put a

little equal sign little brackets

here price

feed a little equal sign put some

brackets here but this is kind of ugly

tomel so instead we're going to

do NW works. sapoia doc

contracts price feed like this and we'll

give an address so let's look at the

apoia eth usdc do. CH eth ethusd address

let's go to resources let's go to docks

here let's go to Price feeds let's

scroll down find contract prices let's

scroll down so ethereum let's look up

sepolia where's eth US eth USD let's

grab this address here come back over

boom okay now we have the address for

sapoia what else well next we can define

a deployer script deployer script and

this is going to be our script that we

just created so this is going to be uh

where is this it's going to be deploy

Mox

dopy and we do have to edit our deployer

script a little bit to in order for us

to run this manifest name contract or

get or deploy named contract there's a

couple other or just manifest named

that's what we're going to be doing


there's a couple names for it and if you

want to read more about the issue that

this solves you can go ahead and pause

and read the documentation here our

deploy mocks our mockas and Main must

also return a Viper contract so we're

going to do we're going to grab this

little type hint paste it here and we're

going to have our deploy feed return

deploy feed so now in our

M.L we can say deployer script is now

deploy Mox dopy and Moccasin will be

smart enough it'll say okay if you're on

seoa I'm going to use this address if

you're not on sapoia I'm going to run

this deploy mock script and whatever

your moccasin main returns and again

this is why moccasin main is kind of a

really cool function I'm going to use

whatever this moccasin main returns as

that contract so let's do a little let's

add this print hello back in here so

that way whenever we deploy this Mach V3

A.P we'll see this print hello in here

and in our deploy dopy let's now update

this to use that manifest named function

so let's just remove everything in here

and let's go ahead and let's now do

price feed
equals manifest named and what do we

call this in our in our MOX tomel we

called it price feed so manifest named

price feed now just with this line this

is always going to return a Viper

contract and if we're on sapoia it'll

return the actual address so let's do a

little print little print F here on

network activ network. name activ

network. name using price feed at price.

address and if we're on sapoia this will

say sapoia using this should be this

address and when we go to pvm it'll say

on active on network pvm using price

feed some random price feed and we'll

also see the hello from our deploy

script here so let's go ahead let's

clear let's see how this works MOX run

deploy key eror price feed key error

price feed hm ah I know why we got this

so This price feed contract

doesn't exist on Pym right so

networks. pm. contracts right now is

blank H we forgot to add the price feed

in there but Patrick you just said it's

smart enough to know blah blah blah

networks. pm. contracts. price feed has

no deployer

script moin went networks. pm.

contracts. price feed it saw a blank


deployer script and said hey um yeah

that price shet thing it doesn't exist

so you'd have to add this now we could

run this and it'll work oops and this

should actually be script slash sorry

about that script SL deploy moep high so

now if we run this oh it looks like it

worked so we got this print hello we got

this big warning hello on network PM

using price feed at and this is

different than the price feed oh okay so

what if we do now --

Network sepolia I'm going to enter

going to say hey are you sure you want

to do this I'm going to go ahead and hit

yes you can skip this if you want you

don't have to actually do this I know

this is okay because I know this isn't

going to actually send a transaction

enter enter your password for the

default key store I'm going to enter my

password in here

oh interesting okay so it says only be

used for debugging blah blah blah but it

never actually printed out hello here

and it says on networks apoia using

price feed at and it gives us this

address is this the right price feed it

sure is it is the sapoia price feed so


with this setup in our Mox and ATO our

codebase is now with this one line smart

enough to know okay if you're on an

actual Network I'm going to use the

address of the actual network if you're

not and you have a deployer script

specified we're going to go ahead and

we're going to deploy Mox and this is

how we're going to make this code way

way easier with this line because

otherwise we would have to say if sapoia

do this if mayet do this if local

network deploys a mock now we can just

all do that in one

line now for those of you who are going

uh Patrick you told us about this dry

principle you said like don't repeat

yourself yet we have to write the we

have to do this deployer script twice

for both Pym and for sapoia that's super

annoying why did you do that well what

we can do is also create what's called

top level named Network contracts so

right at the top we can do a little

Network networks. contracts and create

parameters for every single Network that

gets added so I'll do networks.

contracts. price feed and in here I'll

add the deployer script like here and

I'll delete this I'll delete the whole


PBM section and now for every single

Network there's now a deployer script so

if we don't have an address for Network

it'll automatically deploy a mock for us

and this makes our life a little easier

now for some people this actually might

be too scary for them right oh what what

if I put a new network in here and I

forget to like put an address I don't

want to have to waste the gas to deploy

a mock price feed that's 100% rational

and that's 100% reasonable which is why

you don't have to do it at the top level

but if you want to you can now let's go

ahead let's rerun this let's rerun this

just MOX r deploy we do get that hello

out meaning we deployed a new contract

we can see it's at this random address

on network pm and let's do a clear and

that's because what moccas did is it

said oh okay I don't have an address for

Network PM as you can see we don't even

have an entry for pvm in here so it says

great there's a deployer script I'm

going to use that and in fact since we

have the default deployer script for all

networks being this we don't even need

that for the suppo network then if I go

ahead and run this again on-- Network


sepolia we hit yes I got to enter my

password we see we do not we compile it

right which is why we get this compiler

warning but we do not deploy it we do

not see a hello in here and then we do

see on networks ofoia using price feed

at this address which again is the

correct address

outstanding that was a lot to take in

now might be a good time to take a break

especially if you didn't understand

something that was going on this might

be something to talk with your AIS with

to jump in the discussions jump in the

forums cuz a lot of that was pretty

complicated but like a lot of what we

teach you on ceron updraft just by you

learning this process you're learning

how to write tests more effectively than

many of the current smart contract

developers today so now's a great time

to take a break go on a walk go grab

some coffee go grab some ice cream and

I'll see you in a minute all right

welcome back you ready to keep going now

that you've unlocked this power of the

Manifest named where you have unlocked

the power to say hey if you were on an

actual network with an address let's use

that otherwise let's use a mock great if


you are let's keep going so we have

unlocked this power now so we have a

price feed that's going to be smart

enough to use the mock or smart enough

to use the actual addresses let's go

ahead and let's keep going with this so

we have a way to get this price feed say

hey this is the network that we're on

here's the price Fe that we're going to

use now let's actually pass that address

in to deploy coffee and run this deploy

coffee function so let's go ahead let's

say return deploy coffee using the price

feed dot actually let's just use the

price feed let's keep this as a Viper

contract here now we'll use buy me

coffee. deploy the price feed here and

this will return a coffee of type Viper

contract Viper contract so this will

actually deploy our contract with this

price feed then once we have this

deployed all we have to do is that last

step that verification we'll just say if

oh I guess we could pass the Active

network in again but I'm not going to do

that we're going to do Active network

equals get Active network we'll just say

if active network. has

Explorer like this result equals active


network. moccasin verif y just pass in

the Viper contract and then result. wait

for

verification

verification like this and then finally

we'll do return coffee so we'll say this

also returns a Viper contract and since

we just learned about deployer scripts

we'll also have our Mox and Main return

a Viper contract that way if we wanted

to we could very easily turn this into a

deployer script and now with this we can

do MOX run deploy which will deploy our

buy me a coffee

fantastic now we have this very

sophisticated way to deploy our

contracts no matter what network that

we're on so this way now that this is

all set up we can test our code on a

local network on an actual Network on a

fork network using integration tests

Fork tests whatever type of test you

want to do and if you're like Patrick

what the heck are you talking about I

haven't heard any of those words well no

worries that's what we're about to teach

you what those words are let's go in and

let's start going through let's start

testing this contract so it actually

does what we want it to


do now the different types of tests out

there will probably be a little

confusing a little hard to grasp the

first time you do it but this is another

one of these things where the more we

repeat it the more we do it the more

it'll start to make sense the more it'll

feel ingrained in your bones now that

we're getting into testing here let's

take a quick second to just talk about

some of the different types of tests out

there now we're back in the GitHub repo

associated with this course in section

with moccasin buy me a coffee might be a

different section number when you're

watching this but you have those images

of storage here if you want to take a

look by the way we have several several

several different types of tests and

these are all these types of tests are

basically true across any software

Paradigm on the planet so the test that

we've gone over so far something called

Unit tests and these basically test a

single function or part of your code the

next step up from that is usually

integration test and this is testing

different systems together or different

contracts together or basically the the


definition can be a little bit loose

depending on how you defined it then the

step up from that would be a staging

test and these are testing your code in

a production-like environment maybe for

example if you were to deploy a smart

contract to an actual Network and then

call the functions on and then call the

functions of that contract on that

Network spending real gas that would be

more of a staging test now one of the

tests kind of unique to blockchain is

going to be this type of forked test

although you could probably categorize

these as staging tests as well and this

is essentially where you deploy your

contracts to a fake virtual Network or a

forked Network and call the different

functions on it we've kind of done

something like this with tenderly

virtual network but we're also going to

do it with Alchemy here as well

and these fake networks will simulate

what it's like to actually work with the

real blockchain then there's fuzz and

formal verification now fuzzing is

incredibly important and you should 100%

learn how to fuzz and then formal

verification is when you mathematically

prove different functions and this is


probably the most time intensive for the

least gain so we have a whole separate

course on Cypher and updraft about

formal verification and assembly as well

so for us we are going to do all of

these types of tests for this project

and then pretty soon once you get to the

stable coin portion we are going to add

fuzz testing as

well so let's get started though let's

get started with the most simplest ones

the unit test these are the ones where

we just go hey let's call a function and

let's see if it worked okay so let's go

back to our startup here and in our test

folder often times you'll even see those

types of test set separated it out so

I'm going to create a new folder I'm

going to call it unit and this is where

we're going to put all of our unit tests

now as we learned before we're probably

going to want to use fixtures as well

and it's usually just best practice to

use fixtures anyways so not in my unit

folder but in my test folder so be sure

to do this in your test folder we're

going to create a new file we're going

to create that conf test.py make sure

this is not in your unit folder this is


in the test folder and this is going to

be our list of fixtures for all the

tests that we do anyways so in this way

we can reproduce the exact same code the

exact same deploy script across all of

our tests uh to actually start testing

our code we're probably going to need

our coffee contract so let's create a

new at pest. fixture def we'll just call

it coffee do a pass for now this yellow

squiggly line is going to annoy me so

I'm going to go ahead I'm going to

import pest like this great

and now we want to deploy coffee here so

what I can do is I can do from script

was it script or script script. deploy

import deploy

coffee and we'll do return deploy coffee

I'm pretty sure I'm going to go ahead

and command click this or control this

it takes a price feed in it sure does so

we're actually going to have to make

another fixtion another fixture at pest.

fixture def price feed like this and

this will return deploy feed like this

so we're going to have to get that as

well from script. deploy MOX import

deploy feed like this and we're going to

pass price feed this fixture as an input

to this fixture just like this that's


all you have to do so and then we'll

pass this in to here so this is how you

kind of so we showed you a little bit of

this before I know this syntax can be a

little confusing but essentially this

price feed fixture is going to return

the price feed contract and we're going

to pass the price feed contract into

this coffee fixture here which will get

pass into our deploy coffee function or

better yet you know I want to call this

ethusd instead of price feed so ethusd

ethusd like this great now I like to be

very explicit with my fixtures as we

know the scope always defaults to

function for all fixtures for our unit

tests we actually want to keep coffee as

a function fixture because we want to

basically test the contract from scratch

between test runs and again if this is a

little confusing don't worry it'll make

sense in a bit but the price feed we

don't really care if that one changes so

for this one I'm going to make the scope

a session so we'll deploy this price

feed one time and then that's it then

we'll never deploy it again great now

we're going to have a couple couple more

fixtures but now that we have our basic


fixtures let's go ahead let's start

writing some unit tests all right let's

do it so let's come over to the Explorer

let's create a new file we'll call it

test unit coffee. piy and let's start

writing some tests in here all right so

first we probably want to test how our

deployment even works we want to make

sure that when we deploy this coffee

contract we're using the same price feed

so maybe we'll just say defa

test price feed is correct and we're

going to use let's go back to the C test

and we're going to use these two

fixtures to test it so to add input

parameters to a test we'll say coffee

Neath USD and again this is where AI is

incredibly helpful you can even see it

kind of giving me a little assert here

I'm going to go ahead and hit tab I just

want to make sure that this price feed

is a public it's all uppercase here

because it is immutable so we're going

to have to actually change this

uppercase price feed and then we can go

ahead and run this do MOX test to run

all of our tests oh we have an error

it's because and whenever I run into

errors like this I like to use this

thing called a pdb or a python debugger


it'll drop me immediately into a

debugger whenever I have an error and I

can even kind of check okay well what

did this return okay returned an address

what about about this oh this is a

contract okay let me quit these aren't

the same obviously because this is an

address this is a contract so let's do

e. address and now let's test it and it

passes great so we have our first test

in the bag nice okay let's test these

starting values so let's do def test

starting values of

coffee oops and we'll do assert coffee

do minimum USD equals what is the

starting minimum USD going to be as W

value five ether so we'll say so we'll

use a built-in feature to Titanoboa and

Moccasin we'll say from eth utils import

to way this is essentially the exact

same as asway value in Viper so we'll

say equals 2way five comma ether like

this and let's also check the owner is

going to be the message.

sender now we should now checking that

the owner is actually going to be

messaged us sender we should make sure

that we're always working with the

correct account so when we run our tests


we can do something called Pranking

where we can prank so we can use

something called the get default account

of the Active network to make sure we

know exactly who is deploying our

contracts cuz when we run our deploy

script the Active network is going to be

the one that's sending the transactions

so what we can do is in our comp test we

can do at pest. fixture we can say scope

equals session for the entire session

we'll do def account we'll say

return Active

network and we got to import this from

moccasin doc config config

import get Active network we'll do get

active get active network. getet default

account and this will return the default

account now that we have this fix term

back in our unit test we can know that

this is the one who actually did the

deployment back in our unit test then we

can say assert coffee. owner equals

equals account and we'll pass that in as

a fixture to this as well and then we'll

make sure it works by running mock test

in the terminal and I spelled something

wrong I'm going to command click or

control click this and we have

account scoop there should be scope


let's clear and run again and oh not

quite we have an assertion error let's

do a little mock test- pdb let's see

account uh this is a account object

whereas coffee. owner is an actual

address so we have to fix this one more

time in our test this should be account.

address so they're both address objects

now let's quit the debugger and let's go

ahead and run this again and they're

both passing

nice now when we when we test our smart

contracts we also want to test sometimes

that they revert correctly so for

example if somebody calls our fund

function without enough money we should

expect this to actually revert so how do

we test for when a function reverts so

if we want to test that hey uh you have

to send a certain amount of money when

you call fund we could do a def test

fund fails without enough without enough

eth we'll pass in coffee what we can do

it's at the top we'll do a little import

boa and titano boa has a tool called and

we can do with bo. reverse like this and

then we'll run the coffee dot so this

would be equivalent to US just calling

the fund function without sending any


parameters or any value to it so if this

transaction fails this test will pass so

we can do a little MOX test- K and then

paste the name of the test in here it'll

run run just the single test and that

went ahead and passed now if we got rid

of this and we just ran this and then

clear rerun the test we would see a

failure happen because our transaction

failed with this error you need to spend

more eth so this is how we check that it

reverts we can even check the exact

revert code we can say with boa do

reverts with this specific revert code

and we should do this clear can run this

again

and we can see that this indeed

passes so now let's talk about some boa

cheat codes in titano boa and therefore

also in Moccasin you can both set the

balance of a user and also pretend or

prank a user and this is incredibly

important if we want to test how other

users or other users with different

amounts of money interact with our

contract now we want to call this fund

function and actually send some money

but we need to make sure that whoever

calls this fund function actually has

money to do so this is where we can


start getting into the concept of cheat

codes or functions that work with the PM

or local Fork Network in order to set up

our test better so for example if we

want to call fund like I said we need

someone to actually have money so let's

do this test fund with money as an

coffee like this and you know what let's

also do account in order for them to

call the fund function we might they

need to have some value so what we can

do is we do boa env. set

balance of account. address to some

amount and at the top I'm going to make

a send value I'm going to say send value

equals to way we're just going to do one

whole ether because we're going to be

not super specific here so bo. EMV set

balance account at address let's do send

value send send value Here and Now what

we can do is we can run coffee. fund

value equals send value and this is

still part of the arrange this would be

the act now we can get into the assert

where we should assert well first let's

get the amount funded it's going to be

coffee dot what is it funders fers at

index0 funders at

index0 excuse me funer this should be


equal to account so first off we should

say uh assert fun equals account that

address and then we can also do

assert coffee do funded to amount funded

funded to amount funded of fun equals

equals send value we'll go ahead and

we'll run this test we can do MOX test

to just run everything or we can do MOX

test- K to just run this command and

that passes now something that you want

to avoid doing is having double asserts

or having two asserts typically you

really want it to be one test one assert

as a rule of thumb sometimes it's okay

to break this rule like what we're doing

here but if you were to get a test break

after some change you would have to go

into the test and then check to see if

it was this assert or this assert so

it's typically better to have one assert

one test but they're more like

guidelines anyways great we're testing

some basic functionality here and I'm

going to leave a lot of time for you to

actually write a whole bunch of tests

because you should get incredibly good

at writing tests AIS are very helpful at

writing test and you should use AIS to

help you write your tests but sometimes

AI screw it up and what's worse is if


you write a test or AI writes a test and

it doesn't test what you want it to test

and it breaks that will be very bad so

let's keep going and we'll leave you

some time to write tests

afterwards now sometimes when we're

writing tests we also want to to pretend

to be somebody else or we want to prank

now at the time our account the default

account is going to be who deployed this

address but we should probably check

that the non-owner cannot withdraw right

so and buy me a coffee

we have withdraw we should make sure

that if you're not the owner of the

contract you cannot take the money out

so we should get this revert error not

the owner so we can do something called

Pranking to pretend to be some other

user now first off to get some other

random user we can assign a value random

user equals boa do generate address

we'll just say non owner o

and this will generate us an account

with a random address then we can do a

little def test

non-owner cannot withdraw pass in coffee

like this first off we will want to fund

it so let's go ahead and add these two


lines in here so let's also pass in the

account so we will start up by having it

funded then we'll say with boa prank

random oh a random user we'll say with

bo. revers what's the error not contract

owner copy this not contract owner when

we call coffee. withdraw and then I need

a little qu here so we're arranging

we're getting the setup making sure it's

funded and then we are pranking the

random user and we are reverting and

let's go ahead and test this little MOX

test and module boa oh boa

env. prank let's try it now and they all

pass nice so this is how you pretend to

be some other user this is how you set

the current user to somebody else random

and this is how you revert like so so so

anything that you put inside of this

like with segment you will be pranked as

this random user cool let's keep going

so this is how we check to see if it

doesn't work let's also check to see how

it does work so we can do te test owner

can withdraw like this and we'll do

coffee and we'll do account now usually

just to make sure I do like to also

prank that I'm actually the owner here

so I might do something like first off

boa Dov do set balance I'll


do coffee do owner to send

value I will then do with bo. env. prank

let's actually prank the coffee. owner

owner should be all caps this then I can

do coffee. fund value equals send value

and then I can also do coffee. withdraw

and I should be able to assert coffee

do assert

boa.edd need a bounce of coffee coffee.

address excuse me on the test and it

passes now having to copy paste set

balance and then fund for all of our

tests is kind of violating that dry

thing that don't repeat yourself so we

can actually make another fixture that's

a little bit nicer than this going into

our fixtures we'll do at pest. fixture

we'll say scope equals function for this

as well and we'll do defa coffee fun

and then we'll just pass in coffee and

all we'll

do then in here we'll do coffee. fund

value equals coffee coffee do minimum

USD or let's also just add a send value

in here and let's make our code a little

bit nicer so let's take send value

delete it put it in here say send values

to way which means we going to do from

from eth utils import to way like this


and now send value it's going to C down

here copy. fund send value and this

means that we might have to actually

have an account anyways so let's you

know let's do an account we'll do boa

doet

balance balance of

account. address to account excuse me of

uh send

value and that means we need boa in here

import boa then we can do a little with

bo. em. Frank count. address just to

make sure that we're using this wallet

address on this and now we have this

coffee funded picture we can now do

coffee funded uh we can now do coffee

funded and we can skip the arrange up

here we can do coffee funded we can skip

this line that means we can skip this

line this means and then instead of

coffee we'll do coffee funded same thing

up here instead of coffee we'll do

coffee funded and for this send values

and these we'll import that from conf

test we'll say from

test.com test import send value and now

we can run all of our tests again MOX

test non type has no attribute owner and

that's because I forgot to return I sure

did return coffee now let's run this


again MOX test and everything

passes nice so we've done a little bit

of a refactoring to make our code a

little bit more efficient and our tests

are starting to look really good here

all right so now I've taught you pretty

much most of what I want to teach you as

far as the unit tests go I want you to

pause a video and do a little midsection

Workshop here I want you to write one of

the last tests before we move on to

doing some more interesting stuff

including coverage integration tests

Fork tests staging tests Etc so we're

going to do Workshop one I want you to

write a test that first off funds the

contract with 10 different funders so we

learn how to make different funders

right right at the top I want you to

figure out how to make 10 of them for

bonus points do something more clever

than just like for bonus points to

something more clever than just having a

bunch a whole bunch of different users

like that but doing a a bunch of

different users like that is also okay

then withdraw the funds using the owner

so how do you become the owner well we

learned a little bit about pranking we


also learned that we learned a a little

about pranking and then finally SE that

the ending balance of buy me a coffee is

zero the ending balance of the contract

is zero and then the ending balance of

the owner is the addition of all the

amounts that the different funders put

in so pause the video pause the course

try the this Workshop as always spend at

most 25 minutes on this prompt without

the aid of AI and if you're unable to

solve in 25 minutes stop take a break

work with AI work with the discussions

to help you solve them I also have a

dummy example of what this could like in

the GitHub repo associated with this

section so pause and good

luck all right welcome back I hope you

did that challenge because again like I

said writing test is incredibly

important and we really want to make

sure that we're testing all the

functionality of our contracts here I'm

not going to add that final test in here

but again it is on the G repo associated

with the section so if you want to take

a look at what I did feel free to do

so so I'm going to clear this out now

and we're going to talk about our our

next thing so you might be thinking hey


you know what I've done a pretty good

job testing all of my contracts here I I

think you know I think I've tested

everything I'm I'm could I'm content I'm

content with the amount I've tested and

this is where the concept of coverage

comes into play so moccasin comes with

support with this thing called pest Cove

which is a way to test something called

coverage and here's the documentation

for it coverage is essentially testing

how much of your code you've actually

tested and this is a pretty common

Concept in all software engineering

paradigms whether it's smart contracts

or JavaScript or python or whatever a

lot of the commands that pest COV comes

baked in with are also in Moccasin so if

I wanted to test hey uh how much of this

contract have I actually tested what I

can do is I can run MOX

test-- coverage and what this will do is

it'll run all of my tests and compare it

to how much of my contracts I've

actually tested and if we look here we

can see actually how much of all of my

python scripts we've tested and we can

see SRC byy meac coffee. VI we've tested

about 86% of it we've missed at least


two statements if we type MOX test--

help we can see a lot of the different

coverage commands that go with this to

see the exact lines that we are missing

the exact lines of code that we haven't

tested we can do MOX test D- coverage D-

what is it called cover report term

missing cover report term missing and

we'll see the exact lines we haven't

covered over here so for buy me a coffee

lines 64 to 69 we have not tested so

let's go into 64 to 69 let's scroll down

here where is 64 so

64 to 69 aha so we're not testing our

get e to USD rate and we're also not

testing our default function so let's go

ahead let's write a test for just get

eth to USD rate so if I go in here I can

do like a little test def test get rate

with coffee like this and we can do a

little assert coffee dot what is it

called get e USD rate get e the USD rate

of one well we could do the math here

and figure out the price ourself what it

would be but we could also just do 1 is

greater than zero we should get

something that's not actually it might

be zero so let's do uh let's do the send

value let's do the send value the send

value should be greater than zero right


because we're sending one whole ether so

this should be worth around $22,000

right so let's run this line let's do

MOX test- K paste it in Great it passed

now let's go ahead and run our coverage

report again

and now we see for buy me a coffee we

only see that line 69 is now missing

right because our coverage report is

smart enough to go oh okay cool you call

this function now great it's at least

been covered one place in your test

Suite cool you still haven't covered

this one though this function has never

been called and then we would need to

add a function that calls the default

function now a while back I promised you

that we were going to show you the

differences in gas costs between storage

variables and then constant variables so

let's finally do that so to do some

testing let's go ahead let's do little

MOX test d-el again we can see in here

there is a gas profile command here

where we can get an output on gas use

for all of our test functions so if I

just run MOX test-- gas- profile this

we'll get this crazy output here which

will literally tell us how much gas a


lot of these functions cost now this is

kind of borderline impossible to read so

what I might do is I might run this

again with a little Zoom way the heck

out now I'm going to run this command

Zoom way back in and I can see things a

little bit better now so we have count

mean medium standard deviation Min and

Max if we scroll down into the section

down here we scroll over we can see how

much calling each one of these functions

costs including the functions up here

the different lines and obviously you

know our different functions down in

here we can see first off the count is

how many times in the test it or the

test Suite it was called what is the

average gas cost the median gas cost

standard deviation the minimum and the

Max and it's literally for like every

line of computation here which is kind

of crazy okay raw call owner let's look

at this one so this one was 19 gas on

average Okay cool so now let's go back

here let's do a little refactoring you

don't have to do this by the way let's

get rid of it being a mutable so owner

is no longer immutable so we'll do self.

owner here any place we see owner where

else is owner owner self dead owner


we'll do self. owner here self. owner

here okay great so remember this was 19

gas when it was a constant or excuse me

19 gas when it was an immutable let's

rerun this again to gas. text now that

we're using self. owner oh I got to

sorry I got to zoom way out and run this

zoom zoom zoom zoom zoom up up run it

Zoom way back in now let's see now it

costs more now it's 21 here so we can

see that we actually ended up spending

more gas by having it be a storage

variable so I'm actually going to move

it back to a mutable so if you want to

check how much more or less gas your

contracts use you can use that gas

profile

command all right great so what's next

so we've written some unit tests awesome

we learned a little bit more about gas

we could write an integration test but

we've kind of been doing that with our

unit test here so I'm actually going to

skip it for now but we haven't done the

staging tests and we also haven't done

the forked tests so so let's go ahead

let's actually let's create the staging

folder but let's do the fork test first

cuz technically the fork tests are a


type of staging tests now what are Fork

tests now Fork tests are going to be

very similar to us just working with the

tenderly virtual networks or our

tenderly virtual network is an example

of a forked Network so what really is a

forked chain cuz I've kind of been

dancing around a little bit well so

imagine there's a real blockchain right

a real blockchain is happening and

blocks are being you know added and

people are sending transactions and

everything well imagine we on the side

what we do is we spin up our little fake

Anvil chain we f up a spin up a fake

much much tinier much tinier little

chain I'll make it a little black and

I'll say this is our we say it's an

empty chain our empty new chain and it

actually starts off as as empty there's

nothing in it right it's just a a real

real minimal empty chain that we spun up

this could be like your Anvil or

whatever now the idea behind a

blockchain is that it will resemble

everything that's on a real blockchain

but in an easier way so if in my python

code I'm connected right I'm connected

to this forked blockchain but I call

Price fee. latest answer well our forked


blockchain is empty it right it doesn't

have this price feed on it well the real

blockchain does have the price feed

right it does have this price feed

contract so since we're connected to

kind of this forked empty little little

thing what happens is we say hey uh we

want the latest answer our fake chain

what it does is it makes an API call to

the real chain says hey uh I need I need

this I need this price feed I need this

contract and what it does is kind of at

request time it'll grab that price feed

and give it to itself give it to itself

and it'll be like oh yeah you know uh I

had this the whole time they'll go ah I

had this the whole time and then we will

get we will be able to call it interact

with it as if we were interacting with

the real blockchain this allows us to

quote unquote have the whole blockchain

but only really when we request

something about the real blockchain this

is also incredibly helpful for us to

have this forked blockchain because then

we could do something like buy me a

coffee. deploy and we'll deploy it to

this forked faked blockchain which kind

of has all the real contracts that are


on the actual real blockchain because

anytime any of these contracts need the

data from a contract our forked

blockchain will just go ahead and grab

it and like copy it to itself

essentially so forked blockchains are

incredibly helpful because they allow us

to simulate a real blockchain without

actually having the whole blockchain but

for our from our perspectives we have

the whole blockchain at our disposal

which is really really nice and forked

tests and running Fork tests therefore

are one of the most important steps

whenever you're going to try to deploy a

smart contract because you want to see

hey what do my tests look like compared

up against a real blockchain with the

real contracts because my mocks my MOX

for example could have been wrong I

could have screwed these up right so we

always want to run what's called forked

tests now these are actually really easy

for us to run in Moccasin all we have to

do is in our moccasin Doo we have to

have a real Network set up and then what

we can do is we can just do MOX

test-- Network sapoia let's say we

wanted to test our smart contracts

against the real sapoia test net but


then all we have to do is Das Dash Fork

this tells our test Suite to yeah use

the aoia test net but run it as a fork

don't run it don't actually deploy any

contracts don't actually do anything and

if we hit enter we do have to enter our

password for the default key because

because we did set the default account

name to default so we do have to do this

you could have we could have not done

that and it would have worked a little

bit easier but anyways let's enter the

password you'll notice it didn't prompt

us to say hey you're sending a real

transaction cuz it's smart enough to

know that we're not now this will take a

little bit longer to run these tests

because we're actually making API calls

to our sepolia RPC URL and I just

realized that our Active network does

indeed have an

Explorer um but we need to do and Active

network uh dot is local or forked

network is false here because if we

don't have this line when we go to run

our Fork test this is going to try to

kick off and uh we don't want to verify

to Nowhere Ville so uh yeah so uh now

that we've updated this if active


network. has an Explorer and it's not a

local or forked Network now we can run

MOX test-- networks aoia D- Fork and we

see that everything passes so this is

additionally why it's so important to do

these conf tests as well where is the

conf test to the to do the conf test as

well if for example every single time we

had to create a new account that would

take more time doing the fork tests

often take substantially longer than

doing the pvm tests so now this might

seem like an easy little step here

because it was essentially just doing

the same thing with like a dash Fork but

you can often find a lot of bugs just

doing the fork tests so be absolutely

sure to always run your fork

test the last type of test that we're

going to be working with is going to be

staging tests and we Fork tests are

technically a type of staging tests but

we're going to be also having a type of

test where we can actually deploy the

smart contracts to a test net or even to

a main net maybe there's a set of tests

you want to run on an actual Network to

make sure that that network does what

you want it to do so we can also signify

very special staging tests to run on


real networks and if you go to the

documentation for moccasin you can

scroll down to staging markers to learn

more about these so the idea is that a

lot of developers should run some sanity

checks on live Network for example if

you're working with oracles or any setup

tricks but a lot of people don't so in

order to run a test on an actual test

net we have to mark it with a staging

pest marker this will tell moccasin hey

if you're on a live Network you can

actually run this you can actually

deploy this code you can actually send

these transactions and if you don't have

a staging test anytime you're running on

a live Network it Should Skip it you can

also have by default all tests are

marked as local if you want a test to be

both staging and a local test test you

can do that but I digress so let's go

ahead let's write just our one and only

staging test and you'll see what I mean

here so if I'm in my staging folder

create a new file we'll do test

staging coffee dopy like so zoom in a

little bit and we'll do def test can

fund and

withdraw live so this is going to be a


live test I'm going to do this

actually on seoa now when we're working

with staging tests you can use your

fixtures the same fixtures that you're

using in your unit test but usually it's

actually best practiced to use a

different conf test so if you wanted to

you could actually create a new file in

here called conf test you could have two

conf tests and then you would use just

use the fixtures from this one I'm just

going to skip that for now to make it

nice and minimal but we're going to go

ahead and get started here we're going

to say we're going to first off get from

moccasin doc config import get

Active network like this we'll say

Active network equals get Active network

and then we can do get the price feed

equals active network.

manifest named of price feed so this

manifest named should as we know get us

this address here or get us a contract

at that address then we'll say coffee

equals deploy coffee like this so we're

going to have to do and yeah these

probably should be fixtures for staging

test but since we're only running this

once it's okay we'll say from script.

deoy import import deploy coffee like


this deoy coffee needs a price feed

address is it the address or is it a

contract it's a contract so we just pass

in price feed now we can just call

coffee. fund because we're going to be

calling we're going to be setting our

eoa as our default wallet and it should

have money in it on our tenderly Network

here we'll say value equals send

value we'll actually get this from the

conf test so from test.com test import

send value so we'll fund it and then

we'll get the amount funded equals

coffee. address to amount funded from

the boa.com

active account the account sending all

the transactions so we want to get how

much money they've sent in it should be

send value and we can even assert that

we'll do a little assert amount funded

equals send value thanks chat gbt then

since we also should be the owner we can

then do coffee. withdraw like this and

then we'll assert boa

do.get balance of coffee. address should

equal zero so since this is a staging

test here this will only run on a live

Network or when we allow staging tests

to run so what I can do is I can do MOX


test we're going to do Dash Network

sepolia and it's only going to run that

single test because that's the only test

it's only going to run this single test

because this is the only test we said

hey this is cool to run in a real

environment this is this is a staging

test it is okay so now I'm going to hit

yes and we run into an error uh no

default EA account that's my mistake

let's go back to moccasin go back to

sepolia let's do default default account

name equals

default let's try running this again now

yes to my password Pro does not have evm

snapshot capability and if you get that

error the final Mark you have to add is

this ignore isolation this is something

that BOA does to help us run our tests

and kind of snapshot different tests for

running later we don't want to do that

with our staging tests so we're just

going to go ahead and add this ignore

Isolation part here and we can finally

do

topolia yes Al to my password and this

will take a lot longer because we're

actually sending real transactions hence

why this is a little ill-advised you

really want to do staging tests as the


last step before going to audit or the

last step before actually deploying and

if you're watching this you do not have

to do this because again you're going to

have to spend test at eth that can take

a long time you're going to have to

spend test at gas that can take a long

time our scripts also are trying to

verify the contract as well so this test

might actually take quite a long time

and this actually failed because we

added the contract verifications so we'd

want to modify our deploy to only run

the ver verification not here but in the

main function I'm just going to even I'm

just going to comment this out sorry for

the multiple back and force and we're

going to run this one more time and this

one failed because I don't have any

money and I set up my test to send a

whole eth and I do not have a full suppo

eth but you get the picture so I should

have wrote my test a little bit better

should have wrote my scripts a little

bit better but in any case this is how

we can write a staging test to actually

work with a real live Network

so so now we have some so now we have

some really good tests if I run MOX test


boom everything instantly passes I know

how to run the staging tests you know me

Patrick I kind of screwed up writing

them a couple times but you get the idea

and it's really not worth me going

through it because I don't really want

you to run it anyways but now let's

finally look at this save to DB thing so

we've been seeing on on a lot of these

counts this save to DB equals false save

to DB equals false so what is that what

is it for and why do we care about it

well moccasin and titanol will actually

save your deployments to a database a

SQL like database this way we can it's

much easier to interact with them in the

future so let's say I had a contract

actually deployed on a network and I'm

actually going to create one more

Network in my moccasin just to work with

and Vil I'll do a little same as we've

been doing networks.

Anvil URL equals

HTTP 127.0.0.1

we'll do default default account name

equals Anvil one and I'll leave I'll

this time I'll set save to DB equals

true okay and we're not going to set a

price feed for this one because we want

to deploy a new price feed so if I open


up my terminal let's open up a new a new

terminal we'll run Anvil here great I

can now deploy to my Anvil network with

MOX run deploy D- Network Anvil oh is

the oh I have the URL wrong let's fix

this to fix this I need the port great

so let's clear let's run this again yes

enter the

password and great we now have a price

feed deployed to this address and we

have our coffee deployed to this address

since this time I have saved Tob equals

true now on the left hand side here we

now have this deployment. DB and this is

going to keep track of all of our

deployments if we wanted to withdraw

from our most recently deployed contract

we would might have to go like okay we

might have to grab this address we might

have to do like you know from SRC import

buy me a coffee like this we have to do

buy me a

coffee. this address coffee equals but

if we were to deploy a new contract um

and then run coffee. withdraw withdraw

right but if we deployed a new coffee

then we'd have to go and re-update this

and that could be a lot of work we want

to work incredibly hard to be incredibly


lazy so what we can do is we can

actually go back to that manifest named

contract and that manifest named we'll

also check to see if we recently

deployed a contract so instead of this

we're going to do from M.C config import

get Active

network we'll do

active Active

network equals get Active network and

then instead of this we'll do active

network. manifest

named coffee and then just do coffee.

withdraw and we can even do a little

print print F statement here to make

sure working with contract contract.

address excuse me coffee. address so as

of right now I have this coffee address

I have this address deployed on our

Anvil chain and it should be saved in

our database

so if I run this withdraw function

what's going to happen is we're going to

run this manifest name contract and

again we look at our moccasin Doo it's

going to see okay I don't have a coffee

I do have a deployer script maybe he

wants me to deploy it but let's check

the database real quick it's going to

see there's an address in the database


and it's going to use that address let's

do MOX run withdraw D- Network Anvil yes

enter my password

on network Anvil using price Su blah

blah blah TX broadcasted working with

contract blah blah blah working with

contract here so now that we have that

all set up if I run MOX run deploy D-

Network Anvil like this I'm going to

type yes type my password we're going to

get a transaction has been broadcast and

we're going to see our coffee was

deployed to Anvil to this address

now we get is we have this deployments

deployment. DB database and now this is

a SQL light database this will store all

of our deployments on networks where we

have save to DB equals true I can now go

into my extensions I can look up a

sqlite extension I'm going to use this

sqlite viewer I'm going to go ahead and

install this and now what I can do is in

my deployment. DB even kind of like

formats a little bit nicer if I click on

it I'm able to see

what is in here so I can see all the

different tables such as session ID

contract name contract address contct

name RPC deployer TX TX project blah


blah blah what I can do is I is if I

scroll over I can see the contract

address that was just deployed for the

contract name buy me a coffee so if I

pull up this I can see Ox E7 F1 in my

database I have Ox E7 F1 for contract

buy me a coffee now what I can do now

that I have this let me X Out is I can

create new function where I say where I

interact with specifically that address

I'll go

active act Network equals get Active

network Active network Active network

and I can use that manifest contract

function again or that manifest named

function again cuz what it'll do if I go

to the

M.L is if we're on Anvil first thing

it'll do is it'll say hey is there an

address here that he specified okay nope

there's not one next it'll say is there

an address in the database and it will

see one it'll see one right here with

buy me a coffee and then if it doesn't

see that then it'll look for the deploy

script for buy me a coffee which this

shouldn't be coffee this should really

be called buy me a coffee but I digress

so now what I can do is I can do coffee

equals Active network dot manifest named


by me a coffee like this and then I can

do coffee. withdraw withdraw to even

make sure we're on the right Network

working with the right contract I can do

a little print little print F statement

on network Active network not name

withdrawing from

coffee. address thank you chbt for

picking that up for me now if you don't

want to use this manifest name because

there's too many conditionals okay if

there's a price feed if there's

something in the moso and if it's in the

database and if there's a deployer you

can also do coffee equals active

network. getet latest contract unchecked

by me a

coffee now get latest contract unchecked

means that get me the latest contract

deployed that has the name buy me a

coffee if you do get latest contract

checked it'll say get me the latest

contract named buy me a coffee that must

have the same bite code as my current

buy me a coffee so if you want to be

more specific you can use these get

latest contract checked you can also run

SQL there's commands to run raw SQL

there there's commands to get all the


deployment ments there's a whole bunch

of commands that we can run but we're

going to do this manifest named and this

is another why it's best practice to use

this manifest named because it's

basically always trying to figure out

okay what what contract did you mean so

now if we clear and we run this MOX run

withdraw withdraw D- Network Anvil like

this type yes type the password in on

network Anvil withdrawing from the exact

same address that we just deployed

transaction broadcasted and then we did

the withdraw so this is how we can have

even more powerful scripting and as far

as like the devops goes and working with

our latest deployed contract keeping

track of deployments moccasin keeps

track of all of that for us and this is

incredibly

exciting we have learned and an absolute

ton here and guess what there's more so

let's close Anvil here we can also test

once again against ZK sync if you have

the ZK sync prerequisites installed

again that's going to be the era test

node-- version and it's going to be the

ZK Viper D- version if you have those

installed you can always run MOX

test-- Network ARA VM that will spin up


the fake ZK sync Network work oops and

if we run the test here we get some uh

not enough balance errors so let's uh

let's do like send value times three to

set the balance here actually let's do

send times 10 just so that we don't have

to deal with any of that let's rerun our

test on the Arrow VM oh and we also have

to do this test fund with money as well

set balance let's do send value times

let's just do three just to be safe run

again and boom

everything passes on ZK

sync and we have one thing left to do

here one thing left to do it's finally

time for your GitHub repos for your

GitHub profiles to start to develop and

also your cyphon profiles as well people

always ask me Patrick how do I get hired

what do I do after I take your

curriculum and the answer is you do a

lot of stuff and you got to show up off

all the cool stuff that you're doing so

pushing your projects to GitHub and then

also signing up for cyphon profiles is

going to be how you start showing off so

I'm going to have a link to cyphon

profiles of course in the GitHub repo

associated with this course but now


we're going to do what I think is

arguably one of the most important

things for us to do in this entire

course and this is push our codebase up

to GitHub I've mentioned this a couple

of times but GitHub is how a lot of the

entire blockchain industry works for

example if I look up gu GitHub entally

the go implementation of ethereum it's

got 20,000 Forks almost 50,000 Stars

2,000 people watching it this is one of

the most popular repositories in all of

the evm in the blockchain ecosystem the

go ethereum is the code that runs one of

the most popular ways to run an ethereum

node if you're were to look up moccasin

cyphon moccasin that we've shown you

before this is the G up repo of the tool

we're working with if we look up Viper

we look up Viper in here Viper Lang

Viper 5,000 Stars almost a th000 Forks

this is the language that we're learning

in here and if you go into issues you

can see countless issues you can see

countless PLL requests this is how

developers interact with each other this

is how developers in the open source

Community contribute and work with each

other and guess what I do sometimes I

might go to repo I might go H okay who


is working on this who are the cool

people here I might click someone's

profile and go whoa this person is

working on some really cool stuff and

especially if you're a hiring manager

this is often how you're going to do a

lot of your hiring is looking at

people's profiles and saying what is

this person about what does this person

do what have they done what have they

shown success in and the cyphon profiles

as well they do the same thing

especially when it comes to competitive

Audits and security which is something

that you can get in much much later

after finishing the updraft curriculum

and the profiles are growing more and

more with more and more interesting

features coming out to show off to

potential hiring managers so the first

step though is for us to push our code

up to GitHub and sign up for cyphon

profiles so let's go ahead let's get

started pushing up to GitHub you have

done a ton in this project and this is

the final step this is a badass project

that you're going to push up now the

first thing that you should check

finally is that in the dog ignore the


EnV is in here so way way back when I

was like Hey The Pledge the EnV pledge

blah blah blah if we go back to the

GitHub repo Soo with this course let's

scroll way up to the top let's go to

discussions here the EMV pledge in here

we said I am aware if I forget a DOT get

ignore and push my key SL phras get up

for even a split second it should be

considered compromised thisg ignore is a

file that says hey when we're pushing

stuff up to GitHub ignore these files so

we do not want to share these files we

do not want to push these up to GitHub

if there's anything else sensitive that

you don't want to push up to GitHub it's

a good idea to put it in this file we

will we will still be able to check what

we're about to push up to GitHub before

we push it up that's how that's why this

line in the pledge is so important and

then additionally down here

now this sentence makes sense use the

buil-in functionality of moccasin to

encrypt my private Keys now you

understand how that works now you

understand you never ever ever need to

really deal with your private Keys ever

again so now this is the GitHub repo

that I'm going to be deploying to and


it's a newer GitHub repo because I

wanted to show you what a blank GitHub

repo looks like it's got this sick neon

sign as the Avatar so to get started

here we first need to make sure we have

git installed g-- version per usual this

is one of the things we installed way

way way at the beginning of this whole

course so you should have get installed

if you don't have get installed there's

a ton there are links in the GitHub repo

associated with this course as well as

AIS are very helpful at this Google's

very helpful at this there's a lot of

places where you can install git now

GitHub is a centralized company and

there are decentralized versions of

GitHub being worked on but as of today

GitHub is what we have as of today

GitHub is still the dominant player to

the point where we kind of have to use

it so with that being being said if we

go to the GitHub docs we should go to

the get started and in here it says get

started with GitHub documentation we'll

go to the quick start as well and you

should have already created an account

on GitHub right so you should already

have an account here so you don't have


to do that one you don't have to set up

your profile downloading files now we

could follow along with this uploading a

project to GitHub but this is going to

show you kind of the manual way to

upload everything and that's cool but

like I don't want to have to go onto a

website every single time I want to

upload my code I want to work incredibly

hard to be incredibly lazy so what I'm

going to do instead is I am going to

first come to repositories I'm going to

select new and I am going to create a

new repository but I'm going to upload

all the stuff from it from the command

line so we're going to call this our MOX

buy me a coffee cyphon updraft and we

are going to make sure this is public so

other people can see how cool we are for

finishing this project we're going to go

ahead and click create repository and

boom now this is created there are some

notes down here it says quick setup if

you've done this kind of thing before or

create a new repository on the command

line and this will show you how to get

set up here as well but this assumes

you're already signed in we are not

signed in we want to do this the

hardcore way so we're going to look


upload locally hosted hosted files

adding locally hosted code to GitHub and

this is what we're going to follow and

since Windows users are using WSL you

should be following the Mac or the Linux

stuff here I'm going to follow along

with the Linux pieces this link will be

in the GitHub repo associated with this

course so the first thing that we're

going to need to do here is do get a nit

and this will say initialized and empty

git repository at this location right at

your PWD wherever you're working with

you might even see some colors light up

in your vs code as well and that's

actually our first step in the docs as

well initialize a git

repository it says get init DB main you

can do that as well or just get in it

like what we did don't do this one then

what we want to do is we want to decide

which one of these files we want to put

into what's called Version Control or

Source control you also might see

something that this pop up this tells us

what branch we're on you can learn about

branches another day but we want to say

which files we want to push up to GitHub

which files do we want to share with the


world now if we do a little git status

what we can see is a list of all the

different potential files that we could

push up to GitHub all the different

files that we've recently made changes

on that we need to update and all these

look pretty good so this is a coverage

file for coverage get attributes get

ignore these all look fine I don't see

any I don't see the EMV in here this is

great if you want to test it if you go

into your dog ignore delete the line

that says EMV then run you know clear

get status again now in here oh looks

like we still don't see it oh it's

because there's more dotting beads

there's a whole bunch of doting beads if

we delete all the envs and then we do a

get status we now see EnV is in our list

of untracked files that's very bad so

I'm going to undo all of that that we

just did I'm going to do get status

again now it's no longer in there now we

can override the dog ignore but having

the EMV and any sensitive stuff in the

duck get ignore is going to be helpful

to not push it up to GitHub so this is

the list of stuff that we're going to

push up to GitHub you might notice on

the leftand side if you're using vs code


depending on how your formatting is some

of these are green and some of these are

grayed out so moccasin comes default

with this dog ignore and it

automatically Grays out a bunch of stuff

like B build out lib D store Etc so some

of these are great out because you don't

really need to push a lot of these to

get up you definitely don't need to push

the deployments database you don't need

to push your DMV the eror test node the

compiled out folder live there's a bunch

of stuff that's not really important

that you share with the world so we

don't push it up so once we have it

initialized we can choose which files we

want to add by we can do get add uh SRC

like this now if we do do get status we

see oh everything in the SRC folder is

in this other section called it changes

to be committed and then down here is

untracked files so this is like a

stanging ground for it's like hey it's

almost committed it's almost pushed up

to GitHub these are the and these are

the files that we've changed but we

haven't like we haven't staged them to

be committed to just stage everything we

can do get add period this period stands


for everything in this current directory

do a clear I do a get status again now I

see all the files that are staged to be

committed to what's called my git

history so this is where you want to

take a second you want to look in here

and say okay are all these files things

that I want to push up to GitHub or all

these things is everything in here

something that I want to commit to get

history and if you're like oo I don't

think so you can run this command like

get remove cash readme.md for example

clear and now I do get status again now

we see read me is once again untracked

and these ones are staged I want to add

it back so just do git add dot like this

run another git status and now I see

once again everything is in here now to

commit this to our local git history we

would do git commit dasm which stands

for message and then some message like

our first commit little exclamation mark

there enter oops uh sorry it's uh single

quotes not double quotes wow what a Nob

Mistake by me now you'll see this create

mode for all this stuff and it's

entering all these files into our git

history now if we do a little git log we

can actually see a log of all the


commits that have ever been done and we

can see we just have one our first

commit now if I do a get status it'll

look like it's blank there's nothing to

commit this has been committed to our

locally running commit history but if we

go back to GitHub we do little Refresh

on our repo here it's still blank uh

what the heck Patrick your GitHub repos

have like so much code what's going on

well we we need to push our git changes

to GitHub so this is this git commit is

only on our machine we got to push it

over to GitHub then we have to do what I

think is arguably the hardest part

importing a git repository with the

command line after you've initialized a

git repository you can push the

repository to GitHub using either GitHub

CLI or git you can download the GitHub

application as well if that's going to

make your life easier you could 100%

download the GitHub CLI and to be honest

that'll probably make your life a little

bit easier if you're struggling but I

want to do it raw with the git command

because it's going to allow you to use

more than just GitHub as your remote

provider and if that doesn't make sense


don't worry the more you do this

eventually that will make sense so we're

going to follow this adding a local

repository to GitHub using git it's

important to note that GitHub and git

are different right when I type g--

version this is a tool for doing Version

Control Management and GitHub is a place

to push code it's like like a cloud

provider or like a Google Drive for code

if you will so git is a tool GitHub is a

company they are different so for us to

do this we're going to need to create a

new repository on GitHub we've actually

already done this well done us to avoid

errors do not initialize the new

repository with REM license or GitHub

files we've already done that great so

then next says at the top of your

repository on github's quick setup page

click the copy button to copy the remote

repository URL okay so that's going to

be this button right here okay clicked

it and then what we're going to do is

we're going to open our terminal and run

a couple of commands here so we're going

to run this command here we're going to

run get remote add origin and then paste

that

in there and what this is going to do is


it's going to when we type get remote- V

it's going to say whenever we push or

pull code from a remote git repository

it's this one that we just set up it's

this one that we just set up it's the

one that we're going to use and then

finally you can just run git push dasu

origin origin main like this and I'm

getting an error because I'm logged in

as a different user whoops so to make my

life easier I'm just going to give

access to Patrick all right so I've gone

and added my other account to this one

I'm just going to rerun that command and

what's going to happen now now if I do a

little refresh here now I see all the

code that we just created in here now we

have a terrible read me and if you've

been following along with the GI up repo

associated with this course of course

you know that in most of our readmes you

know let's look at uh yeah let's look at

this one for example if you go to the

codebase associated with this one it has

a really nice read me where it says

here's how you get started here's how

you can install here's how you can work

with all the code in this code base but

now I will tell you right now there's a


good chance that you'll run into an

error here and working with AIS AR are

phenomenal at triage and GitHub issues

so if you run into an issue please work

with an AI be sure to Google around

because getting this up here getting

this project up here like I said is

incredibly important for your career

because guess what if you go build a

bunch of amazing awesome really cool

projects and really cool things people

want to see that so you kind of have to

show it off you have to have a place to

show it off for example like I wrote how

to sign into my get config on my command

line this question kind of doesn't

really make sense but Claude is still

actually giving me pretty good

information here saying here's how you

set your username your email verify your

settings Etc so pause the the video

pause the course be sure to try to get

this up be sure to take the time it is

to get get this up and I'll see you in a

minute now like I said on every single

one of these GitHub repos that we make

on Cypher updraft we usually have this

section called installation where we do

like get clone and CD mock buy me a

coffee blah blah blah so what we can do


is I'm going to show you what it looks

like to like do one of these clones so

if we're in our mock CU folder here and

I run get and I you know actually just

paste this command get clone get up.com

cipon MOX by me a coffee I can rename it

to something like cyphon buy me a coffee

Mox and what and what this will do is if

I type LS now there's this new cyphon

buy me a coffee MOX in here and I can CD

into that cphon bu me a coffee MOX I can

do code or file open and and get it up

here and I can have all of the code from

somebody else's GitHub right in my vs

code as if I wrote the code myself so

this is why every single time on all of

our gab repos we usually see some

installation tips like this we also have

tips like how to actually quick start

how to get going yada y yada etc etc now

let me CD out of this let's go back to

the mock buy me a coffee Cipher updraft

something I didn't show you is if I do

get log again right this is what our

first commit looks like if I do a little

um if I let's let's make a very small

change in here let's go to the read me

let's just do like hello hello and then

save it now if I go get status I can see


that has been changed if I do get add

period and then another get status I can

see it's staged for commit I can then do

get commit minus M update

enter and then I can do get push to push

it back up to my GitHub and then if I do

a little refresh o not not on this one

on this one if I do a refresh I can now

see there are two commits and if I click

this we can see this little update thing

here now there might be a couple errors

you run into doing this and be sure to

work with your AI to get past and solve

them so you can work with GitHub and

once again if you're excited about this

what you should be scroll up or scroll

down hit this tweet me button and tweet

about it say hello to the community

because like I said if you want to get

hired engaging with the community is a

great way to get

started which leads us to the final

Workshop of this section of this

Flagship project that you have just

finished and you've learned a ton we've

learned about storage we've learned

about different types of testing we've

done a couple of workshops we' pushed up

to GitHub now it's time for Workshop

number two number one write enough tests


to get your code to 100% code coverage

remember we tested that out with MOX

test-- coverage like this we could see

on our where is it on our buy me a

coffee we're currently at

93 how do you get the last 7% or or 99%

is fine number two sign up for cyphon

profiles like I said getting these

profiles up this is how you're going to

build your career your job career in web

3 doing these projects signing up for

cphon profiles which is going to have

even more information about

opportunities and where to start earning

rewards start becoming an auditor jobs

Etc push your code to GitHub if you

haven't done this I'm telling you this

is a crucial piece of your Learning

Journey and then finally add a new

commit up to your GitHub repo try this

out yourself really really get hands on

with this

as always spend at most 25 minutes on

these without the aid of AI and then if

you're unable to solve them start

working with an AI asking AI questions

and I guess I'll see you in 25

minutes all right welcome back did you

do the workshops if you didn't go back


and do the Workshops the workshops are

so important for your Learning Journey

repetition is the mother of skill and we

want to make you skillful so go back do

the workshops if you have not sign up

for siphon profiles push your code up to

GitHub do all of

this now before we jump off here you

should be incredibly proud of yourself

for getting this far oh my goodness

everything we're going through is

difficult there is a ton I'm throwing at

you and you are absorbing it you are

doing a great job it might be a little

overwhelming at the moment and that's

okay that's okay be sure to use the

quizzes be sure to do the workshops work

with your AIS Etc as always let's do a

quick recap of everything we learned in

this section before you should take a

break so first off we learned a nicer

way to format our codebase we ended up

splitting our codebase up into a couple

of different files we have buy me a

coffee get price module and then we also

have a new interface we learned about

finally why constants and immutables are

different in prices especially because

we learned about storage versus

constants versus immutables what goes in


storage what doesn't go in storage how

that storage layout works we we even saw

with mock test-- gas profile we even saw

with a gas profile that yeah uh there is

a gas difference when it comes to those

different terms we learned about using

mocks to test our contracts on PM we

also we learned some more advanced

deploy scripts using moccasins manifest

named that was smart enough to say okay

cool you don't have this contract I'm

going to deploy it or oh cool it's in

the database I'm going to go get it or

cool you've given me an address we're

just going to use that it's kind of this

magical function we learned that if we

want to we can actually keep track of

all of our deployments and all of the

rpcs the deployers transaction has all

this information about the transactions

we actually send so that we have them

locally and we can work with our

deployment database to know what we're

deploying and where things are going

we've written some of the best tests

we've ever written in this whole course

so far we've written some better conf

tests we have some session scope

fixtures some function scope fixtures we


learned about different types of tests

and we wrote mainly unit tests here we

also learned that we could run four

tests with a simple MOX test-- Network

sapoia D- Fork we learn that this will

not actually send any real money because

it's on a forked Network and this is

really really important for working with

before deploying our smart contracts the

fork tests are a type of staging tests

but we also learned about how to write

staging tests that actually run on an

actual Network here we learned that we

could use manifest named to pull

information out of the database or we

could call get latest deployed or get

latest contract checked or unchecked as

well to run scripts to interact with

contracts that we've already deployed

and then finally we we pushed everything

up to GitHub to actually start building

our portfolios building our history of

becoming a smart cont developer also a

lot of the times whenever I make

something in the future in 6 months I

forget how to do that thing and I will

literally go back look through my GitHub

repositories look at code that I wrote

in the past and say ah okay that's how I

did it before and since I have it all on


GitHub I have a quick and easy place to

reference how I learned something or

where I learned something so at this

point in this section you should be

incredibly incredibly proud of yourself

the reason this section is starred is

because this is what I call one of the

flagship projects of cyphon updraft

seeing a developer understand every

piece of the code that we went through

here is very telling it's very promising

that they'll actually know what going on

if put in a production environment and

they actually have some deep

understanding of the smart contract

development world so this is the

flagship project now we have a couple

more sections to go through in this

course and then as well we've got a lot

more in advanced moccasin coming down

the line now is a great time as always

to take a break go get some ice cream go

for a walk lift some iron at the gym

because you earned it we went through a

lot in this section so get some ice

cream go for a walk and I'll see you

very

soon welcome back so this one is going

to be a little bit different so what


we're going to be doing if you're on the

GitHub repo associated with this course

and scroll all the way down to this next

section html/javascript

moccasin running anvil in the background

so if you want to go ahead and follow

along with me here you can whenever I

say hey run this with Foundry deploy

this with Foundry just know that I mean

with moccasin and we have some

instructions in here on how to get

started here with moccasin instead of

with Foundry now also you do not have to

follow along with me here you can just

watch and learn because it is really

important that you understand okay what

is actually happening when my mamas pops

up and says hey confirm this transaction

because if you confirm the wrong

transaction that's actually really scary

okay so we want to learn how interacting

with websites work what it looks like

and if you have no intention of ever

being a front-end developer which is

totally fine if you're like hey screw

this I just want to be a python dev then

great you don't need to follow along

here at all but if you would like to the

instructions in here from moxas are here

as well and additionally The Foundry


version of this project is just called

fundme for the Mox Edition I thought it

would be way nicer and more advanced if

we call it buy me a coffee so whenever

whenever I refer to fundme just know

that I'm referring to the same buy me a

coffee contract okay so we're going to

go ahead we're going to go through the

we're going to go through with this

section I'm going to you know uh this is

a slightly older video I'm going to be

showing you how to do a lot of stuff

using Foundry but again you can just as

easily use moccasin for this as well so

let's go ahead let's learn how websites

actually work work and how our wallets

interact with these websites so here we

go welcome back so this one is going to

be a little bit different so what we're

going to be doing if you're on the

GitHub repo associated with this course

and scroll all the way down to this next

section HTML /jf buy me a coffee you can

find all the code for this in here

now this is going to be a little bit

different because because what we're

going to be teaching you here is how

your wallets and how your metamask

actually interact with websites and if


you scroll down in here this front-end

code that I've I've written here is

actually going to work great for both

Foundry and for moccasin running anvil

in the background so if you want to go

ahead and follow along with me here you

can whenever I say hey run this with

Foundry deploy this with Foundry just

know that I mean with moccasin and we

have some instructions in here on how to

get started here with moccasin instead

of with Foundry now also you do not have

to follow along with me here you can

just watch and learn because it is

really important that you understand

okay what is actually happening when my

mamass pops up and says hey confirm this

transaction because if you confirm the

wrong transaction that's actually really

scary okay so we want to learn how

interacting with websites work what it

looks like and if you have no intention

of ever being a front-end developer

which is totally fine if you're like hey

screw this I just want to be a python

dev then great you don't need to follow

along here at all but if you would like

to the instructions in here from moxin

are here as well and additionally The

Foundry version of this project is just


called fundme for the moxin Edition I

thought it would be way nicer and more

advanced if we call it it buy me a

coffee so whenever whenever I refer to

fundme just know that I'm referring to

the same buy me a coffee contract okay

so we're going to go ahead we're going

to go through the we're going to go

through with this section I'm going to

you know uh this is a slightly older

video I'm going to be showing you how to

do a lot of stuff using Foundry but

again you can just as easily use

moccasin for this as well so let's go

ahead let's learn how websites actually

work and how our wallets interact with

these websites so here we go

all right welcome back now I know a lot

of you are excited because we're finally

going to start talking about tokens

blockchain tokens or blockchain

cryptocurrencies there's a whole lot of

different names for these of course and

we're going to scroll down to the get a

repo associated with this course it's

got a little bit of an upgrade we're

going to go we're going to scroll down

here we're in Moccasin fundamentals

we're now going to go to moccasin erc2


we originally had this as a raffle or a

smart contract Lottery but you'll see

that return in the next section how to

get hired in this section about erc20 is

this is going to be the last coding

section of the moccasin fundamentals

before we move on to the advanced

moccasin section where we're going to go

much deeper we're going to learn about

nfts we're going to learn about defi

we're going to build an actual stable

coin we're going to do signatures

upgrades all this good stuff down there

but before we get to all that we're

going to finally learn about about

tokens which you've probably heard of if

you're here we're going to learn what

they actually are and we're going to

learn a ton of other stuff as well so

the full code for this section of course

is right here and I have it available

locally and we're going to do a quick

walk through of all the phenomenal

things that we're going to be learning

here cuz we're not just going to learn

about tokens you can actually very

easily deploy your own token you can

very easily create and deploy your own

token you actually don't even need to

take this course to deploy your own


token there's a ton of codefree products

out there that will say hey here's how

you deploy your own token but if you

want to understand how to customize your

own token and build some of the most

advanced some of the coolest tokens out

there this is what you're going to need

to follow through and additionally in

doing this section we're going to learn

a ton of advanced python tooling as well

so let's do a quick walkr of what we're

going to learn here so the first thing

that we're going to be looking at is

this is our project here and you'll see

that there's actually a contracts folder

as opposed to a source folder and you'll

also notice that there is no moccasin

DOL well guess what if you want to you

can add all of your configurations to

your P project. if you like so for

example this tool. mo. project has the

information in here I'm getting too

ahead of myself yes we're going to learn

more about customization we are going to

build our own contract we are going to

build our own contract that has an erc20

token we are going to learn about tokens

how to deploy tokens what what they look

like additionally we're going to be


learning about importing other libraries

one of the most important libraries that

you're going to work with in Viper is

this thing called snackmate or snake

mate you know I actually not sure how to

pronounce it but we're going to learn

about snackmate this is going to allow

us to not have to build everything from

scratch every time we build a project

it's got a ton of Viper contracts in it

already including access control

functions extensions of popular ercs and

eips which is something we're going to

learn about governance tokens utilities

and so much more we're going to build

our own custom erc20 or our own custom

token and additionally we're going to

kind of intentionally put a bug in this

that might seem kind of benign but some

of our more advanced tests are going to

catch we're going to learn about this

concept of stateless and stateful

fuzzing and this is going to be this is

going to be a brief introduction to

stateless and stateful fuzzing but we're

going to write stateful and stateless

fuzzers which are more advanced more

important types of tests that have a

higher chance of catching bugs

additionally we're going to write a


couple of basic unit tests we're going

to have a fantastic conf test as well

but it's these stateless and stateful

fuzzers that we're really going to focus

on we're going to learn a little bit

more about working with our scripts

we're going to of course we're going to

be working with something called the

moccasin console we're going to learn

how to format our contracts better and a

way to automatically format them so they

look very professional we're going to

learn about this this weird thing called

events that we have here what is an

event how do events work we're going to

learn a little bit about random numbers

checks effects interactions and so much

more as of recording this is the final

coding project before we go through the

how to get hired where I'm going to set

you off on a very long very important

Workshop that's really going to the

skills on this how to get hired so let's

go ahead and now if you run this

codebase as is if you do a little mock

test you'll actually get an error and

this is intentional we want this error

and we see this weird long falsifying

example like what is going on here


you'll understand this in a minute but

additionally we can also just do MOX run

deploy and we'll see deployed snack

token at this address and this is how

we're going to deploy our erc20 AKA R

token so we are going to learn a ton in

this lesson let's go ahead let's jump in

and let's get started

all right so here I am back in my MOX CU

folder with a PWD I'm currently in that

folder we're going to create a new

directory called MOX erc20 CU for Cypher

updraft or whatever you want to call it

I'm going to do a little code MOX erc20

CU or you can do a file open folder and

open that folder so we open a new window

for our brand new project and now that

you know a little bit about GitHub I

highly highly highly recommend that you

add this to GitHub as well so that once

again you can show off all your projects

and especially with the fuzzing skills

we're going to learn in this section

fuzzing is one of the most advanced

testing techniques out there and yet I

still see maybe like 60% of smart

contract developers not use them and yet

they're one of the most important tools

that security researchers and the top

level professional smart contract


developers use so I'm going to be

teaching you the skill that still to

this day and it makes me my hair out a

lot of smart contract developers don't

use we are going to turn you into a

fuzzer but I digress now like I said

we're going to be doing a lot of

advanced stuff in this section and

especially with the fuzzing it might not

all syn right away but I want to tell

you that is 100% okay if it doesn't sync

in right away I want you to do your best

to follow along and as we code more and

more as you do more and more of these

projects what do I always say repetition

is the mother of skill and we want to

make you incredibly skillful so let's go

ahead let's get started and we create a

new project here so I'm going to do a

little MOX init --vs code dpy project

like this to get started with my project

here now we're given some test SRC

everything like that and of course we're

given our moccasin DOL with a whole

bunch of boilerplate code added in

here now right here is already where

we're going to do some new learnings so

moccasin is completely customizable as

of right now we have in this project


section we're saying our SRC our source

folder or a folder where our smart

contracts are is going to be called SRC

but we can actually call this whatever

we want and if I run a little MOX

compile we'll see it says compiling one

contracts to the to the out folder and

it knows there's one contract because

there's exactly one contract in SRC now

if I were to rename this to contracts

like this clear my terminal hit up a

couple times to do MOX compile it says

compiling zero contracts to out because

it says hey uh you don't even have an

SRC folder so you don't have any

contracts so I'm not going to compile

anything we can actually customize this

and change this to contracts like this

and I'll run MOX compile again and now

it goes oh okay well why didn't you say

so the contracts folder is where your

contracts are going to be I'm going to

look in the contracts folder so there's

a whole lot of customization this that

you can do again if you scroll to the

bottom of the dummy repo that you're

given you can command click or copy

paste that link into your browser and

you can get linked to a list of all the

different customizations that you can


make in this moccasin DOL now we're

going to go even a step further I am

going to say hey uh you can just go

ahead and delete that whole folder if

you don't want it the M.L is actually

kind of a an optional file that you

don't even have to have a lot of python

products do a lot of their tooling right

in the p project. tomomo and a lot of

products prefer this because then you

can just have one single configuration

file for everything that you need to

work with so in here now that we've

deleted the file if we run MOX compile

again it'll default to the SRC folder

which knows none exists so it just will

return nothing but if we look in the P

projecto we can add

tool. moccasin do project and we can say

SRC equals contracts exactly as if we

were doing project in our M.O so tool.

moon. project SRC equals contracts MOX

compile and now once again we see

compiling one contract two out so we can

additionally just put everything in our

P project. toml if we so choose so let's

go ahead let's do that for the rest of

this section

here okay great so now we have this


setup let's go ahead let's get started

creating our first token we're going to

go into contracts create new folder type

snck token. VI and this is where we're

going to create our token oh and you

know what let's also get rid of this

this this and this going to delete those

so I can start oh not rename this this

this and this let's go ahead and right

click delete so we can start from a

brand new project so we want to build a

token now before we build a token we

should probably learn about what one is

and to learn about what a token is we

need to learn about ERC 20s eips erc's

and how these token standards come about

so what we're going to watch is an

excerpt from our solidity curriculum but

all the high level concepts are still

the same all about what are these tokens

actually and how do they work so let's

go ahead and take a look we'll even get

to watch a Patrick from a few years ago

and he looks like a

baby before we can understand what an

erc20 is or even what one of these

tokens are we first need to understand

what is an ERC and then also what is an

EIP in ethereum and Avalanche and

binance and polygon all these


blockchains have what's called

Improvement proposals and for ethereum

they're called ethereum Improvement

proposals or eips and what people do is

they come up with these ideas to improve

ethereum or improve these layer ones

like polygon madic Avalanche Etc and on

some GitHub or some open source

repository they'll add these new eips

they'll add these new Improvement ideas

to make these protocols better now these

improvements can really be anything they

can be anything from a core blockchain

update to some standard that is going to

be a best practice for the entire

Community to adopt once an EIP gets

enough Insight they also create an ERC

which stands for ethereum request for

comments so EIP ethereum Improvement

proposals ERC ethereum request for

comments and again these can be like be

PE EP you know etc for all these

different blockchains both the

Improvement proposals and the requests

for comments all have these different

tags now they're numbered

chronologically so something like an ERC

20 is going to be the 20th ERC EIP the

erc's and the eips share that same


number and there are websites like eips

doeum org they keep track of all these

new ethereum Improvement proposals and

you can actually see them real time go

through the process of being adopted by

the community now one of these eips or

erc's is going to be the erc2 or the

token standard for smart contracts this

is an improvement proposal that talks

about how to actually create tokens and

create these smart contract tokens I

made a video about this recently so in

the GitHub repo associated with this

course we're going to have a subl lesson

and we're going to watch a quick video

that explains more about these different

tokens now first let's define even what

are ER c20s so er c20s are tokens that

are deployed on a chain using What's

called the erc20 token standard you can

read more about it in the erc20 token

standard here Link in the description as

well but basically it's a smart contract

that actually represents a token so it's

token but it's a smart contract it's

both it's really cool tether chain link

uni token and die are all examples of

ERC 20s technically chain link is an ERC

677 as there are upgrades to the erc20

that some tokens take that are still


backwards compatible with ear c20s and

so basically you can think of them as ER

c20s with a little additional

functionality now why would I even care

to want to make an erc20 well you can do

a lot of really cool stuff with it you

can make a governance token you can

secure an underlying Network you can

create some type of synthetic asset or

really anything else in any case how do

we build one of these ER c20s how do we

build one of these tokens well all we

have to do is build a smart contract

that follows the token standard all we

have to do is build a smart contract

that has these functions it has a name

function a symbol function decimals

function Etc all these functions we need

to be able to transfer it we need to be

able to get the balance of it Etc and

again if you want to check out some of

the improvements that are still erc20

compatible like the ERC 677 or the ERC

777 you definitely go check those out

and build one of those

instead all right great so now that we

know a little bit more about ear C's and

eips let's go ahead and let's start

building our own token so we would look


up EIP 20 or erc2 and let's go to the

actual let's go to the actual EIP site

eips

ec20 ec20 token standard okay e.

ethereum.org list looks great and let's

go in here and let's go through all the

different methods and add them to our

contract so this is for solidity so

let's take this and let's do this in

Viper so I'm going to do a little defa

name what do this return returns a

string okay so we're going to say say

returns a string let's just give it a

size of 100 and okay let's just say

return my

token okay great we have the name let's

keep going okay symbol okay so we're

going to do defa symbol okay this

returns a string let's just give it like

10 characters and we'll say return

myt okay what's next okay some deal oh

my gosh there's so many functions I have

to implement oh my goodness so no I'm

not going to make you implement all of

these functions although it might be a

good exercise for you to build your own

token from scratch however we're not

going to do this as you probably know

people have probably already written

Viper tokens before or Viper simple


tokens before so what we could more

easily do is we could look up like curve

token GitHub on Google or something um

stable coin Devi so we could probably

just copy paste oh thanks curve copy

paste curve stable coin and run with

that but we're not going to do

that this is where the concept of

libraries come into play now we've

actually used libraries with python

before right we've written a ton of

different scripts where we do like you

know or we've done like from moccasin

you know import whatever or from Boa

import whatever we've already worked

with libraries for python well you can

also work with libraries for for Viper

so what we can do and this is going to

be one of the most important repos for

your viper coding journey is we're going

to import and install this snackmate or

snake mate I I I don't know how to

pronounce it snake mate or snake make

package now in this GitHub repo there's

tons of boiler plate or default code

that we can use in our project ourselves

for example there's access controls

there's extensions to eips in different

erc's there's some governance utilities


which if you're working with a dow or

decentralized organization you can work

with there's different token standards

as well different utilities there's a

whole bunch of phenomenal things in here

you can kind of think of this as the

standard library for Viper a group of

contracts that a lot of people use and a

lot of people know how to use and we're

probably going to be using snake mate in

a lot of our projects so if we're on

this GitHub repo what we can do is we

can look in the SRC snackmate folder and

we can look in the tokens folder and we

can see aha there's an

erc20 Dov in here and this whole

contract is built in a way for us to be

able to import it and install it in our

own local projects to make it really

easy for us to create our own minimal

contracts now we could 100% copy paste

the code from in here but I'm going to

tell you right now not to do that for a

number of reasons and probably the most

important reason is that we're going to

do it a much easier way and a much more

flexible way for us working with our

projects so we're going to learn how so

we so yeah we could 100% you know do a

little copy paste it in here here but


what we're going to do instead is we're

going to work with the moccasin

dependencies functionality now moccasin

allows you to install projects either

directly from GitHub or install python

projects so you know how like moccasin

pii for example if we go to moccasin so

moccasin is in the pii repository and

this is how you know when we ran UV tool

install moccasin right you know how we

we install moccasin with that well when

we ran this command it reached out to

pii to download moccasin so snackmate

not only is a get up repo but it also is

available on pii so if I look up snck

mate in here I can see snck mate is also

on pii so we can install this with Pip

install or UV ad or we could also

install it directly with moccasin so we

can install it as a python package as a

normal pit package or we can install it

directly from GitHub and I'm going to

show you both versions here let's start

with in installing directly from GitHub

to install directly from GitHub you

would just do MOX install and then the

org SL repo so for example MOX

install uh pcast ver I don't know how to

say that SL snackmate so I'm actually


going to copy this go back to my GitHub

I'll do MOX

install paste this oh I got to do a

couple Backspaces so that it actually

works hit enter going to say running

install command installing one GitHub

packages using latest version and then

it says it's installed so if you don't

add a version right so in the

documentation it says these little

brackets in documentation mean this is

optional if you don't add a version

it'll automatically try to get the

latest version but we could also do at

0.1.0 like this and it'll go ahead and

install it and you'll see a couple of

things happen number one in your P

project. toml you'll see this new

dependencies section this is saying hey

this moccasin project depends on

snackmate being installed and then

Additionally you might ask oh where did

that get installed to well if you look

in the lib folder in the GitHub folder

there's now some new stuff in here we

basically just cloned and downloaded

that whole GitHub repo and so now it's

all available in here for us to work

with so if we wanted to work with snit

now in our file here there's actually


some more good documentation we can run

a command like this so we'd say from

that what is the name from uh that

org. snackmate so lib GitHub we could

also do actually li. GitHub dot but mock

isn't smart enough to just let you do

this from this place/ snackmate what's

the next folder SRC dot what's the next

folder snck mate. off uh ownable import

ownable so this is how we can import

this ownable VI contract into our token

here and then of course we can do the

and then of course we see okay let's

let's look at ownable this ownable Dovan

does it have any storage okay that looks

like a storage variable so we would do

initializes ownable oops I have to

actually import it here initializes

ownable and we'll get this little error

hey you need to add ownable do anit we

might do like def oops or at deploy def

uncore uncore init

uncore uh ownable doore init uncore now

you can also rename your Imports so we

could say import ownable as Al and then

we could say initialize as Al and then.

anit so if you have some big names in

here you can rename them to be a little

bit easier to work with great so that's


how we install and work with GitHub now

you might be seeing this kind of super

long name here and you might be going GH

Patrick that's kind of gross

well that's just the way it is if you're

working with

GitHub we can also work with projects as

pii now not every GitHub repo will have

deployed their code to pii so you want

to make sure you know if a project works

on pii or if you just need to install

directly from GitHub so if we want to

install from pii with moccasin and snake

mate is available on pii instead what we

would do and I'm going to show you the

wrong way to do it first we would just

do MOX install snackmate and we're

actually going to get this error here

which I should make the logging on this

a little bit easier we're going to get

this error because oh actually the error

is at the top of here no virtual

environment found run UV vnb you run UV

venv to create an environment or pass

system to install to a non- virtual

environment as of today you need to be

in a virtual environment in order to

install like this I'm not sure if this

is a feature or a bug at the moment I

guess I'll decide a later date so we can


create a virtual environment with UV

venv like this my vs code is going to

pop up I'm going to go ahead and say yes

this way if I'm on a python file let's

go to a python file down in the bottom

right we're now in the venv bin python

area which is good let's go ahead let's

activate this virtual environment as

well and now we're in a virtual

environment so let's clear let's rerun

let's run MOX install snackmate and now

it'll install snake mate two now it'll

install snake mate although it actually

doesn't even install it to the virtual

environment it installs it to this lib

folder

IPI snake mate so now we have snackmate

installed in this pii folder you could

actually also just do UV add snackmate

and then not to mockas and AD but now

we're kind of getting into a lot of The

Oddities of working with python

dependency management and different

versions of python but again if we look

in the P product. tumml now we see

there's two dependencies there's pcass I

I don't know how to say this SL snake

mate and then snake mate this is saying

our project here depends on this GitHub


repo and this python repo here now we

don't need both of these and I'm going

to say I prefer doing it like this so

I'm going to go ahead I'm going to add

it here and the reason that this

dependencies thing is cool is if I go

ahead let me just delete the entire lib

folder so I don't have snck mate

installed anymore right if I pull up my

terminal I can do UV pip

freeze pipe it into GP snck mate which

uh this command basically gets all of

your python packages and then this GP

snake mate looks for them it says oh

yeah there's no snackmate anywhere in

our virtual environment we also don't

have it in our our lib folder and if I

were to try to run MOX compile right now

we would get an error because it's

saying hey uh what what is this I I

don't see that anywhere if I just run

MOX install moccasin will look inside

our dependencies folders and grab and

automatically install whatever is in

here so I can just run MOX install and

it'll now install snck mate updated

package snck mate and now the lib

folders populated with pii with

snackmate back in it so this

dependencies folder allows us to very


easily send other people's projects if I

if I build a really cool project and I

have 100 dependencies all I have to do

is add to this dependencies folder and

somebody else just has to do MOX install

and it'll automatically install all the

dependencies whether it's GitHub Pipi

whatever you want so a lot of cool

dependency stuff that we can do here and

we're really just kind of scratching the

surface but now that I've installed it

if I go back to the p. tml now that I've

installed it as a python dependency what

I can do here is I don't have to do kind

of this crazy link here anymore I could

do you know the direct link still I

could do li. Pipi dockmate do okay

what's after snackmate

Doo uh do whatever but when you install

with a pi uh but when you install with a

pii or a python package you can just

directly access that python package so I

can just say from snackmate off import

ownable as Al

now I'm getting this little squiggly

line because in my vs code we have this

line here saying Viper DP lib GitHub lib

Pipi it's looking for this lib GitHub

folder which doesn't exist so let's


actually go ahead let's create that

GitHub folder GitHub and we hit save and

now it's happy again so now we can

actually talk about what this file is

doing if I get rid of this line here

Boop good goodbye and I save this file

we get a red line BS code is saying hey

uh no such module is found in settings.

Json this is the Viper command that we

can run for Viper to recognize this lib

folder as an actual folder to find

dependencies without this line our VSS

code tries to format and syntax

highlight everything and goes I don't I

don't know where these are from I I

don't know what these are for moccasin

knows automatically but vs code not so

much so if we uncomment this line we

save we save this file again the red

line goes away because vs code goes ah

okay now I know where you're getting

this SNM thing from that's in the lib

pyi folder got it I understand so if we

got rid of this for example got rid of

it save go back here save Red Line comes

back up so we'll add it back in save

come back here save boom

nice okay so Okay so we've installed

snck mate now we can actually start

creating our token here let's actually


give this a version because we haven't

done that we'll do pragma version

0.4.0 we'll do our little triple

comments here we'll say at licens MIT at

title Snick token or whatever you want

to call it at author this will be you

and then at notice this is my erc20

token like so great just to make sure

we're doing things right we'll do a

little MOX compile stuff is looking good

okay what's next so we can go ahead like

we've been saying and we can finally

actually just import the token contract

to have a base token contract for us and

then just tweak it so if we go to our

lib pii or GitHub if you decide to work

with GitHub snck tokens erc20 Dov we can

see all this code in here for working

with an erc20 we have a bunch of stuff

at the top which we might see and go I

don't really know what this does but

okay cool we scroll down okay we have

some exports in here cool we have this

weird permit hash thing ah okay we have

some variables like name symbol decimals

balance of allowance all this stuff okay

we have an init function ah we have a

transfer function I recognize this this

transfer function is right in the erc20


implementation where is that okay

there's a function transfer cool it's

got the function transfer ah it's got an

approved function in here okay let's

look for uh function function approve ah

okay that's in here looks like this has

all of the functions that we want to be

a part of our token so let's go ahead

let's import this and use the modules

feature of Viper to work with with this

so let's go ahead and import it so we'll

do from snck mate. tokens import erc20

like this let's go ahead let's see if

this erc20 does it have any state

erc20 let's scroll up uh okay that's a

storage variable that's a storage

variable okay great so we're going to

have to do

initializes e

erc20 okay cool I'm getting red squiggly

that means it has a a deploy or an init

function let's look for that okay great

it does have an init function so we're

going to have to call this nit function

and it's got a lot of parameters so

we're going to have to add these

parameters in as well so we'll do. init

let's do this as the order we'll do.

init and we'll do erc20 doore anitore

uncore and let's see what are the


variables in here okay so first we have

a name let's let's give ours a name but

let's not do a magic number or a magic

name let's do a little name of type

constant

string and how many characters are in

here okay 25 we'll say string of

25 equals call it snck token like this

so the name will be name what's next the

symbol okay let's do that as well we'll

do a symbol which will be a constant

string five and the symbol we'll say is

snck great we'll do a symbol next then

we have

decimals decimals so decimals is going

to be how many zeros are associated with

your token most of the time thank you

chat gbt it's going to be 18 kind of the

exact same format as wey or with

ethereum there's some weirdo tokens out

there like like if we look up usdc on

ethereum we go to here go to contract

read contract excuse me read us proxy

you'll learn about proxies much later

we'll scroll down to decimals it'll say

six so usdc is like super bizarre and

that it only has six decimals and I hate

it and most of the security Community

hates it but I digress um if you're


going to launch a token I recommend you

do 18 and not be a weirdo like usdc so

um what else do we need okay EIP 712 so

we're going to learn about EIP 712 much

much later in the signatures section of

ciper updraft so for now just kind of

follow along with me here just do EIP 72

version constant U into 256 equals 1

just do this for now you'll learn this

is kind of a really Advanced concept

we'll learn that much later and then the

last last thing that we need is what uh

excuse me we needed the name and then

the version uh so both of these are kind

of a more advanced concept so just for

now just do as I do and you'll learn

later so name we're just going to say

his name name and then e712 version

great so now we have the init function

for erc20 oh we're still getting a

little error here ah erc20 uses ownable

but is not initialized with ownable so

in the erc20 Dov if I look in here here

let me scroll down this is going to

actually use ownable and if we look in

here where does it use it if we scroll

down in here we see ah uses ownable so

whenever you see this uses ownable in a

dependency we need to literally do what

this error kind of says erc20 uses zable


but is not initialized with ownable so

we need to tell Viper how this erc20

should initialize ownable and we can

just do it by saying ownable walrus

equals ow so this is basically us

telling hey erc20 contract use the exact

same ownable that we've imported here if

that's a little confusing for now just

anytime you see somebody uses that uses

thing just do the syntax and you'll be a

okay so nice this is looking pretty good

let's pull up our terminal let's do a

little MOX compile see what this looks

like oh we're getting an error given

type has reference U 256 expected uint 8

that's right this is actually a uent 8

not a uent 256 let's clear the terminal

run it again get another errror given

reference as type un 256 expected string

20 uh what line oh EIP 712 version so

this is this little line here is this

little error code here is saying it's

this line and it's this variable that's

screwed up so this should be a string oh

did I do it backwards is it name version

what's what's the it is name version and

the oh the name is a string 50 and the

version is a string 20 H okay so excuse

me this should be a string 20 and that


means this needs to be a string and

we'll save we'll clear we'll compile and

it looks good outstanding so now just

with this you almost have a complete

erc20 token let me prompt you what are

we missing what do you think we're

missing here to although to be fair

we're missing a couple things but I want

you to pause the video and ask yourself

what is the most important thing that

we're missing here and I'll even let you

cheat I'll even give you a hint look in

your out folder and look at Snak token.

Json is there something in here that

stands out to you that isn't in here go

ahead take a minute and let me know all

right welcome back did you actually

pause I hope you did because knowledge

is the residue of thinking and the more

you think about subjects the more memory

and knowledge you will acquire so if you

go through this ABI section here which

again which again is the application

binary interface which has all of the

functions to work with this contract

there are zero erc20 functions in here

whoopsies so what we have to do we have

to export those functions do not forget

to export your functions so right at the

top here I'm going to do exports I'm


going to do two types of exports I'm

going to say ERC 20 doore interface

uncore and if we look at the erc20 Dov

let's see does this export anything

exports aha it exports ownable do owner

can we export ownable. interface let's

try it

_ interface uncore save try to compile

we actually get an error here remember

transfer ownership already exists in so

we cannot export ownable because in the

ec20 we have transfer ownership in this

contract already so we would have to

specify the exact functions in here the

exact functions are notable we'd want to

use for example we could do _ or.

renounce

ownership like this but I don't really

want to add that so we're not going to

add that so since it's only a oneliner

let's just go ahead and put it on one

line here now the question

uh now how many tokens does this get

deployed with well let's go ahead let's

go to the

erc20 contract that comes with snate

snate or however you say it and let's

see if there's an initial Supply let's

look for a mint function a def mint so


it looks like there's a mint function

that comes automatically with our erc20

snck token and it's minting is how we're

going to create different tokens when we

deploy our contract it starts out with

zero tokens are minted initially often

times right in our deploy function we

might want to give an initial Supply so

we'll do like

initial Supply Type U into 256 and then

we'll do

erc20 doore mint because there's thisor

mint function it does a whole bunch of

really cool stuff if you want to see

what they do feel free to go ahead and

pause the video and check them out and

we usually will mint them to the

message. sender the whole

initial Supply now this might be a bad

idea depending on how you want your

token to actually be like giving

yourself the original initial Supply can

be kind of gross but it's up to

you so this actually looks great to us

now there is one other thing that I want

to show you before we go on to scripting

and and some more p Pyon if you go back

to the

erc20 from snet you scroll down past

this giant comment you'll see something


like this from ethereum erc's import I

erc20 now Viper actually if you read the

notes Here We import and implement the

ic20 interface which is a built-in

interface of the Viper compiler so Viper

has a ton of interfaces that come

builtin and a lot of the built-in

interfaces are going to be common token

standards like ic20 erc20 detailed

permit some other more advanced type of

and it might be good to and this is kind

of a newer keyword that we haven't

worked with yet implements what this

does is it makes it so that our contract

does not compile unless it adds all the

functions of an interface this might be

really helpful if for example you know

maybe you make like my interface.

byi and you want to kind of scaffold out

what your contract looks like and you

want to make sure to not forget any

functions if you make a Viper interface

like that this can be a really helpful

architecturing tool to make sure your

codebase is solid so Viper automatically

comes with this ic20 which will and the

erc20 Dov because it has this line it

will make sure that this erc20 VV cannot

compile unless it adds all the functions


of an erc20 here we can also add them in

our contract as well so we could say

from

ethereum erc's import I

erc20 and then we could do right below

it implements

ic20 and if we go ahead and try to

compile this it'll compile successfully

little MOX compile because our

erc20 is exporting our erc20 has its

functions being exported and therefore

it knows that those functions are indeed

implemented for us great so now let's go

ahead let's write some scripts and we'll

come back to this in a little bit to

learn a little bit more but let's go

ahead let's write a deploy script so

that we can actually deploy our first

token so as you know let's do a little

def moccas main like this and we'll do a

return deploy deploy which we'll go

ahead and Define up here def deploy oops

def deploy let's do a little we'll pass

for now and we'll say from contracts

instead of from SRC right because the

name of our contracts folder is now

contracts import snck token what does

our snck token need in it's a nit

function it just needs an initial Supply

so let's do from eth utils import to way


because remember our token has 18

decimals the exact same as way and we'll

say initial

Supply equals to way let's just do 1,000

1,000 ether this line will give 18

decimal places to 1,000 we might get a

little Squiggy line that it could not be

resolved this comes with moccasin so we

can ignore that or if it bothers you you

can do UV add moccasin like this and

then it should go away as well so we

have the initial Supply then we can just

do is say snck contract equals snck

token. deploy

initial Supply initial Supply like this

and then we can just do a little print

Line Print F

deployed

deployed to and then snck contract

contract. address like this we'll pull

up our terminal we'll little we'll do a

little MOX run deploy and will'll get

this output now I haven't shown you this

but we could also do MOX

runscript SL deoy dopy and that does the

exact same thing so both of those

actually work with

moccasin so now we've deployed this what

we would want to do next is obviously


write a couple of tests now I'm not

going to beat you down writing tests

here but I am going to tell you that

this is a great time for a little

workshop but let's go to test

we'll create a new file we'll do test

token. piy and I'm not creating the

utils I'm not created the unit

integration you know staging test files

folders here because if you want to go

to the extra mile and in the workshop

you want to flush those out you can

absolutely do so but I'm just going to

show you a single test here because for

the workshop you're going to have to

write more tests here so we're going to

just create one test we're going to do

from script. deploy import deploy little

defa test token Supply and then we'll do

um first snck token equals deploy we

have to make sure this actually returns

aha returns a Viper contract we'll do

from moccasin booat tools import Viper

contract we need to have this return

snck contract let's have this also

return of let's give this the type hint

to return a Viper contract as well SN

token equals deploy already some alarm

Bells should be going off in your head

you should probably be thinking huh this


would work great as a fixture but I'll

leave it up to you um so now we want to

do a little assert assert snck token.

total

Supply and remember this function is

being exported from our erc20 VV this

should equal uh the initial Supply in

our deploy script so let's grab this as

well so from script. deploy import

deploy and initial Supply assert snck

token. total Supply equals initial

Supply pull up our terminal run a little

MOX test and we only have one test and

it passes here nice all right

great now in our

erc20 Dov we have this thing that you

keep seeing called logs and we actually

haven't done a whole lot of talking

about them because as smart contract

developers they don't really come into

play into until much later but you'll

notice pretty much anytime our erc20

here is updating storage they're also

emitting a log now events are this

additional data structure inside the evm

that you can write data to Smart

contracts can write data to this area

but they cannot read data and for a

while you might not understand why you


need them and that's okay they're mainly

needed for indexers which are these

offchain applications that help create

websites and applications so if you're a

smart contract developer you care about

them less but if you're a website

developer you care about them a lot but

the other thing that they're needed for

is for migrations or social migrations

or social upgrades if you have to

redeploy your smart contract for some

reason having a log of these events M

can make updating storage for that newly

deployed contract much easier and again

these are two more advanced things that

you'll learn about later in advanced

moccasin so for now I am just going to

tell you that anytime you update your

state anytime you update storage you

should also emit one of these logs now

we are going to write a quick test to

test for these logs but before we write

a test let's go ahead let's watch this

video which will explain more about what

logs do and what they're for now this is

from an older section and this is using

solidity examples but all the same

examples apply to Viper as well so let

let's go ahead let's take a

look now if you've worked with solidity


you've probably seen these things called

events before or maybe you haven't seen

some of like events but you've always

wondered how chain link or the graph or

some of these other offchain protocols

work under the hood or maybe you just

love watching these vods in any case in

this video we're going to learn all

about logging and events in solidity how

to view them on ether scan and we'll

work with them in brownie as well now if

you like hard hat once again I also have

a hard hat version of the code that

we're going to go over and got a

hardhead blog as well links are in the

description all right let's get

froggy now it's the ethereum virtual

machine or evm that makes a lot of these

blockchains tick like ethereum and the

evm has this functionality called a

logging functionality when things happen

on a blockchain the evm writes these

things to a specific data structure

called its log we can actually read

these logs from our blockchain nodes

that we run in fact in fact if you run a

node or you connect to a node you can

make a f get logs call to get the logs

good function naming design get logs


gets the logs now inside these logs is

an important piece of logging called

events and this is the main piece that

we're going to be talking about today

events allow you to print information to

this logging structure in a way that's

more gas efficient than actually saving

it to something like a storage variable

these events and logs live in this

special data structure that isn't

accessible to Smart contracts that's why

it's cheaper because smart contracts

can't access them so that's the

trade-off here we can still print some

information that's important to us

without having to save it in a storage

variable which is going to take up much

more gas each one of these events is

tied to the smart contract or account

address that omitted this event in these

transactions listening for these events

is incredibly helpful let's say for

example you want to do something every

time somebody calls a transfer function

instead of all always reading all the

variables and and looking for some to

flip and switch all you have to do is

say listen for event listen for that

event to be emitted instead of writing

some weird custom logic to see if the


parameters changed at the certain time

and doing some weird stuff like that

listen for these events so a transaction

happened an event is emitted and we can

listen for these events this is how a

lot of offchain infrastructure works

when you're on a website and that

website reloads when a transaction

completes it actually was listening for

that transaction to finish listening for

that event to be emitted so that it

could reload or it could do something

else it's incredibly important for front

ends it's also incredibly important for

things like chain link and the graph

chain link for example in the chain link

Network a chain link node is actually

listening for request data events for it

to get a random number make an API call

or Etc sometimes there are way too many

events and you need to index them in a

way that makes sense so that you can

create all these events that happen at a

later date the graph listens for these

events and stores them in the graph so

that they're easy to query later on so

events are incredibly powerful and they

have a wide range of uses they're also

good for testing and some other stuff


but you get the picture they're really

sick now that we know what events are

let's look at what they look like how we

can use them and how we might use them

in our smart contract development Suite

now here's what an event is going to

look like we have an event here called

stored number so we have basically a new

type of event called stored number we're

saying hey solidity hey smart contract

we have this new event thing we're going

to be emitting things of typed stored

number in the future when we emit this

event it's going to have these four

parameters it's going to have a u 256

for called old number a un 256 called

new number a un 256 called added number

and an address called sender now for the

astute people here you might have

noticed that there is another keyword in

here the indexed keyword keyword and

this is a really important keyword when

we emit one of these events there are

two kinds of parameters there are the

index parameters and the non indexed

parameters you can have up to three

indexed parameters and they're also

known as topics so if you see a topic

you know that that's going to be an

indexed parameter indexed parameters are


parameters that are much easier to

search for and much easier to query than

the non-index parameters in fact way

back in that F get logs function it even

has a parameter allow us to search for

specific topics so it's much more

searchable than the non-index ones the

non-index ones are harder to search

because they get ABI encoded and you

have to know the ABI in order to decode

them if that confused you don't worry

about it we're going to explain it isn't

this video great now this just told our

smart contract that there is a new type

of stored number a new kind of event

here we need to actually emit that event

in order to store that data into the

logging data structure of the evm to do

that we need to do something that looks

like this this is what it looks like

when we emit an event it looks very

similar to calling a function so you

call Amit and then the name of the event

and then you add all the parameters in

there that you like here's the full

example of a smart contract that has an

event and is going to be the example

that we're going to walk through in

brownie again if you want to see a hard


hat addition of this link in the

description for the hard hat Edition

both of this video and the blog now in

this smart contract whenever anybody

calls the store function we're going to

emit this event here's an example of a

transaction where we called the store

function with a value of one let's look

into the logs to see what this event

actually is going to look like an event

is going to be broken down like so the

address of the contract or account the

event is emitted from the topics are the

index parameters of the event data this

is the ABI encoded non-index parameters

of the event what does this mean this

means that we took those parameters that

were non-indexed we matched them

together with their ABI or application

binary interface pumped them through an

encoding algorithm and boom this is what

we got if you have the ABI they're very

easy to decode if you don't have the ABI

they are very hard to decode these

non-indexed parameters cost less gas to

pump into the logs and are harder to

query like we said so if you think

something's important but like not that

important you dump it in data you dump

put into non-indexed now in this


particular contract since we have

verified the code we verified the

contract ether scan knows what the API

is and we can view this in De or decoded

mode hex mode is obviously the non-

decoded mode or in its raw hex or hexad

desal or encoded mode you can read more

about the layout of these events in the

solidity

docs so now that we've learned what

events are and what they're used for

let's look at our SN token let's see if

we need to add it anywhere okay maybe

for this mint function maybe okay maybe

for our initial deploy but actually does

this mint function already emit logs

let's take a look and yep it sure does

okay so we don't need to do any logging

on our snck token our snck token is good

let's go to our test token though and

let's learn how to read these logs to

make sure that we're actually using them

so we'll do a little test or a def test

test token emits event or log like this

we'll run this line again which again is

not good we should be using this as a

fixture but then we'll do with bo. do

rank let's just be the snck token. owner

owner uh and I need to import boa import


boa like this let's do snck token.

transfer to some random user so I'm

going to say random random equals boa

em. generate address like this we'll do

SN token. transfer random user and we'll

transfer them the whole initial Supply

so this transfer function if we go to

Def transfer this is on the erc20 Dov

and it calls this self. transfer this

internal transfer function which is a

whole bunch of code here but basically

this is what updates the balance right

so the balance of a certain address is

really just a mapping so when people are

like oh I have X number of tokens what

they're really saying is oh I have seven

in my mapping on that contract or

however many tokens they have right that

that's really all having tokens is is

having an entry in this mapping in the

smart contract kind of crazy right well

when we do snuck token. transfer this

transfer emits this I erc20 transfer

owner to to an amount so this transfer

event is actually specified in the I

erc20 interface and events by the way

they look just like structs to make an

event or a log you just have event the

name of the event and any of the

parameters in it and then you emit it


like this or you log it like this so in

the I erc20 interface it has those event

objects specified one such is the

transfer event but it takes the owner

the two and the amount and it emits them

so we can actually get this log by back

in our test here after we do the

transfer function but still inside of

this this wi context we'll say we could

say logs equals snck token. getet logs

like this and this will return a little

array of logs so I can even do a little

breakpoint in here and let's run this

test so we'll do MOX test- K paste it in

it'll pop us into this little terminal

here so let's see what the the logs

variable looks like so the logs has a

single event in it so this is an array

of different logs or events that have

happened and there's a single transfer

event in it with a sender receiver and a

value so we have we see sender receiver

value we go back to the erc20 we go down

to this we have sender receiver and

value exactly as the transfer laog is

doing so to do a little assertion here

we could say let's even look at uh the

snck token. owner SN token note owner is

this address here we can see that it is


also the sender so what we could do is

we could say the log owner is going to

be equal to the snck or is going to be

equal to the logs zero so the first log

or the first event. topics which we

learned about from the video we just

watched

zero which is going to be this sender

and we could do assert log owner equals

is equal to snck token. owner we can

even run this we can even run this in

our little terminal down here let's

paste that line in here we got a little

error because we're editing our test in

a breakpoint which is annoying then we

can run this and we get true so I'm

going to type Q we're going to quit that

got rid of the break point we could also

add another assert in here if we wanted

we could say assert snck token. balance

of the random user is now the full

Supply right because when we deploy our

snck token we give the initial supply to

the message test sender who's going to

be the what they're going to be the

owner so now let's run this test oops

clear uh we can do MOX test. K or MOX

test- K or just run all the tests

and we get both of them passing standing

so now we know how to get events how to


emit events what events are for and then

how to test events as

well all right so we're going to go into

fuzz testing in just a minute but but

let's go let's come back to this code

base and let's clean this up so this

looks pretty good but there's some ways

we can actually format our Viper and

format our python so that everything

looks much better now our code looks

like this and we have the Imports kind

of up like this and maybe in this weird

order here this is formatted kind of

terribly and I could 100% manually like

you know come in here delete all these

switch the Imports or we could use a

tool to do this for us now if I hit

command shift p or control shift p or

view command pallet and I type in format

document you might get a little popup

saying there is no formatter for python

files installed go ahead and install

formatter we're going to actually look

up the rough formatter so I'm going to

type rough in here click on this and

this is a tool that actually comes built

in with UV as well so we're going to go

ahead we're going to install this and

now what we can do is we can close that


formatter here we can now go back to

this we can type format document again

hit enter and it'll automatically format

our document to be much nicer ready

watch this I'm going to do a bunch of

enters here again now when I hit save it

actually automatically reformats it for

me every time I'm hitting enter a whole

bunch then I'm saving and it's

automatically reformatting if you go

back into the you can change the format

once again by going into your command

pallet and going through the settings

and switching the formatter Additionally

you can run some formatting through your

command line let's for say for example I

have all these Imports in a weird order

I could run oh actually well this won't

even work cuzz it's completely in the

wrong spot but I could do this which is

kind of gross I could do UV UV run rough

check-- select i-- fix and it'll

automatically fix a lot of my imports

except for this one for some reason um

but now I have my python formatted what

about Viper can I do the same thing for

viper well what if I do a whole bunch of

lines here here and I saved this ah man

it didn't it didn't format what's what's

what's going on here well this is where


we can use a tool called mamushi I'm

actually not totally sure how to

pronounce it there will be a link to

this in the GitHub repo associated with

the course and in the project if we look

up mamushi we will get benur 86 mamushi

and this is actually a Viper formatter

that we can also install we scroll down

in here we can see pip install mamushi

let me copy this we're going to go ahead

we're going to install it with UV so I'm

going to do a little little zoom in but

I still want to show you kind of all

this crazy stuff here and then we can do

UV add mamushi this we'll install

mamushi then we can run UV run mamushi

on our contracts folder and this will

reformat automatically our entire snck

token. VI to be much nicer looking nice

excellent

now something that I like to do and you

don't have to do this is I use something

called a just file to also run a bunch

of commands easily I have this thing

installed called just and if you want to

install it you can this is 100% optional

but it's a handy way to save and run

Project Specific commands so if I'm very

specific about how I like to have


formatters what I can do is I can create

this just file and I can create little

commands that I can create a command

that's a combination of a bunch of

commands but are really easy for me to

run so for example if I want to run the

formatter run the formatter oops and I

want to just be able to type the word

format and it runs all my format

commands what I could do is I could say

format like this and then I could do UV

run Ru check D- select i-- F and for

some reason this is getting my formatter

is thinking this is a python file

extension it is not a python file at all

so I'm going to go to my extensions I'm

going to look up a just file and it

looks like there's some extensions in

here for just and I want to look up the

just documentation for the one that they

recommend vs code just seems to be the

one that they recommend so we're going

to use this vs code just here I'm going

to go ahead and install

this now instead of this formatting as a

I would go down to the bottom section

here and click this python on and

instead do just like this so now my VSS

code knows that it's a just file and the

format it looks nicer but anyways I can


also do UV run

mamushi contracts and I already have

just installed again you do not have to

install this um but if you want to feel

free to do so but now I can just run

just format and it's going to run both

of these commands for me so that I have

a single Quick Command that I can run I

can do just format and and boom and it

runs all of my commands you can make

this crazy long you could have a whole

bunch of commands in here and this is a

popular option for people to make quick

commands if getting started with a

project takes a lot of time so this is

an optional additional thing you can add

if you want

to now on the topic of formatting one

more thing on formatting there's a link

in the gab repo associated with this

formatting thing but we can also do but

in our code

if this gets huge if we have a ton of

code here it can be kind of hard to know

what section that you're on and this is

where headers can come into play so in

the G repo associated with this course

there is a link to these two vhe header

repos one is vhe header pi and one is


headers VI so headers VI is a nice

little headers generator written in Rust

and you can go ahead and install it if

you want to work with rust but if you're

like hey Patrick uh I only have UV cuz

that's what you taught me uh we can use

this vhe header pi as well scroll down

and to install it we'll just do UV tool

install vhe header I'm going to copy

this come to my terminal I'm going to

clear this out UV tool install vhe

header and now what I can do in my

terminal is I can type something like V

header Imports and it'll automatically

copy to my clipboard what you see in

front of you now and in my codebase I

can now do a little the little section

here boom paste in Imports and now I

have the Imports section I can go back

in here I can do beheader state

variables boom and now I can Mark where

the state variables starts I can go back

in here clear the out viter functions

get that little functions section and

boom now I have the functions section

our Snick token here is pretty small so

this isn't super helpful for us here but

adding these little section headers can

make your code way way way more readable

and make sure that the layout of your


code base looks professional as well so

this is another very helpful tool while

we're on the topic of formatting

things now if you want to you can pause

the video and try to deploy this to CK

sync or sepolia or your tenderly virtual

Network or even Anvil whatever you want

to do because now is a great time to

pause go for a walk go grab an ice cream

or go to the gym because we're going to

get into fuzz testing next now there's a

a lot to think about when it comes to

fuzz testing and I've said this before

fuzzing is probably one of the most

important concepts for any smart

contract developer to know so I'm going

to be introducing you to fuzzing and

this is going to be a very introductory

basic guide of what fuzzing is later on

in advanced moccasin especially when we

get down to the moccasin defi stable

coin the fuzzing is going to be

incredibly important for us writing good

tests for this one we're going to be

writing some very basic fuzzing tests

just to kind of get you started get you

understanding what fuzzing even is and

how to write fuzz tests in Python if

you're already familiar with writing


fuzz tests in Python great you can

probably skip ahead a little bit or skip

much faster there's only a few tweaks to

fuzz testing in titano and Moccasin that

you need to learn so just to get you

primed what fuzzing is we're going to

watch this video about fuzzing and

invariant tests the basic idea behind

fuzzing is just throwing random data at

your contract in order to find a bug

throwing a lot of random data at your

contract many times we're going to learn

about stateless and stateful fuzzing how

to write good stat less and stateful

fuzz test and we're actually going to be

writing some stateless and stateful fuzz

test together on contracts that I've

already created for you so let's go

ahead let's watch this video just to get

Prime on what fuzzing is and then we'll

come back here and we'll write some fuzz

tests so let's watch this video and this

video is going to be using Foundry and

solidity but all the concepts are still

going to be the same and then we're

going to redo this in

Python all right contracts are written

and tested can I ship my code no I can

easily break this with a flash loan

attack a crap I didn't think about that


let me fix all right how about

now I make a flash loan on a I can use

that loan to lock up a cdb on Faker Dow

and I can exploit the Oracle by

re-entering your dinner reserv at

Chili's causing a bridge malfunction on

the flux capacitor bypassing the

possibility media can exploit your

contract I exploit your

contract most of the time hacks will

come from a scenario that you didn't

think about or write a test for but what

if I told you that you could write a

test that cannot check for just one

scenario but every scenario let's get

froggy fuzz testing or fuzzing is when

you supply random data to your system in

an attempt to break it so if this

balloon is our system/ code it's us

doing random stuff attempt to break it

this is chain

link now why would we want to do all

that let's say we have this function

called do stuff it takes an integer as

an input parameter and we know that no

matter what we give it as an input our

variable should always be zero should

always be zero the fact that this

variable should always be zero is known


as our invariant or our property of the

system that should always hold in our

balloon example if we Market our balloon

as indestructible or unbreakable or

unpoppable the invariant that would hold

would this balloon cannot be broken and

unlike this balloon in real life we can

write a test that will call the do stuff

function many times with random data and

check to see that our should always be

zero variable is always zero now a

normal unit test for our code might look

like this we pass a single data point we

call the function and then we do our

assertion to make sure that should

always be zero is in fact zero and with

this we might think our code is covered

but if we look back at our D stuff

function a little bit closer we can

clearly see that if our data input is

two should always be zero Zer will end

up being one this would break our

invariant should always be zero will not

be zero now this may seem obvious for

this function but sometimes you'll have

a function that looks like

this it would be insane to write a test

case for every single possible integer

or scenario so we need a programmatic

way to find this scenario now in our


code we also see a second exploit but

we'll get to that in a minute now there

are two popular methodologies to find

these EDC cases fuzz test/ invariant

tests and symbolic u/ form of

verification we'll save the ladder for

another video if we were writing our

code in Foundry this would be our unit

test writing a fuzz test in Foundry

where we do all this random inputting is

going to be really similar instead of us

manually selecting our data right in our

test parameter We'll add our variable

comment out this line and that's it now

when we run a Foundry test here Foundry

will automatically randomize data run

through a code with a ton of different

examples this is as if they run with

data equals z data equals 1 data equals

this number that's a t but whatever you

get the picture now if run my unit test

you'll see that the unit test actually

passes however if we run this fuzz test

you'll see it actually gives us an

output where it says assertion violated

counter example gives us the call data

and the arguments it was able to find

out by randomly throwing data at our

function call that two breaks our


invariant AKA it makes it such that

should always be zero is not zero now

it's really doing semi- random data

instead of purely random data and the

way your fuzzer picks the random data

matters it won't be able to go over

every single possible went 256 so

understanding how your fuzzers pick the

random data is an advanced thing that

you should learn later on at the moment

I think the trailer bits a kidna SL

optic integration is probably the best

fuzzer out there and it easily has the

best logo of all time but ripped Jesus

is a solid second so now that we have

our counter example here we can use this

to go back into our contract find out ah

okay so we are doing this wrong delete

this line and then run our test again

and see that it does indeed pass what's

important is this number down here the

number of runs so this did 256 different

random inputs to make our test run in

Foundry you can change the number of

runs in your Foundry tommo file by just

adding a section like this rerunning

your test and now you'll see it did a

thousand different examples the number

of runs is really important obviously

because more runs is more random inputs


more use cases more chance that you'll

actually catch the issue and now

congrats that's the basic of fuss

testing let's just do a little recap

here before going further the first

thing you need to do is understand our

invariant or property of the system that

must always hold and our example should

always be zero was our inv variant

understand your invariant and then write

a test that would input random data to

try to break that invariant now if we go

back to our example contract though

you'll see with our fuzz test we were

able to find this first use case however

it didn't find this second scenario

where should always be zero was set to

one if hidden value was seven in order

for this to revert hidden value would

need to be seven and the only way to set

hidden value to seven would be to First

Call do stuff with seven which would set

hidden value down here and then call do

stuff again with anything our fuzz test

as written would never be able to find

this that's because this fuzz test is

known as a stateless fuzz test which is

where the state of the previous run is

discarded for the next run if we go back


to our balloon example stateless fuzzy

would be doing something to the balloon

for one fuzz run then discarding that

balloon and blowing up a new balloon for

each fuzz run however instead of doing

State less fuzzing we could do state

full fuzzing stateful fuzzing is where

the ending state of our previous fuzz

run is the starting state of the next

fuzz run for example instead of blowing

up a new balloon for each one of these

runs we just use the same balloon to do

multiple random things to it combined is

considered one fuzz run so a single fuzz

run on a stateless fuzz run would be

having data B7 calling do stuff just

using the same contract that we just

called do stuff on and then call another

function on it if this was a unit test

we had we would of course see this get

violated but as you can see with

sufficiently complicated code calling at

these very specific scenarios are going

to be missed to write a stateful fuzz

test in Foundry you need to use the

invariant keyword and it requires a

little bit of setup and don't get too

confused by the invariant keyword here

yes it's being a little overloaded right

an invariant test and Foundry we first


need to import this STD invariant

contract and inherit it in our test

contract then we need to tell Foundry

which contract to call random functions

on since we only have one contract with

one function we're going to tell Foundry

that my contract should be called and

it's allowed to call any of the

functions in my contract so we'd say hey

the Target contract for you is going to

be the address of example contract

Foundry is smart enough to know okay

it's going to grab any any and all of

the functions from my contract and call

them in random orders with random data

so it's going to call do stuff with

random data and then it's going to call

do stuff with random data and then it's

going to call do stuff with random data

since do stuff is the only function now

we can write our invariant by saying

function invariant test always is zero

public and we can just add our resert

cert our example contract that should

always be zero is zero so it'll run do

stuff with some random data if it

happens across seven it'll set hidden

value to seven and then it'll call do

stuff again with hidden Valu starting at


seven which will trigger this

conditional so now if we run this test

we can see it does indeed find a

sequence where our invariant or our

assertion or our property is broken we

can see first on my contract it's going

to call do stuff with an argument of

seven and then it's going to call my

contract with an argument of some random

number because it doesn't matter what

the input is after it sets it to seven

so now that we have that we can go back

to our code remove this come back to our

test rerun our test and we'll find that

our code is now safe and sound because

our invariants hold up now in important

aside on the term invariant founder uses

the term invariant to describe this

stateful fuzzing stat less fuzzing is

when you give random data to an input to

a function to see if it breaks some

invariant State full fuzzing is when you

give random data and random function

calls to a system to see if it breaks

some invariant in Foundry fuzzing is

stateless fuzzing and invariance are

stateful fuzzing so when people are

talking about invariance and Foundry

they're usually talking about State full

fuzzing if they talk about fuzzing in


Foundry they're talking about State less

fuzzing even though they're both

technically fuzzing there's an issue on

the repo to potentially change the name

but I digress so in a real smart

contract your invariant won't be that a

balloon shouldn't pop or some function

should always be zero it might be

something like new tokens minted is less

than the inflation rate there should

only be one winner in a random Lottery

someone shouldn't be able to take more

money out of the protocol than they put

in and let me tell you what at this

point congratulations you've learned the

basics of fuzzing this is something that

even some of the top protocols in this

space don't use and this is something

that we in cphon use to find High

severity vulnerabilities in smart

contracts hey I'm Alex ran co-founder at

cyphon we use invariant tests during our

audits to identify vulnerabilities that

are often difficult to catch purely with

manual reviews that's not to say they're

a silver bullet they are in no way a

replacement for experts manual review

but they certainly can aidid in the

audit process this needs to be the new


floor for security in web 3 if you're

working with a protocol that isn't doing

stateful fuzzing or invariance or fuzz

tests red flag get them to use it make a

PR number one understand what the

invariants are number two write

functions that can execute them do not

go to audit without these don't let your

Auditors let you get away with not

having them so this video was just to

give you the basics and if you want to

learn the advanced fuzzing strategies on

how to fuzz like Pro be sure to watch

our next video on the topic is that'll

give you the keys to write professional

fuzz and professional invariant tests

come on gang let's make web3 better and

I'll see you next

time welcome back so we're going to have

you actually write both some State full

and some stat less fuzz tests we're

going to start with State less fuzz test

cuz they are a little bit simpler and

easy to and easier to follow along with

so in the get a repo associated with

this course if we go to the codebase

here if you go to contracts there's a

section called sub lesson and I want you

to actually create a new folder yourself

in the contracts let's do new folder sub


lesson in here and I want you to copy

the contents of each one of these so

we're going to copy this first one what

is this one this is State full this is

called State all

was solveable

.v paste it in here then we're going to

grab the other one stat less fuzz

solvable Dov let's grab this and we're

going to paste this in here State less

fuzz

solveable by past this one in here now

we're going to write some fuzz tests for

each one of these but before we do that

let's understand what these do so we

have this contract here it's really

minimal and we can see right at the top

what our invariant is the always returns

input number should always return the

input number so if we give this number

one it should return one if we give it

two it should return two three and so on

and so forth however we can pretty

clearly see that if input number equals

two it'll return zero so this breaks our

invariant right so our invariant of this

function is that it should always return

the input number whatever this function

is given we should get back now this is


kind of a simple invariant but in most

smart C in most smart contract systems

we can have invariants that are kind of

more meaningful for example if we had a

borrowing and loaning platform like a

maybe a you can never lend out more

money than you have or in a variant with

an erc20 token could be the total supply

of tokens should equal the sum of all

balances of all users once you start

understanding how to write good and

variance a lot of these fuzz tests will

become easier and easier to write but in

any case so here is our function we have

an invariant it's a very simple

invariant here let's go to our test

folder let's create a new folder call it

sub lesson let's create a new file

called let's create a new file called

test stateless dop now we could probably

pretty easily solve this with a unit

test right we would just create a unit

test where we pass the number two in

here but like I said often times the bug

is not going to be obvious so we want to

throw a whole bunch of random data in

here basically what we want to do is we

want to try this function with the

number one with the number two with the

number zero with the number 5,000 with


the number 84 just let python throw tons

and tons of random data at this and hope

that it catches the outlier hope that it

catches this case here so to get started

writing a fuzz test we're going to be

using this tool called hypothesis and

this is one of the most popular python

libraries for doing fuzz testing in

Python so this this will be applicable

to not just moccasin but it will be

applicable to really any of your python

coding career out there so let's go

ahead let's let's do a little bit of

basic setup and then we can write our

fuzz test so I'm going to say at pest.

fixture and I'm going to deploy the

contract so I'll do def contract we also

need to do import pest then we need to

get the contract by doing from

contracts. sub lesson import what do we

call this again fuzz solvable import

stateless fuzz solvable and then in here

we can just do return stateless fuz

solvable but. deploy and we're going to

leave this as scope equals function like

this and let's actually just create a

basic unit test for it so let's just do

a basic test test

always returns input we could say like


input

equals zero and then we can do assert

contract dot what's the name of the

function always returns input number

contract dot always returns input number

of input input equals equals input now

if we run this test as is right with MOX

test- K it's obviously going to pass

oops has no attribute always returns

input always returns input number

stateless fuzz solvable stateless fuzz

solvable always returns input number

it's because we need to pass our

contract fixture into here okay now

let's rerun this and great it passes

right it only fails if we pass two in

here so let's rerun this with two now

I'll hit up a couple times we'll rerun

it and it fails right so this is how we

would write a unit test but let's turn

this into a hypothesis test let's have

this test run with zero with one with

two and with a whole bunch of other

random inputs so I'm actually going to

go ahead I'm going to delete this input

variable and what I'm going to do is

instead of having input here we're going

to use a hypothesis tool called given so

at the top we're going to say from

hypothesis and hypothesis comes baked in


with moccasin from hypothesis import

given and this is where we Define a a

range of numbers for an input so as a

decorator I'll now say at given and this

input will now be a range of random

values that we can import into our

contract but we have to tell hypothesis

what type this is is it a is it a bunch

of random strings is it a bunch of

random booleans is it a bunch of what

what is it so we could say like int

equal equals int however we know that

256s can only be so big so what we can

do is titanoboa comes with this thing

called strategy so we can do from boat.

test.

test.

strates import strategy like this and we

could say our input should be a strategy

or of type uint 256 and by us doing this

we're saying hey we're going to have

this variable named input and it's going

to be any number between zero and the

max you went 256 if we just did input

equals int it could be any number

between zero and infinity and we would

get errors because our smart contract

would go hey um Infinity is too big of a

number so we're going to do this other


strategy of a Max U 256 now that we have

this input we can also pass this as a

parameter to our test like this and what

we could do is let's actually go ahead

let's run this test as is and let's see

what we get oh okay so we get we get an

error here and we get this error here

hypothesis doesn't like fixtures at all

and that's okay because actually

technically we probably should do like

you know contract equals this and don't

have this and then do this and then

rerun but sometimes we actually might

want to have a fixture and and we might

even want to have this as like a session

fixture so if you want to ignore that

warning what you would do is you would

from hypothesis import strategy and

health check and we would add some

settings to this test we could say at

settings which is another thing we would

import from

hypothesis at settings we would say

suppress health check

equals Health check. function scoped

fixture like

this oops sorry these are from

hypothesis up here so that's how you can

ignore that up there be be careful about

using this I'm using it for now but I


digress now if we run this test it

actually passes again which it shouldn't

and we'll fix this in a second but

essentially what just happened here was

hypothesis ran this test with a bunch of

random numbers so we could even see what

random numbers it tried by doing a

little print input like this and we'll

see how many different numbers this test

tried so let me pull this back up MOX

test- K oops excuse me MOX test- K we

also have to add- S to see all the

prints out and we can see every single

random number that hypothesis came up

with now right away we can see oh wow it

it didn't try that many examples so if

we want we can say hey uh hypothesis you

need to try more examples so we could

say Max examples equals you know 1,000

or something whatever number you want to

put here pull up the terminal again run

the same thing oh and this time it

actually errored so what's cool here is

it'll give you a falsifying example and

this is what you would use to recreate

and turn this into a unit test so you

can see the inputs are going to be the

contract right which obviously it's

going to be the contract and then input


equals two so it was able to

programmatically without us telling it

what the issue was that two was the

error two is what breaks our invariant

so this is a successful stateless fuzz

test for working with or finding an

example that breaks this invariant just

by knowing stateless fuzz tests just by

knowing this you're already better then

I kid you not 60% of python developers

out there not just smart contract

developers python developers this is an

incredibly powerful tool and you should

be incredibly proud of yourself for

getting past this we are going to do a

workshop in a little bit to practice

some of your stateless fuzz testing and

this is a great time to ask AIS a ton of

questions if any of this was unclear to

you you should ask an AI because this

can be a little tricky to grasp just to

reiterate once again our hypothesis tool

tried a whole bunch of random stuff to

break our invariant and it found an

input where this function always returns

input number did not return the input so

well done learning stateless fuzzing now

we're going to learn State full

fuzzing all right so we just solved we

just wrote a phenomenal stateless fuzz


test for this always returns input

number and we were able to break this

invariant at top always returns input

number should always return the input

number we found out programmatically if

two goes in this invariant is broken now

what if we had a contract like this

though so we have another invariant at

the top always returns input number

should always return the input number

okay we have the exact same invariant we

have this function always returns input

number we have input number and it

should always return the input number

now we can pretty easily see here that

if self. suum number equals 2 2 return

zero self. suum number this is a storage

variable up here the only way this

variable changes is if somebody calls

change number so if we were to create a

stateless fuzz test let's go back to our

our tests here right a stateless fuzz

test in our stateless fuzz test here we

were just calling a single example we

were just calling a single function

every single time we weren't keeping

track of any state at all this type of

test isn't going to work to solve this

issue right because in order for some


number to be two someone needs to call a

change number so this isn't going to

work because we're just only calling the

single function right we're not keeping

track of State this is why it's known as

state less we need to use a state full

fuzzer where it is aware of different

functions different state and different

basically different things going on in

the contract so let's go ahead let's

learn how to create a state full fuzzer

that can find the answer to Breaking

this invariant programmatically so let's

go to our tests let's create a new file

test State full. piy and let's create

our state full fuzz test in here now

working with a state full fuzzer is in

concept pretty much the same as working

with a state less fuzzer but the code is

going to look a little bit different so

to work with a state full fuzzer we

first have to make a class stateful

fuzzer

of type rule based State machine and I'm

going to do a little pass in here and we

got to do import excuse me

from

hesis do stateful import rule based

State machine now we haven't taught you

anything about classes in python or how


they work so if you're unfamiliar with

classes in Python just follow along with

what we're for now and now is a great

time to work with AI and do some Google

searching on how classes work in Python

and what they do it's not super

important for this section that you

understand how classes work but

essentially in our stateful fuzzer we

want to give this class a list of

functions that it can call on our

contract here and then what this class

is going to do what this object is going

to do is it's just going to call a bunch

of random functions with a bunch of

random input so our state less fuzzer

called a single function with a single

input multiple times our state full

fuzzer is going to call a whole bunch of

functions with a whole bunch of

different random inputs on the exact

same contract so if you go back to the

balloon example from the video that we

watched it's going to blow up a balloon

and it's going to try a whole bunch of

random stuff to the same balloon the

reason it's considered stateful is

because it's the same balloon you you

keep the state of the same balloon and


after after maybe 10 different attempts

to break the balloon you throw out the

balloon you blow up a new one and you

try again for State less the way it

works is you blow up a single balloon

you try one thing you throw out the

balloon you blow up another balloon you

try one thing you throw out the balloon

that's how State less fuzzing works we

kind of cheated a little bit by having a

fixture that was a session scope fixture

but don't worry about that too much

anyways so we want to give this state

full fuzzer a list of functions it can

interact with and different inputs for

it to work with as well so first we have

to initialize our stateful fuzzer with

what it's going to be doing some fuzzing

on so we'll do a little decore uncore

anitore uncore self and we first just

want to run super

doit uh this will run the initializer of

the rule-based state machine it's not

super important that you understand this

line but then we want to give our

stateful fuzzer a contract to keep track

of so we'll say self. contract equals

and we need to import this from

contracts. sub Lon import State full

fuzz solvable
solvable self. contract equals stateful

fuz solvable do deploy and what this is

going to do it's going to deploy a

contract it's going to try maybe 10

maybe 50 different things or 50

different steps and then it's going to

redeploy and that'll make sense in a

little bit now we need to give it two

things we need to give it a list of

what's called rules and these rules are

essentially going to be a list of

actions what can you do to this contract

and these actions can also have

Properties or invariance on them

themselves and you'll see what I mean in

a minute and then additionally we can

give it in variance and these are going

to be properties that should always hold

true so we have two functions that we

want to tell our fuzzer about let's go

ahead let's start with this change

number okay so to get started here I'm

going to say uh I'm going to create a

function on my fuzzer that can call this

change number on our contract so first I

need to import rule from hypothesis.

stateful and I'll say at Rule and we're

going to do the same thing as what we

did with the stateless fuzzer we're


going to say input equals and I got to

do from boat. test strategies import

strategy we'll say import equals

strategy this is a once again going to

be a uint 256 and we'll say def input

number or excuse me we'll say def change

number we'll say self and input and then

we'll just do self. contract. change

input to the input like this or we could

say you know new number new number new

number new number so what this is going

to do it's going to do pretty much

exactly what our stat list test did over

here basically we're going to create a

random new number a whole bunch of times

it's going to be in the range 0 to the

max un 256 size and we're going to call

change input is that what it's called on

this excuse me change number not change

input and we're going to call change

number on our contract here so it says

Rule and that's like a little bit

confusing here cuz there is no rule if

we wanted to we could add a rule here to

we could say like assert um self.

contract dot what is this sum number do

suum number does not equal seven or

something like that we could add a rule

here and that's why it's called rules

because these can be actions and also


have like an assert we're not going to

do that so great so now we're now we've

told our stateful fuzzer hey this is

something you can do you can call change

number on that contract object with any

number between zero and the maximum U

256 what else can it do well it can call

always returns input number okay great

this is where the invariant actually

lies because always returns input number

should always return the input number so

for this as well we'll still say rule

we'll do input equals strategy uint 256

oops excuse me uint

256 right because this returns or this

takes a u into 256 as an input then

we'll say say def input number returns

itself and we'll pass in self and input

like this and now we'll do kind of

exactly what we did up here we'll do

self. contract always what's the name of

the function I'm just going to copy it

always returns input number dot always

returns input number of input like this

now this is going to return some value

so we'll say

response or return equals self. contract

that always return random number and

then this is where our invariant comes


into play because what is our invariant

again always returns random always

returns input number should always

return the input number so we can then

say assert the response equals the input

and if we want we can also give a

rationale if this doesn't hit we can do

a little F expected input

got response so this is why these are

called rules because they can have

either just some action or they can have

an action and your rule or invariant now

that we have this set up what our fuzzer

is going to do is it's going to deploy

the contract and then it's just going to

start calling these two functions in

random orders so it's going to call

change number with some random number

and boom set the number then it's going

to call input number returns itself with

some other different random number and

boom and it's going to keep calling

these on the exact same contract then

after some number of steps it's going to

say okay I couldn't break it let's

deploy a brand new contract and it's

going to do that again so to actually

kick it off at the bottom we'll do

test State full fuzzing equals State

full fuzzer do test


case and then we can run this so let's

go ahead and clear and to run this this

is the ne name of the test here test

stateful fuzzing so we'll do MOX test- K

test stateful fuzzing and you'll see it

waited a long time because it had to do

a lot more work now what we could do to

actually see what's going on here so I

could do a little print statement here

print deployed contract and then in all

of our function calls here I could do

like a little print I'm even going to

like tab it out a little bit so it's

easier I'll say and this will be an F

statement I'll do called with new number

like this and then I'll do another tab

it out here we'll say input uh and then

we'll say called change number with new

number called

always returns with that now now that we

have these print lines in here we can

really really get a good idea of what's

going on so I'm going to clear run this-

s and now we can see a list of what it's

really doing so if we scroll all the way

to the top of all these print lines okay

I can't even scroll all the way to the

top um but we can see our fuzzer will

deploy a contract and then on that exact


same contract it will call change number

with this value change number with this

value a whole bunch of random values and

it looks like this run it only called

change number it looked like this one it

only called change number looked like

this one it only called change number

only called change number okay now down

here always returns with a random value

always returns always returns and then

it call change number and then it's

going back and forth then it's calling

both and then it's doing that a whole

bunch of times so our fuzzer is

literally trying a ton of random stuff

and then after it calls a whole bunch of

function calls on both different

functions it gives up and it goes okay I

couldn't break it let's start over so

all of the these steps are known as the

stateful step count and every time we

deploy a contract that's known as a the

start of a single fuzz run so from this

deployed contract all the way down to

here this is considered one fuzz run and

each one of these commands is considered

a step in the fuzz run so we can

actually set our settings up to change

the number of fuzz runs or examples or

stateful step count there's a couple


different types of nomenclature

depending on who you are we can do test

stateful fuzzing do settings settings

equals settings I'm going to say Max oh

and I have to import settings from

hypothesis we'll do from

hypothesis

import import settings we'll say Max

examples equals let's try to put it up

to 10,000 and we'll say this stateful

step count equals 50 so this right from

deployed contract all the way down here

is one example and these are all the

steps in here so we're saying let's do

10,000 examples with 50 steps in each

example so if you do the math here we're

going to call

500,000 functions to try to break our

invariant here you ready I sure am let's

go ahead let's run this and let's see if

we can programmatically find our

invariant and you might have to wait a

while because hypothesis and python

needs to run through a lot of different

examples here and after quite some time

you will eventually get an output like

this and this is actually why Cloud

fuzzers are pretty popular because

fuzzing can take a long time I know a


lot of people in the smart contract

world that they will run a fuzzer and

then they'll like go away for the

weekend just to have their fuzzer run

for days it's actually a good practice

to let your fuzzer run for a long time

but we can see here in our response we

have an assertion error expected one got

zero and it gives us an example so first

it called state. change number new

number equals 2 and then input number

returns itself and obviously because we

can see in the code here if some number

is two it's going to return zero so all

I had to do was call change number with

two and then input number returns itself

with any number and it was able to find

the outlier and with that you now know

the basics of both stat less and state

full buzzing this is an incredibly

powerful tool for smart contract

development and smart contract testing

and smart contract security Now the

hardest part of fuzzers is on the back

end is them picking intelligent random

inputs

so if you want to engage in helping

build really good random inputs the

Titanoboa boat. test. strategy is a

great place to start contributing and


generate much better much cooler random

inputs to make them find these bugs even

faster but in any case at this point you

know about stateful fuzzing you know

about State less fuzzing you should be

incredibly proud of yourself because I

want want to say like 75% of current

smart contract developers don't do

stateful fuzzing and you know how to do

it now and that's kind of crazy so you

should be incredibly proud of yourself

for getting this far so before you take

a break and I do want you to take a

break and you could take a break now too

if you want to but before you take a

break let's go to your Workshop here so

if you go to the GitHub repo associated

with this course let's scroll on down to

Workshop one here let's scroll on down

to Workshop one here we have two prompts

for your Workshop here the first one is

write some test for your Snick token

contract and try to get it to 80%

coverage this is something that actually

you know you can go ahead and use AI to

help Rite your tests and if you do that

you should be able to get test coverage

pretty easily remember we can do mock

test D- coverage like this oh and then


we well hold on we get uh we get them

failing because obviously our fuzz tests

are failing well we actually do have

100% coverage here but write an

additional function and test it so write

another function that doesn't up

coverage and then test

it that's the first prompt and then the

second prompt is more challenging where

we should write a stateful fuzzer for

your erc20 token in the GitHub repo

associated with this the snck token in

here does have a modified function in it

that does have a bug so I added this

super mint function in here and you

should and if you want to do this prompt

and you 100% should you should copy this

function bring it over to your snck

token and then paste it at the bottom

here and you should write a stateful

fuzz tester that actually finds the bug

in here this is kind of an example of

like looking at it right away it might

not seem that obvious that there's a bug

here the issue with this super mint is

that we forgot to update the total

Supply right self. total Supply Plus

equals amount we aren't updating the

total Supply so the total Supply is

going to look different from the balance


of all the users balances so the total

Supply is going to be different than the

sum of all the users balances now if you

go back to the gabbo associated with

this there is also I have a test fuzz.

py I have a example of a solution to

this problem but you should not look at

this you should try to write it yourself

first and then come back to this after

an hour so this is one that 1 hour is

okay working with AI a little bit is

okay don't just copy paste The Prompt

into AI try to actually solve this try

to actually write this fuzzy yourself

you can you can and should 100% use the

hypothesis documentation to help write

your fuzzer here now I'll also say this

you could 100% just write a stat less

fuzzer and that would eventually work

but I want you to write a stateful

fuzzer and I want you to try to add a

couple of the functions that your

contract can do like the mint for

example and I guess I am kind of showing

you the super mint and an invariant here

so okay you can go ahead and and just

peek this and kind of take a look try to

add at least two functions other than

just the super mint here so write a


stateful fuzzer try to have it find and

break the invariant that the total

Supply should always be the sum of all

the users balances so that's your

challenge here for working with buzzing

good

luck all right welcome back are you a

fuzzing wizard now I hope you are now if

you haven't taken a break yet after that

Workshop you should 100% take a break

your brain absorbs information much

worse if you do not give it breaks so if

you haven't taken a break now is a great

time to take a break we are going to

wrap up this section with a couple of

just additional pointers that have

nothing to do with with tokens and then

I'm going to send you over to the final

section of this course there's a couple

of learnings here that I want you to

know about before you finish moas and

fundamentals and the first one is going

to be random numbers we actually have

one of the workshops is for you to build

a provable random Lottery and there's a

couple different examples and I've given

you two examples one which uses very bad

Randomness and one uses much better

Randomness but it's a little bit

outdated in this repo and I'm going to


kind of just show you a little bit of

the solution for this uh early in this

repo we have this this line here where

we do a whole bunch of con catting and

converting and uh caking or I don't even

know how to say that to try to basically

get a random number but I want to tell

you right now that that random numbers

don't really work in the blockchain

because the blockchain is a

deterministic system so when you get to

this Workshop if you want to take the

easy route and use a pseudo random

number like this you you 100% can but I

encourage you to try to do the much

harder route and when I say much harder

route I mean much harder route of using

programmatically provably random number

using something like the chain link vrf

so this is something you should 100% be

aware of because I've seen way too many

projects go oh I'm just going to do kind

of this clever hashing thing and that's

going to make me a random number and

that's what ends up getting exploited

and you get hacked and you get wrecked

so if you think it's a good idea to get

a random number off of some values based

off the blockchain you need to remember


the blockchain is a deterministic system

and somebody can use that determinism to

gamify the randomness and make it not

random so that's the first point I

wanted to make to you

here the next thing I wanted to

introduce you to is this pattern of Ci

or checks effects interactions now I'm

going to kind of briefly go over this

and this is a this is some security that

you'll learn later on down the course in

advanced moccasin we will go over CI but

whenever you have a function you should

always think that it should go in the

pattern checks effects interactions and

this is to prevent a hack called

re-entrancy now I'm not going to go too

deep into re-anesthetized

later but essentially anytime you have a

function like def High you always first

want to do your checks this is going to

be kind of your internal checks you're

going to your asserts for example assert

you know self yeah sure whatever

whatever chat gbt said here first thing

you want to do is your checks second

thing you want to do is your effects

this is all your internal State changes

you know so I might do like self. total

Supply you know plus equals 1 all of


your internal stuff and then the last

thing you always want to do this is the

last thing is you want to make external

calls so any time you see this x call

keyword you should immediately go this

should be at the end of my function if

you see this something like this where

you make an external call and then you

update some storage value red flags

should go off in your head now this is a

rule of thumb there are some cases where

you might want to do this but by default

you want to follow this CI interaction

we'll learn about CI more like I said in

advanced moccasin and Viper also has

this really cool decorator called

non-reentrant which can help with this

as well but i' digress I wanted to just

bring this to your mind that there's

this concept of CI checks effects

interactions to prevent against

re-entrancy attacks we we will learn

about re-entrancy attacks in advanced

moccasin but you should know that it is

a thing and you should be aware of it

now and then finally I wanted to bring

your attention to

the console so you can do with Mo you

can do MOX console and this will bring


you into a python shell that has uh all

your moccasin stuff kind of already

baked into it uh everything that

moccasin would have so I could do you

know from contracts import snck token

and then I could do uh snck token or

snack contract equals snack token.

deploy uh let's say the initial Supply

is like six or something and you can do

this for actual networks as well so let

me quit out of here oops quit like this

you can do MOX console -- Network ZK

sync for example and if you had a zkc

network defined you could drop into a

console and actually send transactions

right from your console and this could

be an easy way to run scripts do some

devops that you want to kind of quickly

work with all in Python right from your

terminal now this feature is currently

in beta and if you want to help out well

the moccasin GitHub repo if you want to

help the feature the Mox and GitHub repo

is always looking for helpers always

looking for contributors and feel free

to jump in here make a PR or make an

issue so I know I kind of breeed through

these last extra learnings but I wanted

to just introduce them to you before I

send you on the way to how to get hired


and before Advanced moccasin we will

talk about them more in advanced

moccasin but I wanted you to know now

before we send you off so there's one

more giant Workshop that I really want

you to do and you should not continue to

advance moccasin until you've completed

the workshop in section 9 but before you

get started on Section N9 you should

congratulate yourself you just learned a

ton you learned what a state full

fuzzing was what a fun what a fuzz run

is what an example is what is a stateful

step count you learned what stateless

fuzz run is you learn how to use given

you learn how to use strategies how to

create a stateless fuzz strategy you

learned what a token was what's an erc20

token how can I create my own token you

learned that well it's actually pretty

stinking easy I can actually import

things directly from snackmate we

learned about MOX we learned about MOX

install and how we could install

packages directly into our project to

make our lives so much easier we learned

this let me zoom out let me get rid of

this too we're learn that this this

whole thing this is it this is all the


code mode you need to do to create your

own custom erc20 token your own custom

cryptocurrency that you can deploy right

now to some Network you know maybe ZK

sync for example have your own token we

learned about making our code way more

badass with vhe headers Imports we can

use these in our codebase they're just

giant comments right to make our code

look a lot better we learned about just

files we learned about mamushi to

actually format our Viper contract to

make the everything look much better oh

and it looks like these were screwed up

so it reformatted them for me thank you

so much we also learned about UV Ruff

right or UV run Ruff which is a python

formatter to make our code also look way

nicer we learned how to test events and

what an event is we learned about events

how can we find events how can we get

events we were briefly introduced to

random numbers CI and the console and

then of course we worked with snackmate

or snake mate I don't know how to

pronounce it thank you Pascal this guy's

Pascal for making this tool be sure to

start it also be sure to start moccasin

we learned a ton and you should be

incredibly proud of yourself for getting


this far and learning everything that

you learned in this section cuz this was

a lot so at this time congratulations

for finishing moccasin ERC 20s be sure

to go for a walk get some ice cream go

go to the gym before advancing to the

next section so be sure to take that

break before going to the next one and

I'll see you very

soon welcome to this brief section on

how to get hired I'm here and I'm just

going to talk directly to you I'm going

to spit some facts I'm going to let you

know what's good then we're going to

watch a video it's going to tell you a

little bit more about basically how to

get a job and how to get into this

industry now people could rant for hours

about how to get a job but I'm going to

tell you it all boils down to this do

cool and then show off that cool

or I guess said without the

profanity build really cool stuff apply

your knowledge and then show it off

somewhere doing that while you apply

when you're applying for a job when

you're looking to get a career when

you're looking to get deeper into this

industry
hiring managers are basically just

people who want to work with you when

applying for a job the hiring manager is

asking this question do I want to work

with this person does this person have

the skills I need to work with them and

then additionally some soft skills but

I'm not going to go over soft skills

people always people try to have like

courses on soft skills but it's really

just like interact with more people and

you'll get like better at like

interacting with more people like be a

good person I probably should make a

course on being a good person but that's

I don't know I should probably get

really good at that myself and how much

of an ego would I have to have be like

here's how you be a good person anyways

and now in the next video I'm going to

go over four or five steps to how to get

it and we are going to watch that video

but I am going to tell you these

basically four and a half steps right

now and the first step is kind of half a

step because the first step I always

tell people is write down why you want

this type of job literally exactly what

we did at the start of the Viper course

of writing down the reasons why you


wanted to finish this course is it

because you want to learn more more is

it because you want to change your life

is it because you want to have better

work life balance is it because you have

kids is it because you you want to be

able to flex your Lamborghini to your

friends I it doesn't matter it literally

doesn't matter if your reason for

getting a higher paying job or a better

job is because you want more money great

be honest with yourself write that down

but maybe go a little bit deeper than

like have more money have more money to

do what what will your quality of life

look like what will it feel like to have

more money what will be able to do what

will having more money enable you with

or what will having more time enable you

with maybe you're working two jobs and

you're trying to make ends meet write

down exactly why you want this job or

why you want to get hired so that when

things get tough because they will you

can fall back on those reasons and

remember this is why I'm trying so hard

to get this job so the first step write

down why Next Step do a full course and

learn the thing you're trying to get a


job in so you're doing a great job being

here already

but for example if you want to get a job

being a python and Viper developer do a

full course of python development learn

the skill do a deep deep dive into that

thing and if you're taking this course

right now this means you're not done you

should definitely finish Advanced

moccasin as well take a full course then

the next two steps the next two and a

half steps are probably the most

important ones apply your knowledge

build projects do things that give you

practice doing that thing and and you'll

learn more along the way and you'll

probably learn more than the course even

taught you but do things apply that

knowledge and this is where you know and

this is where you can go crazy using Ai

and Googling and etc etc this is why I

focus so much on saying hey get your

GitHub repo up sign up for cphon

profiles because especially with

developers that's where software

engineering hiring managers are going to

look they're going to look at your

GitHub your cyphon profile your code hog

R to answer the question of does this

person have the skills does this person


have what we need for our team some

great examples of things you can do are

you can join hackathons like eth Global

many many many of the teams that I've

worked on have hired people directly

from hackathons people who have done

well at hackathons eth Global chain link

hackathons Cod Hawks competitive audits

hackathons are a great place to show off

your skills speaking of competitive

audits competitive auditing platforms

like code Hawks or code finina these are

places especially if you're going to go

down the security track these are some

of the easiest places to get jobs I know

countless people who have done some of

these gone off and then got a job make

poll requests to open source projects

here's another one this one is way

underutilized and nobody uses this and

it drives me crazy because this is one

of the easiest ways to get hired find a

project maybe it's moccasin maybe it's

some other open source project that

you're into and you go hm I've used this

tool a lot but I wish it had this

feature drop into the GitHub repo maybe

make an issue asking hey can I

contribute to this repo and then go


ahead start making poll requests doing

things like documentation is nice as

well but but really nailing out some of

the tougher issues or some of the

tougher features that's really what's

going to be what makes people go wow

this person's legit they know what

they're doing maybe I want to hire them

and it could be the project that hires

you or somebody else who likes the

project goes who you contributed to that

project I love that project I want to

hire you you can build projects and add

them to your GitHub this is why I focus

so much on GitHub you should be building

portfolio projects and putting them

somewhere some place you can show it off

if it's not GitHub put it somewhere else

but you got to put them somewhere and

finally as you're building things as

you're gaining experience as you're

doing the thing this is where you start

applying for jobs or one of the things

that you're building one of your side

projects ends up being really cool and

you go turn that into a business you

could do that as well but these two

steps of applying your knowledge and

applying for jobs you're going to just

keep going back and forth and repeating


them and then that's the final step

repeat those two just keep doing this

learning and growing is something that

you're never going to stop you're always

going to want to be learning you're

always going to want to be growing

you're always going to want to be making

projects so do those so doing those

steps in tandem will be the thing that

ends up Landing you the

job here's a thing that can be a little

bit tough to hear you're going to see a

lot of rejection and that's going to

suck and it's not going to feel good

I'll tell you right now the first time

that I was trying to get into Tech that

I was trying to get a technical job I

must have sent 200 resumés out just for

99% of them to not respond to me but

just the one that responded to me I

hammered and that was my step in the

door that was my step into Tech it is

normal for it to be difficult it is

normal for it to be challenging but

again that's why you want to learn and

keep growing because you need to but

again that's why it's so important to

learn and keep growing because you need

to do something to stand out and that's


how you're going to land the job and

that's how you're going to get into this

industry so

speaking of doing things that is why

we're going to give you this next

Workshop here let's take a look so in

the GitHub repo associated with this

course the final workshop and I'm going

to update this your final Workshop

before jumping off here is to actually

go apply I'm going to force you I'm

telling you you got to do these things

spend at most one week on this so this

will be the largest so this will be the

largest Workshop out there and your

prompt is to build a smart contract and

your prompt is to build a smart contract

Lottery SL raffle contract yourself

using some minimal AI help and I'll tell

you right now building the test Suite

hypothesis fuzzing test Suite that you

should 100% try to build AI will

probably not do a great job on you can

do a weak Randomness Lottery if you so

choose using onchain Randomness just

know that that is going to be weak sauce

but if you want to go to the extra mile

use chain link vrf 2.5 to build a secure

Lottery that would be even more badass

and you should 100% put that on your


GitHub the other thing that's going to

be challenging about that is chain link

vrf is written in solidity so you would

have to do some conversion from solidity

to Viper for your mock contracts kind of

like what we did with the chain link

price feeds you should also have test

coverage of over 80% of your lines of

code you should have a function called

enter raffle for people to enter your

raffle the raffle should pick one winner

every X seconds this should be a

customizable variable the winner should

get the sum of all the entrance fees

added by all other participants and

anyone can call a pick winner or request

RN a function that will randomly select

the winner and then finally I have some

example code bases that I've written one

using the weak Randomness and one using

a slightly older version of chain link

that you can use for references here the

goal here is to do what the goal here is

not to give you some long hard

challenging project the goal here is

this this is how we get a job repetition

is the mother of skill and we want you

to be incredibly skillful then once you

finish this you should 100% post this


onto your GitHub and possibly post it on

Twitter see the thing is I know a lot of

us nerds are kind of antisocial but this

is also why I keep prompting you to jump

on Twitter or whatever social media that

you want to go on or I guess x.com now

because engaging with the community is

going to be how you're going to get your

stuff in front of other people engaging

with social media engaging on these

platforms especially before you have a

job is a fantastic way to get out there

and get exposed and then if you

absolutely hate posting this stuff if

you hate posting to GitHub if you hate

posting to Twitter if you hate writing

blogs or whatever social platform you

decide to use once you get the job then

you can stop so this is why I'm

encouraging you to do this stuff because

this is how you're going to get there go

off do that workshop and then come back

when you're

done welcome back did you actually do

the workshop CU if no you're not going

to get any

skills repetition is the mother of skill

and we want you to be skillful so if you

didn't do this go back and do it what

are you doing you're only hurting


yourself but if you

did congratulations and welcome to the

end of moccasin fun mentals you've

learned a absolute ton here but your

Learning Journey is not over to gain all

the learnings to gain all the knowledge

you got to go through the rest of

advanced moccasin and then if you want

to go the extra extra mile go through

the security curriculum as well the more

you know the more you can be a positive

force in this industry but you have to

celebrate the wins as well so you

getting here you getting to this point

in the curriculum is worth celebrating

so if you haven't done it already you

probably already know what I'm going to

say now is a great time to take a break

to go for a walk to get some ice cream

to go to the gym because you have earned

it and you should celebrate getting to

the end of this section congratulations

on finishing moccasin fundamentals and

we'll see you in advanced moccasin

all right welcome back and welcome to

Advanced moccas or Advanced Python and

Viper if you're following along with the

GitHub repo associated with the Viper

and python we're scrolling on down we


are now in the advanced moxin section

and these are the workshops we're going

to be working on now at this point you

know a lot of the basics of what we're

going to be working with so I'm going to

be handholding you a little bit less

obviously still walking through

obviously still walking you through all

the concepts everything you need to know

going to be letting you explore a little

bit more on your own and I want you to

explore more on your own here as you get

more advanced and as you get better and

better learning how to work with AIS

Google ask questions and forums

literally becomes your job literally

becomes how you get good at this and as

AI gets better and better you're going

to want to be on top of knowing how to

work with these tools so there are going

to be some times here where I say hey

we're going to go flip over to some AI

now and I want you to work with the AI

to get through some of these projects be

absolutely sure to do all the workshops

associated with each one of these

sections because those are going to be

how we really drill in all the skills

that we're going to be learning here so

welcome to Advanced moccasin welcome to


Advanced Python and Viper we're going to

be learning some amazing things in this

course working with nits we're going to

be doing finally some algorithmic

trading where I will show you how to

balance our portfolio we'll be building

our own decentralized stable coin we'll

be working with signatures and upgrades

and everything I'm going to be giving

you here is going to set you up to go

out there get a job work in the industry

build really cool Viper contracts and

then additionally it'll be setting you

up for success to actually head on over

to Security if security is where you

decide you want to go down which by the

way if you want to be a top tier

developer you should also be very aware

of how the security in this industry

works so welcome to Advanced moccasin to

Advanced Viper and Python and let's get

started so our first section is going to

be this this moccasin nfts and of course

if you're working with the GitHub repo

associated with the course you can find

the link here if you're working with

Cipher updraft once again as always you

can find the course resources in the

little link on the videos associated


with this and here is the full code the

full project that we're going to be

working with here I'm going to go ahead

and I'm going to walk through this

codebase to show you what we're going to

be building and what the end of this

project is going to look like and all

the crazy things that you're going to

learn along the way so I have the full

MOX nfcu get up repo for this section

right in front of me here it's a classic

mockasin project we have a mockasin DOL

with a lot of different pieces in here

now if you're unfamiliar with what an

nft is great no worries we will explain

that to you as well but essentially

these are smart contracts that contain

Collectibles or digital Collectibles

kind of like Pokemon trading cards or

baseball cards or pieces of Art and the

like and in here we have we're going to

be using snackmate or snake mate once

again just like we worked with the ERC

20s and build this ERC 721 or nft we're

going to be learning about what an nft

is what the different parameters are

what the different functions are Etc

here is going to be the whole code the

entire smart contract for one of our

minimal nfts our Poppy nft and we're


going and to deploy our first type of

nft we're going to be able to pull up

our terminal and run MOX run deploy

excuse me MOX run deploy basic nft and

this will go ahead and deploy a basic

nft and it'll say minted pug nft with a

URI and we'll get out this ipfs link

which is something that we will learn

about and that will point to this Json

file here where we have this image

attribute which will point to this cute

little pug here which represents what

our nft actually looks like this

adorable little doggy that will be our

basic nft then after we play around with

the basic nft we'll finally move over to

this slit L more advanced nft the mood

nft where I'm actually going to let you

do a lot of the coding but the cool part

here is we're going to go all the way

we're going to go ahead and actually

deploy this with a little MOX run deploy

we deploy to Anvil test that whatever

you want enter your

password this will get deployed we'll

actually get this base 64 encoded where

we can take this entire URL stick it in

our browser get this kind of weird Json

here but it's this Json that reflects


nft which looks like this we can then

additionally import this and we will go

through all this showing you how to do

it import this into our metamasks and

you can actually see the nft directly

inside of your metamask here the final

thing that we're going to be showing you

in this section is also going to be this

more advanced subl lesson where we learn

how to call anything we learn about

encoding we learn about raw call and a

lot of this low-level functionality that

we've been skipping over so even though

this is kind of a fun section where

we're going to be going over nfts and

arts and building really cool

Collectibles we're also going to be

going over some low-level encoding and

some low-level raw calls so buckle up

and let's get

froggy all right well we are once again

in our MOX CU or whatever folder that

you want to get started in and we're

going to create a new project we're

going to call it mkdir MOX nft CU CD

mock

nft cuu and we're going to go ahead and

CD into MOX nft cuu that new folder we

just created we'll do a MOX init dot--

vs code-- py project and I'm going to do


code dot but you can just as easily do

file open and select the new folder that

you just opened up I will open this up

in a brand new window as always let's

pop in here let's go ahead and

delete all these files in here so we can

get started with something blank let's

open up the readme.md and let's do a

quick little write down of what we want

to do we're going to create two nfts one

is just going to be a basic nft just to

get our feet wet with like what even

nfts are and then a second more advanced

one where the nft image can actually be

changed we're going to call this our

mood nft and if we're happy we'll show

an image of a little happy smiley face

and if we're sad and upset we'll show a

sad frowning face so we'll have a

dynamic nft where the nft can actually

change based off of what parameters and

what functions that we call in

it so before we can start coding on our

nft we have to know well what is an nft

so we're going to go ahead we're going

to watch a little excerpt little video I

made a couple years ago about what an

nft is what they look like and what they

can do for us so let's go ahead let's


watch this video

we're going to watch a portion of the

previous python edition of this course

where I explain nfts from a high level

and then of course we're going to get

into the ultimate nft tutorial so let's

learn about nfts look nfts are hot right

now nfts also known as ERC 721s are a

token standard that was created on the

ethereum platform nft stands for nonf

fungible token and is a token standard

similar to the erc20 again erc20 is like

link a maker all those goodies that are

found on the ethereum Chain an nft or a

non-fungible token is a token that is

nonf funable this means that they are

starkly unique from each other and one

token isn't interchangeable with any

other token of its class a good way to

think about it is $1 is interchangeable

with any other dollar $1 is going to

have the same value of another dollar

those are fungible tokens that's like er

c20s one link is always going to be

equivalent to one other link by cont is

going to be nfts those of you nerds out

there would know like a Pokémon would be

a good example of an nft your one

Pokemon is going to have different stats

different move sets and isn't


interchangeable with any other Pokemon

or maybe a more relatable one is like a

trading card a unique piece of art or

the like so that's what these nfts are

they are nonf fungible

non-interchangeable tokens that for the

moment are best represented or thought

about as digital pieces of art that are

Incorruptible and have a permanent

history of who's owned them who's

deployed them Etc now like I said nfts

are just a token standard so you can

actually make them do much more than

just be art you can give them stats you

can make them battle you can do really

unique things with them you can do

pretty much whatever you want with them

but right now the easiest way to think

about it and the most popular way to

think about it is by calling them Ot Ot

Ot it's OT or some type of collectible

or just anything that's unique so like I

said they're just tokens that are

deployed on a smart contract platform

and you can view them on different nft

platforms like openc or rable and these

are the nft marketplaces that let people

buy and sell them you obviously can do

that without these marketplaces because


it's a decentralized but they help and

give a good user interface now like many

of you out there my initial thought to

nfts was okay this sounds pretty dumb

but I think that that was dumb I think

art does have a lot of value and I think

that artists are not always paid fairly

for what they do and this is actually a

huge issue right now in the modern day

world where an artist can make some type

of art people just copy paste it you

know everywhere and uh and they never

get attribution for what they made so

having a really easy decentralized

royalty mechanism or some type of

mechanism where these artists can get

accurately comped for what they're doing

I think is really important I love music

I love movies those are pieces of art

that I digest and I really like and I

think it's fair for them to get comped

appropriately cuz they are providing

value to my life I think nfts are a

great way to solve this issue as kind of

having these decentralized audit trails

and and royalty trailers that we can set

up and and see really transparently

without having to go through some

centralized service so that's the basic

gist of it let's talk some more about


the standards the ERC 721 standard or

the nft standard this is the basis of it

all there is another standard that's

semi fungible tokens the 1155 we're not

going to talk about that here but you

can check it out the main differences

between a 721 and an erc20 on erc20 is

they have a really simple mapping

between an address and how much that

address holds 7 21s have unique token

IDs each token ID has a unique owner and

in addition they have what's called a

token URI which we'll talk about in a

minute each token is unique each token

ID represents a unique asset so since

these assets are unique and we want to

be able to visualize them and show what

they actually look like we need to

define those attributes of the object if

it's a piece of art we need a way to

define what that art looks like if it's

some type of character in a game we need

a way to define that character stats in

the nft this is where metadata and token

Uris come in so if you know anything

about ethereum you know that sometimes

gas prices can get pretty high

especially when it comes to storing a

lot of space it can get really really


expensive so one of your first questions

might be well are they storing these

images and and these art pieces on chain

and the answer is some sometimes back

when they were coming up with nfts and

artists were deploying stuff the eth

devs and the artists were like yeah art

let's do that art I'm just going to

deploy this one megabyte image onto the

ethereum chain and oh God it's so much

gas expensive at hit the delete button I

know why it's not um it's not deleting

and they realized that if they put all

this art on chain it was going to be

incredibly expensive so to get around

this what they did is they put in the

standard What's called the token URI

this is a universally unique indicator

of what that asset or what that token

looks like and what the attributes of

that token are and you can use something

like a centralized API or ipfs to

actually get that token URI typical

token URI has to return something in

this format like this where it has the

name the image location the description

and then any attributes below there is

often this talk of onchain metadata

versus offchain metadata because it is

so much easier and cheaper to store all


your metadata offchain a lot of people

will use something like ipfs that is

decentralized but does take a little bit

of centrality to keep persisting but

they can also use their own centralized

API however obviously if that goes down

then you lose your image you lose

everything associated with your nft

because of this most nft marketplaces

actually can't and won't read off on

onchain attributes or onchain metadata

because they're so used to looking for

the token URI obviously if you do

offchain metadata you can't do anything

really cool or really interesting or

have any games with your nfts for

example if you wanted to create an

onchain Pokemon game all your attributes

would need to be onchain in order for

your Pokemon to interact with each other

because if it was offchain then that

becomes a lot harder to

cryptographically prove so if you're new

with nfts and you're like wait this is

kind of a lot of information I'll make

it easy for you if you're looking to

render an image of an nft add your image

type ipfs add a metadata file pointing

to that image file on ipfs and then grab


that token URI and put it and set it as

your nft the chain link D and D article

does a great job of walking you through

this and showing you how to do this so

be sure to read that if you're looking

to learn how to do that we're not going

to cover that in this video but we will

be deploying our first nft with some

onchain attributes again having your

attributes onchain is really going to

allow you to build really creative nfts

that build games or have interesting

properties and and really makes the

authenticity of your nft guaranteed

because those attributes are always

going to be on

chain all right great so now that we

know a little bit more about what an nft

is we've actually learned that it's

pretty similar to an erc20 right it's

the ERC 721 standard so if we look up

the ERC 721 we can go to find this on

the ethereum website find all all about

what the different functions are if we

scroll down we can see some different

events in here we've learned about

events we know how to make events some

different functions in here as well

these are the solidity functions so we

could just easily write them as Viper so


what I could do is I could start

grabbing these okay maybe take this go

to my AI agent be like write this in

Viper please paste this in here and I

could do this for all the functions or

we could see if our good friend

snackmate or snake mate has one of these

already we go to snackmate we go to SRC

snackmate you go to tokens just like the

ERC 20V there's an ERC

721 now if you want to really get the

nitty-gritty down if you want to really

power through this and you want to

really understand what the different

functions are now is a great time to

maybe pause and look through all the

functions here now a couple of these

aren't going to make sense to you for

example these domain separator EIP 712

that's something we're going to learn

much much later in the signature section

but if you want to pause you want to

look over some of these functions so

that you can really understand what's

going on great otherwise we're just

going to go ahe we're going to use

snackmate or snake mate in our codebase

to make writing our nfts much easier so

we're going to go back over here I'm


going to remove my read me pull up my

terminal and I'm going to do MOX install

snackmate now you'll notice I'm not in a

virtual environment and in a previous

lesson I might have told you to go to go

in a virtual environment and we no

longer need to be inside of a virtual

environment because we made a little

issue on UV and they changed it so this

is the power of Open Source we made an

issue we said hey um we get this little

error here I have to be in a virtual

environment I don't think I need to be

in one and the UV people said yep makes

sense and they changed UV and updated it

and now we can just run MOX install snck

mate nice so now we have snck mate

installed we could also do MOX install

you know Pascal blah blah blah whatever

SL snackmate but you know whatever you

want to do here we can see it has been

installed in our pii folder and that is

great for us okay so we have that

installed now we can start using it in a

new contract called basic nft

Dov we'll create a little basic nft in

here now I know in that video we went

over some Concepts we'll go over them

again in here because the token URI

thing can be a little squirely so we're


going to make it make sense so let's go

ahead let's do pragma version

0.4.0 we'll do some classic dock strings

in here at like

MIT at title puppy nft because our first

nft we're going to use this cute little

puppy image that I showed you earlier if

you're in the GitHub repo associated

with this section it's going to be this

static pug. PNG it's going to be this

adorable little puppy this is going to

be our nft this is going to be our

digital art so to work with Snick mate

here we're going to say from snck mate.

tokens

import ERC

721 let's go ahead let's open ERC 721

let's see if it has any storage that we

need to initialize tokens erc721

let's look down in here okay some

interfaces yep recognize that implements

implements implements implements

implements some uses stuff okay

recognize that initializes okay so it's

using somebody else's storage for sure

uh export Sports okay support interfaces

okay aha okay so it has some storage

variables here so we need to initialize

this so and let's see does this need


anything else when it's

initialized okay use is ownable so we

need to initialize ownable as well I

think that's the only thing that it uses

right yep so we only need to initialize

ownable so let's also get from

snackmate do off import ownable as Al

and then we can say

initializes Al as we've done before and

then

initializes ERC

721 ownable walrus ow and we got to add

those in as well great let's do a little

at deploy we'll do def Dunder and it

we'll

say. and it and then we'll say your 721

doore uncore init uncore uncore let's

see what this needs for an init Def and

okay string symbol base U okay so we

need a string let's go ahead and make

those some State variables so we'll say

name symbol base so we'll say name is

going to be a

constant

string I think it's like nine I guess

wait what is it 25 okay string at 25

sure

equals puppy nft symbol will be a

constant string what size five okay

string of size five or the name will be


p nft and you notice this is only four

characters that's fine because it's less

than five what else a base URI base

URI for now just go ahead and set this

as con

string 7 equals ipfs col slash we will

learn what this is in a little bit and

then we're going to do the EIP well what

do we need we need the name e712 and the

version e712 and again we're ignoring

those for the moment we'll learn those

in a later section so just for now we'll

do

constant string one equal 1 ring 1 = 1

and then we can do name symbol thanks

chat GPT base U up name again and then

EIP 712 version what's it mad about for

me here and I forgot this up here and

this shouldn't have a double bracket and

that looks good to me okay cool so again

we haven't really gone over base U we

kind of briefly went over it in that

what is an nft video this doesn't make

any sense to you this doesn't make any

sense to you and that's okay because

this these two make sense to you and

this will make sense to you now let's

just clean this up a little bit with vhe

headers state or vhe


header

variables boom let's do the header

functions boom and that looks a little

bit nicer already and then we're also

going to do exports erc721 do _ uncore

interface so we get all the functions of

the erc721

nice so now that we have the basic nft

setup let's actually finally go into

this base URI thing so we briefly talked

about what a token URI was in the what

is an nft video that we just watched so

just a quick recap so a token URI is the

URI of the token and a URI is a uniform

resource identifier BAS basically it's

like a link right like https website.com

slum json. well this should be Json or

even something like this where the

protocol instead of being https is ipfs

the protocol down here is https it's

just basically some way of saying here's

a link that you can use to access some

type of information and https is one of

the most popular ones right this is what

we use on websites every day right if I

go over here go to gith home.com we see

that up at the top left we see this

https here you can have lots of

different protocols like ipfs that also

work great now this token URI this link


this this website needs to return Json

or JavaScript object notation basically

some type of object that looks like this

and it has a couple different fields

like name description image and

attributes image is actually the most

important one here where that must

return another link to an image so this

is another URI but instead of returning

a Json object this URI would return an

image and it might return an image that

looks like this instead so this this

part at the beginning though right this

protocol this is what's known as the

base URI for our nft right so our base U

here I said hey just put in ipfs our

contract is smart enough to say okay the

protocol or the beginning string of your

token URI is probably going to stay the

same so set that as your base URI if we

go look at the erc721 and we look up def

token U we scroll down here we can kind

of read this code to see what's going on

we see that internally this contract has

this mapping self. token U of token ID

which returns this token U and it has

some weird conditionals but basically we

see this line here if the token U isn't

empty then we're just going to concat


the base U plus the token URI right our

token U might be something like this

right so token U be something like this

and then the base U so the two of these

together will make our actually excuse

me this would be underscore token U so

the two of these together would make our

nfts token U now I have already uploaded

this image and this token U to something

called ipfs or the interplanetary file

system and if you go to the gab repo

associated with this we go to MOX

nfcu

SRC basic nftv oh excuse me not here if

you go to the deploy script we go to

script deploy basic nft Devi we click

this we could go to ipfs col SL slash

and paste this in and your browsers

probably will not have an application

that can read ipfs links so there's a

couple ways that you can view these you

can go to you can download this ipfs

companion it's a companion for the for

your chromium type browsers or you can

just download ipfs itself uh and it's by

the way it's not this one I don't I

don't know what this is it's not this

ipfs it's this one you can download the

app for ipfs and says hey a website

wants to open this application open ipfs


Desktop I have this installed so I can

go ahead and open this up and then it'll

give me an output that looks like this

Brave is clever enough to know that okay

it's going to be reading from my ipfs

desktop application which is currently

running but this is the response that it

gives me so we're going to talk about

ipfs in just a second but for now just

trust me this works and we're going to

use this link for our nft token URI I

will explain ipfs very shortly I promise

I know I say that a lot but I really

will so let's go to our basic nft and

let's make that token URI actually

customizable so we'll create a little

external function called mint and this

will take in a URI of string of length

432 and we're using 432 we're using 432

because in the ERC

721 VI the internal mapping of token

youru eyes is of size string 432 so

we're just going to be matching that and

what we're going to be doing is in the

erc721 from snackmate they have this

mint function which will allow us to

Mint one of these nfts so what we can do

is we'll first create a little token ID

of type un 256 which will equal erc721


doore counter so each one of these nfts

is going to have a unique token ID and

inside of here there's uncore counter

there's this storage variable uncore

counter and and you can see that every

time safe mint gets called this gets

incremented um and we're going to do

something very similar to what happens

in Safe mint so then we're going to say

721 doore safe mint actually if we go in

here we do underscore safe mint so this

safe mint thing it says it safely mints

uh basically all safe Min does is check

to see that we're not sending to like a

zero address so you'll typically see

like safe Mint or safe transfer and they

do just some additional checks like

checking for zero address so we're going

to call Safe mint and we need to send a

new owner token ID and then data so the

owner is going to be the message. sender

we're going to let anybody mint our

token here we'll give it a token ID this

token ID that we just got from the

counter and then we'll do just blank

data where we're going to learn very

short more about this data stuff and how

it works and particularly this check on

ERC 720 received function like why this

wants data and what the heck this is


this is oh that's going to be super

exciting when we learn that and then

finally we're going to do ERC

721 dot uncore set token

URI token ID and

_ set token URI URI UR I token ID like

this and if we look in here there's also

this other function called set token URI

which does kind of exactly what you'd

expect in this token URI hashmap it

basically sets it to our token URI like

so and what's nice is we don't have to

store the base URI so we get to save a

little bit of gas not putting this in

storage every time and we just add in

this kind of second half here if you

will not this ipfs oh and then

additionally we need to make sure we do

erc721

doore counter equals token ID plus one

you to make sure we increment the

counter as well and then just so that we

can see this if you would like let's

just make Bas U public so you can go

ahead and see it okay so very basic nft

anybody can mint this obviously you can

start to think of more creative ways to

Mint your nft for example you could add

like assert message. Val is greater than


or greater than or equal to you know 1

E18 or whatever and then you could have

like a withdrawal function that's the

only owner can calls so you could have

people pay to Min your nfts there's a

lot of very cool stuff we can start to

do now that we have our nfts

here let's write a deploy script for

this so we can see this in our metamask

and then I'll finally teach you what

this ipfs thing is so in our script

let's do little deploy Pi this is going

to be start to get very easy for you or

let's do deploy basic

nftp def moccas

main we should be very familiar with

this at this point let's do a little def

deploy basic

nft pass so we're actually going to do

deploy basic nft and in here we're going

to say

from SRC import basic nft that's what we

call it yep then we'll say contract

equals basic nf.

deploy then we'll

do

contract. mint and this is where we can

pass in a URI I'm going to say

pug URI equals and I'm going to paste

this in here so I already have this


uploaded to my IP PFS so for now just

follow along with me I will show you how

to upload and work with and add your own

custom ipfs stuff in just a second and

why we're using this weird ipfs thing in

the first place but for now if you want

to just copy this from the script here

paste it in boom this will resemble the

nft associated with that pug and we're

going to pass in this pug U that we've

set here and now since this mint

function right this mint function should

have minted us a new T and we should

start with counter of zero or token ID

zero should be able to do

token metadata

equals contract. token U of zero and we

could print

print token

metadata so if I pull this up now and I

just run MOX run deploy

basic nft we now get running run command

and boom oh excuse me this isn't the

token metadata this is the token URI

this is the token URI itself and that's

exactly what we want so this is actually

token

URI token

URI now let's finally learn what this


ipfs thing is so that we can actually

use it in our metamask here so I've

already explained ipfs in another video

so let's go ahead let's watch this video

about what ipfs is so we can learn why

we're using it to show the images of our

nfts at

all now let me explain a little bit

about how ipfs works it's this

distributed decentralized data structure

that's not exactly a blockchain but it's

it's similar to a blockchain there's no

mining though but there is pinning data

you can add data to this so let me

explain how this actually works and you

can read how this works on the site

there's going to be a link to this in

the GitHub repo associated with this

course but let me give you my basic take

on it so we have our code or or our file

or whatever it is right we have some

piece of data now as we know when you

really have anything you can hash that

thing you can hash that data right and

you can get a a unique output so and

that's actually the first thing that

ipfs does it hashes our data to get a

unique hash that only points to that

data yes a massive code file a ton of

text yes you can encode all of that into


a single hash function your ipfs node

does this hashing for you and every

single ipfs node on the planet has the

exact same hashing function kind of like

a blockchain right they all kind of run

this same spec the same specification so

we can hash our data on our ipfs node

and get this unique output what we can

do then is we can then pin that data or

pin that code or pin that file or pin

that whatever to our node we have some

data we get a unique hash of it all it

does is poost this data and have these

hashes that's it our node is connected

to a network of other ipfs nodes so

there's a massive network of people

running ipfs nodes they're incredibly

lightweight way lighter weight than any

other blockchain node and they all talk

to each other so if I ask the network

hey I want to get this hash all these

nodes would talk to each other and

eventually they'd reach up at our node

saying oh I found a node that has that

hash here is the file associated with it

now you might be thinking okay well

that's kind of centralized because we

have the data on one node here right

well you're right well here's the thing


what other nodes can do is they can say

oh that data looks really cool I want to

have that persist what they can do is

they can pin your hash they can pin your

data and they'll get a copy of your data

on their node and you can keep doing

this and so you easily allow an entire

network to easily replicate any code or

any data in a decentralized sense and

they're incredibly easy to spin up and

they're incredibly easy to work with

something about ipfs that makes it

drastically different than a blockchain

is they can't do smart contract there's

no execution it can really only store

it's just decentralized storage that

ipfs can do now the issue here is that

in order for our data to really be

centralized another node does need to

pin our data right because if we're the

only PFS node that's got this hashed

it's kind of centralized on our node if

our node goes down that data is gone and

the network won't be able to access that

data anymore so we'll talk about

strategies in the future about having

other people pin your data but for now

this is a way we can host data we can

send code and have it be in a

decentralized context so unlike a


blockchain where every single node in a

blockchain is going to have a copy of

the entire blockchain ipfs nodes get to

optionally choose which data they want

to pin and they can't do any execution

so you could have an ipfs node half a

megabyte and you could have an ipfs node

that's several terabytes it's up to the

node operators how much data and what

data they want to pin if you want to go

the extra mile you can actually go to

the ipfs website and download this ipfs

thing and download the ipfs desktop

browser or the ipfs app once you have it

installed it'll look something like this

and what you can do then is you can pin

different objects to your own ipfs node

so for example I have the Pug metadata

pinned to my ipfs node here additionally

I have the image and well I can view the

local gateway to actually view the image

here now on your ipfs node each one of

these files is given something called

the CID and if you click copy CID you

could paste it into a file here you'll

see it's just kind of this string right

and this is the the Pug U we have in our

deploy script this CID represents the

unique hash of the content that's stored


on ipfs so that's why when we use this

as our URI for our pug when it's

combined with the ipfs colon sl/ prefix

this is this unique identifier for that

piece of content whether it's a pug

image or the Json or really any data at

all so all of the data related to my nft

is stored here in ipfs now again the

reason we're storing it an ipfs and

we're not storing this all on chain is

because the data for this can actually

be kind of crazy big so for example this

is a PNG if I save this image to my

downloads and I pop this into a file

here often times your vs code will

actually render this but I'm going to

open this as a binary object as a text

edit and this is what this kind of looks

like in its raw form kind of but this is

a ton of data and storing all this on

chain would cost as you know a lot of

money so we store it in ipfs instead to

save us money now the data on ipfs is

decentralized right because anybody can

just pin this data right it's much much

better than something like storing my

image on some random Google Cloud web

server or something right because

anybody can pin this data however ipfs

doesn't have what's called Data


persistence if everyone went ahead and

just did set pinning and then unpin

these and then turned off their nodes

you wouldn't be able to find this

anymore right so if you upload an image

to ipfs and you the only one who pins it

and your node isn't running then no one

will then nobody would be able to access

that data this is where you can work

with services like Pata Pata nft Pata

nft Pata the internet's file API where

you can upload images directly to panata

and basically just pay somebody else to

pin the data for you or you can

decide or you could use a different

service or decentralized technology to

store your nft data which we will learn

very soon so ipfs though is

substantially better than using

something like Google cloud or AWS and

we've actually seen a ton of nfts deploy

with the token URI pointing to like AWS

or gcp or Microsoft Azure Cloud only for

those jpegs to stop rendering images

once those servers go down so that kind

of defeats the purpose of having an

immutable nft so ipfs is much much

better we're also going to show you

cooler ways to store your nfts using


svgs and R weave but we'll get to those

shortly anyways so that's more about

ipfs if you want to upload your own

image this is how you would do it you'd

want to just import the image import

your Json object as well where this

image here where your image attribute

would point to your image that you

uploaded so boom so there' be two files

you'd want to upload Json object and an

image object so I did it for you so you

could get this

so let's finally do the final step here

and let's deploy this to our own chain

and see it in our metamask so we can

actually see this hey Patrick I does

this actually work do I believe you so

if you're using the nft that I gave you

this should work if you're using your

own nft make sure you have pinned your

data to your ipfs node so what we can do

is we can actually deploy this to Anvil

and see it in our Anvil chain if you

want you can still use tenderly if you

want you can use you can use pretty much

whatever you want I'm going to go ahead

and I'm going to show you how to deploy

this to the Anvil your Anvil your

locally running Anvil chain so first

thing we're going to do is we going to


do Networks net

networks. Anvil H uh URL is going to be

what well let's run Anvil this is going

to be our u o this is going to be our

URL right here URL equals

HTTP like this we'll say prompt live

equals

false and we'll do default account name

equals anvill one and we'll say in my

terminal I will open up a new and I'll

do MOX wallet list great I have the

Anvil one key store here if you don't

have it you can do MOX wallet import

Anvil one obviously and then grab this

top private key in our Anvil instance to

import that for you but since we have

that now we can just run our deploy

script again we can just run MOX run and

what's the name of our

script let's right here MOX run this--

network Anvil get prompted for our

password I think my password is password

for this and boom

transaction broadcasted mind and

contract deployed to here now what we

can do is we can add our Anvil Network

to our metamask if we haven't already so

we'll come up to our metamask I'm going

to actually click the three dots we'll


expand view going to go to my networks

here add custom Network we'll say it's

Anvil We'll add an

RPC which will just be our Anvil RPC let

scroll up here it's this one oops this

one right here copy this

HTTP paste it in we'll call it Anvil add

URL chain ID is 31

eth like this and now I can switch to my

new Anvil chain here very nice you'll

see I have no nfts in here but what I

can do is a couple of things what I can

do is I can import the Anvil private key

into here so since I deployed this with

Anvil one what I can do so I can go up

to my Anvil instance I can grab this

private key from Anvil go over to my

metamask I'll hit the accounts button

add Hardware wallet or uh account we'll

do import account from type private key

paste the private key in import and

since I'm on the Anvil chain it says I'm

a multi-millionaire that would be super

nice so now I'm on a count three on my

new Anvil chain for nfts in the nfts tab

we can now do import nft we just need to

grab that address that it was deployed

to Boom copy this paste it in here token

ID should be zero import and the nft was


successfully added now you'll probably

get a blank image here now as of today

for some reason reason metamask doesn't

support ipfs for the

nfts so if you really want to see this

what we can do is we can use something

called a Gateway a centralized Gateway

and this is a way of viewing ipfs data

without going through ipfs so if you go

to the MOX nft sa and updraft we have

this centralized Gateway option for you

so if you want to just use this instead

we can copy this we can paste this in

here instead let's get rid of this

starting point so that is just this URI

stuff and then in our basic

nft this htps gateway. pat. cloud. ipfs

we would have to change this from a

string seven to a string

34 and now this is more centralized

since we're using the centralized

Gateway on most marketplaces like openc

or element using ipfs should work fine

but just so that you can see it in your

metamask you can feel free to work it

like this so now we'll run this again

MOX run deploy Das Network Anvil type my

password in here I get the contract

deployed here so now I'm going to open

up my metamask let's go ahead let's


delete delete this import a new nft

paste it in token ID of zero and boom

now we can see the pug looking all kinds

of adorable in our metamask so just a

quick recap here using ipfs is much

better than using like this HTTP site if

pinata if the pat. cloud website goes

down you now have a broken jpeg so ipfs

is much better however metamask doesn't

support ipfs at the moment so we're

using a Gateway just to show you what it

should look like in your metamask

we can also do this whole process with

the era test node so I'm going to go

ahead I'm going to delete that Anvil

instance I'm going to do era test node

I'm going to start up a locally running

era test node for my private key one I

have this saved as well if I do MOX

wallet list I have oh I don't have it

saved so what I can do I'll I'll do MOX

wallet import

CK Rich one and from the era test node

we'll grab this private key this is a

account o excuse me we'll grab this

account zero which is really account one

which is associated with this address

here paste it in here my password will

be a terrible password great but now I


can do same thing MOX run deploy basic

nft D- Network era test node oh I should

probably add this to my MOX Ando huh I'm

going to copy all

this we'll say era test node what is

the endpoint on this let's scroll to the

bottom endpoint is here URL

is

this is ZK sync equals true ZK Rich one

will be the default account name and

that is it so now I can deploy this here

enter do

password and it deployed okay great so

same thing and we see a little couple

warnings here that's fine and where is

this contract deployed contract deployed

here what we can do is we can add this

as well same thing to our metamask we'll

go to add a custom Network era test node

add a RP crl eror uh test node add URL

31337 oh sorry this is 260 260 eth not

Guru what the heck um save now we'll

switch to the era test node we'll do the

same thing import a new account from the

private key we'll go to the era test

node again we'll scroll all the way up

to this private key paste that in here

import for nfts now import nft we'll

scroll down in here to contract deployed

to here we'll grab the contract address


paste it in token ID zero import and

boom now we have an nft deployed on our

ZK sync era test node

nice now an important note when you stop

your era test node or when you stop your

Anvil node and you go back to your

networks your nfts might still show up

and they might go away if you start

getting some weird errors what you can

do is you can click up here go to

settings Advanced clear activity tab it

clear and this should kind of do like a

nice little reset obviously you know

right now if I tried to send money cuz

my eror test note is down um it would

just kind of gray out for us which is

really annoying so just know that hey uh

and then we could even do a little

refresh list and it's going to just

nothing's going to happen so just know

that if your networks are down if your

locally running networks are down you

might get some weird stuff showing up in

your metamask so just be sure to keep

that in

mind all right and this leads us all to

the first Workshop associated with this

course so if you're following along with

the kidub repo associated with this


course

we have Workshop one for our moxin nfts

as always spend at most 25 minutes on

all these prompts without the a of AI if

you're unable to if you are unable to

solve them after 25 minutes stop take a

break and then work with an AI order the

or the discussions to help you solve

them number one upload your own dog

image to ipfs minted at mint it as an

nft and see it in your metamask so so

there's a couple of things to remember

if you use your own ipfs your ipfs node

must be running right it must be on and

my desktop app has it such that if I

even close my application it's actually

still running in the background if I

pull up my like I get this little like

node option in the top right of my

computer that I I need to turn off if I

want to stop it or you can use a

centralized service like pinata Cloud

right pat. Cloud you just upload it

directly here that will give you your

own image as well remember though

remember though the token URI should

return something that looks like this

right adjacent object not just the image

the image attribute in the J should

return obviously like an image right you


can use on the local Gateway if you

would like in the GI up repo associated

with this course in the images section

we have a couple other dogs like a

little Shibu or a SA Bernard if you want

to use those as well so see if you can

deploy an nft that is Workshop number

one and be sure to see it in your

metamask you can deploy to Anvil eror

test node import those into here and see

it like that and then number two write

some tests we don't have any tests you

should write some tests to get at least

80% coverage remember MOX test--

coverage test D- coverage right now we

get well nothing because we don't even

have any tests so that is the second

part of this Workshop so these are your

two workshops this first one might

actually take more than 25 minutes if it

takes a little more than 25 minutes

that's okay this one should take you 10

minutes this one probably is going to be

quicker than the first one so pause the

video pause the course do these

workshops and I'll see you in a

bit all right welcome back did you do

the workshops I hope you did because

those are going to be the things that


really help you advance in this industry

so if you did the workshops great job

welcome back if you didn't do the

workshops what are you doing go do the

workshops all right let's keep

going we've got this basic minimal nft

but we don't love it we're not thrilled

with it why well we're using a

centralized cloud provider because we

wanted to see it in our metamask but

metamask doesn't support ipfs so that

was really annoying so we did this we

also know that ipfs isn't the best

either because if everyone stops pting

our node then we won't be able to see

the data anymore right so this pug

centralized as of recording I am the

only person in the world who has this

data pinned so if I were to just you

know set pinning unpin this right and

then I turned off my node no one else

would ever be able to see this nft and

that's not great so I'm actually going

to repin it you might be saying hey

Patrick it would be much better if I

could like put this data on chain

somewhere right it would be so much

better but ah it's so expensive oh well

you're in luck because there are a

couple of ways we can do that so one of


the ways we could do this but we're not

going to show you how here but if you

want to go deeper into this yourself you

can you could do something like R weave

this is a blockchain for storing lots of

data so for example you could store an

image a token URI all this stuff on our

weave and it would still be very cheap

and then you would use use a URI that

points to a certain contract on the r

blockchain as your token URI so that

could could be one way if you want to

play with that more I highly encourage

you to do so but instead we're going to

use something called an SVG now an SVG

is something that we can store all on

chain but the issue is that we have to

be able to encode our image as an SVG we

can also encode our Json

onchain as a base 64 encoded U what the

heck do both of those mean well first

let's get started with what is an SVG

now I'm going to be showing you a bit of

a video from The Foundry curriculum

everything that I'm going to show you

here works for our MOS curriculum here

as well it's all about svgs you don't

have to actually do the encoding that we

show you here but just follow along and


you'll see that whoa you can actually

both encode svgs into a URI itself and

use it in our images so let's go ahead

let's watch this little sub video

here so let's first understand what an

SVG even is so if we go to w3schools.com

we can go to this SVG tutorial so SVG

stands for scalar vector graphics and we

can actually scroll down and we can see

an example right in this SVG example

right so this is it so it looks it's

just kind of this tag where it has very

specific parameters for defining what an

image looks like and the reason that

svgs are so cool is because no matter

how big or small you make them they're

always going to have the exact same

quality because they are scalable you

know how like if you take an image like

this one let me view this now if we take

this image right and I make it super

super big make it super big the bigger I

make it the worse the quality gets with

an SVG you don't ever have to deal with

that because you define exactly what

it'll look like no matter what size and

what we could do is we can actually make

our own SVG sort of like this right and

if you're in the W3 schools if you hit

try for yourself you can see my first


SVG over here and I could change this I

could say the fill is now blue we run

and it now turns blue I could say the

stroke is black right and it turns black

so there's a ton of different parameters

and functions that we can do to make an

VG look a certain way right so if we're

back in our vs code we can even go up to

IMG new file example.svg

code some SVG in here so we'll do SVG

xmlns equals and this is just versing

stuff

HTTP

www.w3.org

2000 SVG it a width of 500 a height of

these need to be in

strings we'll have a closing SVG tag and

here we'll make some text say Phil

equals black hi you decoded this back SL

text like this real minimal SVG like

this and then if we go to extensions we

can look up SVG and there's a couple of

different SVG viewers and SVG previewers

I forget which one's the best one let's

go with this one for now now now what we

can do is go back to our SVG open up our

Command pallet type in SVG preview SVG

I'm going to install this SVG preview

going to go ahead and hit install now we


can come back to our SVG open up

SVG preview open preview to the side and

it looks blank so let's fix that we'll

say x equals 0 y = 15 x = 0 Y is 15 fill

is black text okay that looks good

preview the SVG and boom we can see this

a little high your browser decoded this

on the side now this is just the

SVG and this storing all this on chain

is not a URI right our nft needs a URI

right it needs this string this is not a

URI this is an SVG but what we can do is

we can actually convert this into a URL

that our browser can understand and

we're going to pass all the data we need

in the URL of our browser so this going

to sound really bizarre right but what

we're going to do is we're going to CD

into that image folder and we're going

to run a command called base 64 now not

all computers have this you can check by

doing B 64- dhel if you don't have this

don't worry you can just copy paste what

I'm going to be doing we can actually

base 64 encode the out everything in

here and what I can say is I can do base

64- I which means we're going to input a

file and we're going to pass in this

example.svg we'll see we get this weird


thing as an output so now if we take

this weird thing and I'm going to

actually create a little little read me

to make some notes here so this weird

output is the base 64 encoded example.

SVG we just created now at the start of

this we can add a beginning piece to

tell our browser that this is an SVG so

I'm going to say data colon image/ SVG

plus

XML base

64 comma like this and if I copy this

whole thing oop sorry this is should be

a semicolon here if I copy this whole

thing and I paste it into any browser

we're going to get this hi your browser

decoded this so basically what we did

was we encoded this SVG file and put

this data image SVG plus XML colon Bas

64 so our browser knew how to decode it

and then just passed the entire image

through our browser URL and boom so we

can also do this with images so if I go

back to the repo associated with this

lesson go to images Dynamic nft we go to

happy

SVG happy. SVG we go down to code

instead of preview and see the exact

code here right we create this view box

oops we create some circles we create


this path which is how we just kind of

draw lines and I can copy this whole

thing paste it into my image so I'm

going to say oops image I'm going to do

happy SVG happy. SVG paste it in here I

pull up the preview I see the preview is

a happy now what I can do is I can do

base

4-i happy. SVG we get this output and

copy this output let me go over to the

read me paste it I'm going to add this

beginning piece to it and then copy this

whole thing back to my browser paste it

in and boom we passed all of this data

to generate this SVG right in the URL

and this is looks like yes it does a

token URI right so now instead of using

us an ipfs hash for our token URI we can

actually 100% on chain use this SVG

thing and because this SVG is basically

code on Shain we can update it and

interact with it to make it do whatever

we want it right for example if our H

happy SVG we could say okay if if

somebody has 10 tokens right they get 10

circles or something like that right we

could do whatever we want with this

welcome back

okay so now that we know what an SVG is


and that we can actually encode it and

we can use this en coding to actually

build an nft where all the metadata is

stored directly on chain and this is

really exciting so that's what we're

going to build now and to make it even

cooler this is going to be a dynamic nft

we're going to make a dynamic nft whose

mood can be changed so an nft where

it'll start off as a happy image and

then it'll turn sad so if you go to the

gab repo associated with this go to

images Dynamic we're going to start off

with this happy SVG where this whole

image will actually be stored on chain

and if we decide we're sad it'll flip to

a sad SVG let's go ahead let's build

this nft and we're going to be learning

a lot of low-level stuff as we do this

so let's jump in so let's get started

we'll call our we'll create a new

contract called our mve

nftv and in here you already know how we

do pragma version

0.4.0 do a little dock string here at

licens MIT at title mood

nft and we already have snuck mate

installed so we'll do from snuck mate

tokens import ERC 21 since this uses

ownable we'll say from snackmate Doo


import

ownable as Al we'll do

initializes Al and then initi lizes ERC

721 ownable walrus ow then we have to do

def init

_ init and ERC

721 init we can actually borrow all of

this stuff from our previous contract

let's just past it in here let's just

copy all this state variable

stuff like this except for we don't need

except for we're going to be changing

oops we're going to be changing this

base

U this won't be puppy nft this will be

mood nft so M

nft why is it mad at me here

expent and this needs at

deploy nice looking good we'll need to

do the exports in a bit as well but I'm

going to save those for later and you'll

see why soon so right in our deploy

script here I'm going to have I'm going

to have it taken the happy SVG URI and

the sad SVG URI so we're going to encode

these into a base 64 token URI where you

don't need https you don't need ipfs

this whole image will be stored as like

data we can view in the browser so I'm


going to do happy SVG U uncore will be a

string of let's say like 800 and we'll

do sad SVG URI which will also be a

string of like 800 excuse me like

this now I'm actually going to show you

how we can do this in our script already

so deploy mood

n.p def moccasin moccasin main Ploy mood

and then we'll do def deploy mood pass

here how we can do this is in here we'll

say happy SVG U equals blank then we'll

say Sad SVG U equals blank and AIS are

pretty good at this but what we'll do is

I'm going to open and create a new

folder called images I'm actually going

to save both of these save the sad and

I'm going to save the Happy download

save stick both of these in here images

happy just stick this sad in here too

and you can see these svgs are really

minimal right this is the entire code

that governs what the sad looks like and

what what the Happy Looks like if I go

to my extensions I can even look up like

SVG

preview I can click install for this SVG

previewer and now when I look at these

svgs I can actually see what they look

like right so I think it's I open my

command pallet and I look up SVG preview


SVG to the side boom I could even like

change some of these right I change the

70 to like 10 right you can see the

eyeball kind of changes or I could do

100 150 now it's looking very awkward

right so what's kind of cool about this

is if you put this code on chain you

could actually have your image even

update if you update the image based off

the fvg updating but I digress so cool

so we have these two items and what we

can do is we can open them up I'll do a

little with right I'll do with open

slash images

Slappy SVG I'm going to open it as r or

in read mode as F I'll do happy I'll do

happy SVG equals f. read and then what I

can do is I can actually base 64 and

code it into a URI itself into an image

URI I'm going to create a little little

function down here def SVG to base

64 URI SVG and actually AI is great at

giving you this so python has this

built-in package called base 64 so we're

can to import base 64 oops Bas 64 so

first we have to get the bytes so if

this doesn't totally make sense to you

that's okay this isn't super important

that you know SVG bytes equals sg. ncode


tf8 so we're converting this SVG data

into bytes then we can do base

64 dot there's this function called B 64

and code SVG bytes then we have to

decode it to

utf-8 again this isn't super important

you really know what's going on and

we'll call this base 64 SVG and then we

just say return F data colon

image image SVG plus XML base 64 comma

base 64 SVG so this format this data

image SL blah blah whatever this is also

a protocol and it's the prefix for base

64 coded data so browsers actually

natively understand this so what I can

do now which is really cool is I can say

happy SVG U

equals svg2 base 64 URI

happy SVG and ready watch this ready

I'll do a little print happy SVG URI if

I run this MOX run deploy mood nft will

get this massive output and if I copy

this paste this into my browser my

browser renders this perfectly no weird

ipfs no having to call any points no

centralized nothing just Raw Pure data

encoded and decoded beautiful so then

what I can do I'm going to do the same

thing but for the sad one so with open

uh thank you chbt I'm going to hit


tab sad SVG equals f.

read thank you I'm going to hit Tab and

then what I can do is I can say mood

contract equals let's import that from

SRC SRC import what do we call it mood

nft mood nft mood nft mood nf.

deploy happy SVG U sad SVG U like this

so this is how we're going to deploy our

mood nft we're going to pass it this

data so if we go back to our mood nft so

this is going to be this string this

giant data object which returns this

little image here nice so we're passing

them in we probably want to save these

somewhere in our contract as constant

variables cuz these won't change so

we'll say happy SVG Ur equals or excuse

me uh this will be an immutable string

800 and then I'll do the same thing I'll

make a sad one as well and right in the

structor happy SVG U equals happy SVG U

and sad SVG equals sad SVG you're all

right beautiful all right

great so now that we have the SVG stored

here we need to figure out how to

convert this or add this to the Token

Meda data right cuz this is what we need

to show right something that looks like

like this so what we can do and this is


why we didn't export the erc721

functions is we can actually create our

own at external external def token U

function ourself so if we go to The

erc721

Bu look up def token

Ur we can do the exact same thing it

does EX except we're going to have our

token U actually let's do return like

this we are going to have our token URI

do some clever stuff so we need to

create a token URI that returns

something that looks like this right so

what we can do is we can use the concat

feature in Viper so Viper has another

built-in function called concat which

takes two or more bytes arrays or

basically strings of type bytes M bytes

or string and combines them into a

single value if the input arguments are

all string the return type is string

otherwise it will be bytes so what we

can do is I can do a little I say Json

string we'll say string

1024 equals

concat and this is where I can literally

pass

in this kind of data here right so I

could say little single quote bracket

name double quote single quote comma and


here's where it's going to get a little

confusing so we're basically going to be

P mealing together this this Json object

but then we'll say name comma single

quote double quote comma double quote

description um and if you want if you're

like what I'm going to screw this up

because there's all these single quotes

and double quotes you just go to the

GitHub repo associated with this go to

SRC mood

n.v scroll down to the token youri and

just copy this section here right just

just so that you don't accidentally

screw something up you don't have image

youri yet but that's okay so this is

kind of us peac mealing together that

Json string that Json metadata right the

only thing that we don't have yet is the

image U so we could though we could just

say image URI type string 800 equals

happy SVG URI right boom and this would

this would make adjacent string that

looks you know just like this but with

this image URI of the happy SVG URI nice

now this having this Json string is

great but the token U needs to return a

token URI right this this needs to

return some looks like you know ipfs SL


blah blah blah blah blah blah right not

this Json thing this or like

htps blah blah blah blah and then this

returns this I know that's kind of

confusing but so we need to convert this

we need to encode this to be Bas 64

encoded and don't worry we're going to

make this Dynamic pretty soon so when I

was originally creating this course I

was going to walk you through kind of

the giant process C of converting this

from a string to a Bas 64 encoded object

but I don't know if it's really worth it

because it's just kind of like a lot of

math with the B 64 encoding and doing

all this weird chunking and stuff so

here's what I'm going to say that you

can do for now same thing go to the get

a repo associated with this scroll down

and you'll see this SVG to and this set

indc truncated copy both of

those bring them over to the contract

paste them in and and up at the top

you're going to have to say from from

snck mate. utils import base

64 you're going to need you're going to

need to do final string size is going to

be a constant U into

256 equals it's going to be four *

base 64 doore data output


bound plus 80

constant and then additionally you're

going to have

a Json Bas which would be a

constant

string of

equals

data colon application sljs semicolon

base 64 comma and then you're going to

need an MR image base your I size image

base your eyes size constant constant U

256 equal 26 and then image base

U constant

constant of constant string of size that

equals data colon image/ CG plus XML

base 64 so I know this is a little bit

anticlimactic in working with this this

stuff but we do kind of a lot of

low-level Viper stuff here which I could

walk you through but what I'd rather do

is I'd actually rather just teach you

all the different concepts that are in

here so that you know what this is doing

we do our subl lessons which is going to

teach us about ABI encoding and decoding

so that you can understand everything in

here but actually writing it I think it

will kind of go over a lot of your heads

at the moment so I know like I said a


little anti-climatic but just copy paste

this I'm going to explain what these do

and yeah and then actually same thing

with the with the token URI we're going

to cheat a little bit more here go to

the GitHub repo underneath the Jason

string there's all of this stuff just

copy this for now paste it in Jason base

U size we need that as well Jason base

right side is going to be constant you

into 256 = 29 so I know that's kind of a

lot of copy pasting here return

result and this is going to be final

string size like that so a bit of antic

climatic but let me walk you through

kind of all this stuff that we just put

in here what the heck is going on um so

that we can actually understand this

code and and keep going so we are

running into the problem where this is

what we had right we had Json string and

we had nothing else we basically had

like kind of this object like this this

stringified

object right and we needed to convert it

from the stringified object to a token

URI right something that looks like this

like a base 64 encoded token URI and

what we did to do that was first we


converted it from a string to a b using

the Viper built-in convert and this is

where it starts to get weird is we

chunked it so we called base 64. incode

if you look in your lib here the lib pii

snackmate utils base 64 there's this

encode function that it has and

essentially what it does is it Returns

the maximum four character user readable

string array that combined results in

the base 64 encoding of the data what

does that mean

well this encode function basically

converted this Json bytes into the base

64 encoded object except instead of it

being a string it was this array of

arrays right so it's this kind of

lowlevel blah blah comma uh Ox blah blah

or I guess it's four here yeah so it's

this lowlevel array of arrays which is

essentially a base 64 encoded string and

we needed to take it from this weird

array of arrays byes data and convert it

into a string so we looped through the

array created this custom function

called set Indy

truncated which did some kind of bizarre

array multi uh array manipulation and

then did this weird ABI and code and

decode which we definitely have not gone


over and we will go over very soon

essentially is we looped through this

array of raw byes data and we updated it

into a string and boom return results

that's kind of the final string the Bas

64 encoded string so essentially we did

a lot of weird encoding and decoding

stuff array manipulation to get this

Json object from a Json string into a

base 64 encoded string everything in

here you pretty much should recognize

right everything in here you pretty much

should recognize so we have this encode

function we don't really know what it

does but we have a dynamic array of type

string four so yes you can have an array

of strings this was the max size here

that's something we understand yep we

understand this we understand this we

have a for Loop here great we understand

for Loops we have this set indc

truncated slice is new slice is

something we haven't gone over but it's

pretty straightforward basically copies

a list of bites and returns a specific

slice so for example um yeah here's

here's a perfect example example

contract. Fu why hello how are you if we

just said hey grab grab just a slice of


this string starting at position four

and going for five so we'd go 0 1 2 3 4

we'd start with the H we go for five 1 2

3 4 five boom and it prints out hello so

slice is just getting like a subsection

of an array so for example this string

32 elements size 4 we would just get

hello but the thing we do not know is

this Abi encode and decode and we're

finally going to learn what this is how

does this AI encode stuff and so much

more so to learn more about all this

weird encoding stuff we just did that I

had you copy paste we're going to jump

over to your friend remix so I can show

you some stuff in remix let's learn

about encoding and decoding and

everything everything that we're going

to be going over if you're in the GitHub

repo so with this section you go to SRC

you go to subl lesson everything is

going to be located in here so let's

create a new file I'm going to call it

encoding Dov let's get started so I'm

just going to copy paste pragma version

0.4.0 license whatever title and coding

and

coding doesn't really matter so let's go

ahead and let's get started just viewing

some stuff so let's make a function at


external at pure def

combine

strings we'll pass in string one which

will be of size string 50 and then we'll

do string two which will be string 50 as

well we'll have this return string 100

using that concat function right if we

did return concat string one string two

what what do we get well let's compile

this with our compile it let's deploy it

if I do string one I say hi string two

hello I now get hi hello if I do string

one will be my name is space comma

Patrick my name is Patrick literally

just combines the two of them nothing

super clever there well let's learn

about that ABI en code thing so if I do

add external

at pure Def and code number returns a

bytes 128 I could do return aior encode

some number I could say like amount of

Type U 256 equals 1 I can return ABI en

code amount we'll compile this delete

that we'll deploy this now if I click

encode number I get this crazy output

here this is the bytes

representation of the UN 256 one it's

this giant number like this zoom out a

little bit and it has 1 2 3 4 5 6 7 8 9


10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8

930 1 2 3 4 5 6 7 8 940 1 2 3 4 5 6 7 8

9950 1 2 3 4 5 6 7 8 9 60 1 2 3 4 it's

got 64 characters and it's a classic

representation of what the number one

looks like in heex or in bytes if you

will so if you go back to the Viper docs

ABI encode says it takes a variable

number of args as input and Returns the

ABI V2 encoded by encoded by string use

for packing arguments to Raw call EAP

712 and other use cases where consistent

and efficient serialization method is

needed and there's some future plans to

move it into the ethereum ABI usace so

what if we were to do something else

though what if we were to do you know

number

two come go ahead compile

that oops

sorry that's how you do comments in

Viper number two deploy this right

scroll down what do we get boom we get

number two we get the same exact thing

but encoded number two well what about

25 what does 25 look like I'm going to

save it let's redeploy deploy down boom

it's 19 0x 19 so what's the number 10

represented as in HEX well it's

represented as it's a very fancy hex way


of encoding and decoding these numbers

when these numbers are stored to storage

they're stored in these hex forms right

so this is how we can see those hex

forms ABI encode will get us the hex

form we can also encode strings so so

I'm going to make a little internal pure

function called Def uncore and code

string this will return a bytes 128 so I

could have a string like my string

string 50 equals hello world world even

though I know that's less than 50 but

that's fine I can return AI en code my

string right and then I'll make a little

at external pure Def and code

string returns bytes 128 return self

doore and code string like this cancel

that deploy this and what you'll see is

you'll see the string encoded right so

this is the bytes

representation of this string right so

same thing when we store if we were to

store hello world in storage this this

is what it would be represented as it

would be represented as this hex data in

storage of our contract so not only can

we encode strings to their hex data but

we can also decode them so I could do at

external at pure def decode string which


will return a string 50 and we could say

decoded string string 50 equals

aior dcode

self doore encode string to string 50

actually we could just do this we just

say return turn turn like this so Abid

decode we go back over here we take an

input bytes and an output type and some

other and like unwrap Tuple if it's

Tuple but essentially we say okay we're

going to give you some raw hex some but

and we want you to decode it into this

type now this won't work if the bytes

object is too big or too small or

doesn't make sense and you can play

around with it to figure out where it

may may not make sense essentially we

get we could give this function in code

string this bytes object and have it

return the string so right so if I were

to go ahead deploy this now uh decode

string we see Hello World so it took

this it took this giant number stuck at

through this decoder and we got hello

world we could also do multiple encodes

and multiple decodes so I could do at

internal at pure

defcor multi

encode return a bytes

256 my string string 50 equals hi Mom


and I'm going to copy this whole thing

I'm going call my string 2 string 50

equals comma

missu and I could encode both of them

return aior

encode my string my string 2 we'll save

it deploy it uh oops I should do me at

external at pure def

multi and code U returns a bytes

256 return self. multi encode self.

multi encode like this save it deploy it

deploy multi encoded get this giant

object and we can do the same thing by

decoding it at

external at pure def multi

decode returns two objects string 50

string 50

returns oh sorry duh already just did

returns then I say my

encoded strings equals or of type bytes

256 equals self doore multi encode so

we're going to start with this giant

object like this then we can say my

string string

50 equals empty string 50

copy paste it for my string

2 and now I could do my string comma my

string 2 equals aior

decode my encoded strings AI decode into


string 50 comma string 50 and then

return these two so what we're doing

here is we're taking this giant bytes

object right we're getting it with this

line as M encoded strings we're calling

ABI to code we're say hey take this

encoded object and convert it back into

the string 50 string 50 and let's return

those so if we were to deploy this now

deploy pull this down multi decoded we

now see hi Mom miss you and that's how

it's able to decode that now this just

by itself has told you what this is

doing so for some reason we're ABI

encoding the buffer so just with this

information we now know what this line

is doing or we now know what this

function is doing we have this buffer

object which is of type string we encode

it to be of type bytes and then we

decode it into this string final size

why do we do this well we need to take

some slice update the values in an array

and then change its size and return it

so this is how we're doing some very

clever array manipulation stuff so great

now we know ABI and code and decode

hooray we know everything now right well

yes but let's think back a hop in it

remember way way way way back in the day


when we did our buy me a coffee remember

this remember when we did this buy me a

coffee thing

and in this code in our buy me a coffee.

VI we did this very weird raw call thing

where we originally taught you send and

it's like oh well send makes more sense

Patrick that's like very clear why did

we do this weird raw call thing and we

passed bytes of zero well it's this raw

call that's going to unlock in us the

power to call anything even if we don't

have the Abi even if we don't know

exactly what the functions are and this

is where we can level up so I'm just

going to copy paste this you don't have

to copy paste this but now we want ask

the question okay how does that have

anything to do with this how does

everything you just told me have

anything to do with this raw call and

I'm going to tell you that this ABI

encoding and decoding stuff is once

again how you can call any contract

without using an inter interface without

using without having its Ai and you can

just directly call and build the byes

yourself to call the right function let

me show you and to do this we're going


to learn about function selectors

function signatures and how this ABI

encoding fits in because ABI encoding is

helpful for like doing stuff with

strings but it's even more helpful for

raw

calls so let's create a new file and

we're going to call it call anything. Vi

we're going to unlock your superpower

here so I'm going to grab all of this

stick it into here we're going to call

this call anything and let's get started

on our erc20 and our ERC 721s we have

this function called transfer right so

we have

def at external def transfer and it's

usually has a two which will be an

address and an amount which will be a un

256 right let's create a transfer

function here and it's going to not do

anything really clever we're just going

to have um the two update State variable

and the amount also update a state

variable so we'll do some address will

be a public address and we'll say amount

will be a public ENT

256 and our transfer function won't

actually transfer anything it'll just

update self. suum amount equals the two

and then self. amount equals the amount


so our transfer function will just

update storage not very clever very good

uh contract here and this should be some

address not some amount and here's the

question I want to pose to you when

contract a calls contract B and calls

the transfer function how does it know

to call this transfer function right

because on chain everything is like this

hex data right and we did a little bit

of that hex encoding and decoding over

here it's all hex data or even or even

us when we call how does it know what

functions to call well kind of under the

hood Viper is doing a lot of this

encoding and decoding for us so in the

same way that you can encode numbers and

strings and all this stuff you can

encode you can encode your function

selection and that sounds a little bit

bizarre and it is a little bit bizarre

remember way way back in the day where

we deployed our first contract in web

3.y and we did this build transaction

thing right and we looked in the E

the.org transactions website well if we

scroll down in here again there was

something that we really haven't used

before and it's the data field or I


guess in here it's the input field well

it's the data field and it's this data

field it's this input field that

contains all of the instructions that we

want a contract to do so we send it to

an address and we send all this data and

this and this data or this input is all

the instructions of what the contract we

want the contract to do if you look at

any transaction that does anything other

than just you know transferring raw eth

there's always this input data field

right and eth scan does a great job of

kind of decoding it for us but or your

or whatever block Explorer but if you

view it as original or Raw like this is

what it looks like it's just this jarble

of hex stuff and it's all this hex stuff

that tells the contract this is what I

want you to do this the way it does this

is it ABI encodes all of your

instructions this includes ABI encoding

the function you want to call this input

data is often known and called the call

data and you can think of this call data

as essentially the computer encoded

version of our instructions so if we say

hey we want to transfer X to some

address that gets encoded into this hex

data so this call data is essentially


the encoded version of our function

calls and so this gets us into the topic

of function selectors and function

signatures so we have in remix here we

have this transfer function here now if

I wanted to call this contract right I'm

going to I'm going to compile this and

I'm going to deploy this deploy it if I

wanted to call this this transfer

function what I would need to do uh

what's going to happen is I'm going to

put in a two address I'm just going to

put myself in here and then an amount

I'll say one I'll call transfer since

I'm in the remix VM it goes through if I

scroll down in here um there should be

an input field right boom input field

right here I'm going to copy this me

saying call The Transfer function put in

this address and this amount that whole

thing gets a bi encoded to this to this

giant X object here so us calling

transfer us saying transfer with this

address with this amount gets converted

into this this hex data is the exact

same thing as saying call transfer with

the with some address with some amount I

could even change this right I could say

just change the amount we'll get rid of


the address here right let's go ahead

we'll redeploy this after I save now if

I put a in here I'll call transfer I'll

pull this up let me just call it again I

can scroll down in here I could look for

that input boom input or data field now

the instruction of call transfer with

amount of one gets AB decoded to this

and you'll notice it's a little bit

smaller because there's no address in

here so anytime you call a function with

parameters or anytime you just call a

function it gets encoded into Data now

let's go even one step further what if

we just said transfer no parameters what

does that get ABI encoded into we'll

call deploy we'll click this oh um

excuse me we need to just do pass let's

save that let's

redeploy now if I pull up the terminal

here I call transfer select the drop

down input is this which if I copy it be

prepare to be blown away it's just this

this is the entire input and what this

is saying is all this is saying is call

The Transfer function there are no

parameters and it's this value here this

value is known as the function selector

and that's what we're going to be

learning about right now and if we


wanted to we could just use this

function selector to call any function

instead of using an ABI because whenever

we use an ABI the API just converts it

into the function selector so let me

show you something really incredibly

cool so since we know that when I call

this transfer function right when I call

this transfer when I click this button

here me calling this transfer function

is going to get turned to this little X

data right I could say okay if somebody

calls transfer we'll do self. amount

equals 100 right so let's go ahead let's

close this let's redeploy right now

amount will start off at zero but if I

take this I paste it into this call data

section I hit hit

transact oh it's saying fallback

function is not defined that's actually

that's actually an issue with remix but

that's fine I'll do

deore default underscore underscore

we'll just do pass like this we'll

redeploy oh what do I do at

external external like this if I deploy

this now and I pass this function

selector in here right so amount is

going to start off at zero paste this in


here hit transact am amount is now 100

cuz this is how you call the transfer

function in its XX which is Pretty

stinking cool and this is a major unlock

because now you can call any contract

using its function selector so this is

known as the this hex data Here is known

as the function selector the function

selector is the first four bytes of the

function signature ABI and code it so if

we had this transfer function and we

were to ABI and code this we the first

four bytes would be would return this so

the function signature is the function

name plus the types of any values so if

this transfer function took again you

know a two which was of type address and

an amount of type un

256 the function signature would then be

transfer address comma U into 256 six

and the selector would then change to

something else so we could actually find

this ourselves a number of ways so we

could do like def get uh let's do uncore

get selector let's take this down here

get selector one which will return a

bytes 4 this will be

at

internal at View will return method ID

transfer address U into


256 comma output type equals bytes 4 so

Viper has this function built in called

method ID which takes a function

declaration and returns its method ID

AKA its function selector so in solidity

they're called function selectors in

Viper they're called method IDs it's

kind of the same thing but what we could

do then is we can deploy this click this

o sorry then we got to do at external at

view I'm just going to uh def get

selector one without the underscore

returns a bytes 4 return re return get

selector one like this save oops sorry

self we'll save it deploy it

oops deploy it get selector one returns

this so now our function selector is

this so if you have an address in a un

256 this is how this would be the

function selector now so anytime you see

this at the start of call data you're

saying hey call The Transfer function so

same thing amount right now starts with

as zero if I pass this into the lowlevel

intera I hit transact it actually fails

because well I don't have the rest of

the parameters ABI encoded right I don't

H I didn't pass in a two or an amount

and Viper is smart enough to say oh well


you didn't pass the parameters so you

fail so that's one way to get a function

selector is using the method ID here

what's another way to get a function

selector well in your terminal you

should have access to this cast command

and cast D- version since you installed

Foundry cast comes built in with Foundry

we can also do is you can do cast Sig

and then type in the function signature

to get the function selector so I'll do

transfer address address comma

256 enter like this and I get the exact

same function selector as I did before

right the exact same one as down here if

I didn't have those parameters right I

got rid of the parameters we would get

the exact same function selector we got

way way way before so whenever we call a

function it gets converted to this hex

data which has the function

selector so if I wanted to call some

other contract I could do something like

at

external uh def call it and I could now

use that raw call thing to call it so I

could say like selector of type bytes 4

equals method ID I could even just copy

this boom and I could say raw call I

would have to pass in like some address


the function

selector and I'd be good right well

almost this would work if you don't have

any parameters but well what if you have

parameters in the function so what we

can do is we can do at external at view

def get data to call transfer and we'll

say sum address sum address will be of

type address and we'll get an amount

which will be U into 256 and this will

return a bytes 100 so how do you get the

exact data in order order for someone to

call this transfer function let's do

self. some address equals 2 and self.

amount equals amount how does the evm

how does Viper know that this is the

exact command to call is the exact hex

data needed to call this transfer

function here so first it does do that

method ID bit so we could say you know

method uh or selector

of type bytes 4 equals method ID

transfer use the signature address un

256 comma output type equals bytes 4 so

we have the selector like this then we

ABI encode and this is where this ABI

encoding stuff comes into play We ABI

encode these input parameters so then I

would just return ABI encode


Su address amount and then we would say

method ID equals this bytes for selector

here sorry not byes for selector oh and

sorry the value must be literal it can't

be a variable here whoops so we have to

do method ID instead of the selector

like that but now if I were to deploy

thisy get data to

call I would of do this address with an

amount one this is the exact hex data we

would pass to call the transfer function

with a raw call which is what we're

going to do now so let's create a new

contract we'll call it raw call. VI and

we're going to have this contract call

or call anything contract without using

the ABI only using our knowledge of raw

call

only using our knowledge of abon En

coding and raw call and lowlevel stuff

you ready you should be all right pragma

version

0.4.0 at license MIT at title ra call at

external

external def call function directly

we'll take an address or uh address to

call address type address do new amount

which will be a u into

256 and then update address of type

address and this will return a bytes to


response and you'll see why and in here

we'll say success will be a bull and it

will be false

response will be a

bytes

equals BBB so an empty bytes object like

this and we'll say success comma

response equals this is where we do the

raw call so the raw call returns success

and a response which is why we're doing

it like this so we'll say call the

address to call the data that we're

going to do is going to be aior

encode the

what is it update address comma new

amount and the method ID is going to

equal method ID

transfer address un

256 comma we'll say max out size equals

32 which is why we have this 32 set here

we're saying the maximum response will

be 32 bytes and then we'll say revert on

failure equals false we could also say

true it's usually better to say true

actually you know let's just say true

we'll say assert success and then return

response so with this code you'll see we

didn't import any interfaces no

contracts there's no ABI we're just


purely building the transaction with ABI

encoding to create that hex data

ourselves what did I mess up given Miss

bull success response given reference

has Type byes

32 oh it's cuz oh I need to set revert

on failure to false if you set it to

true then it doesn't return the success

got it so now that we have this function

let's go ahead let's do the whole thing

here so we have our call anything

already deployed at this address amount

is zero some address is just a blank

address right let me zoom in a little

bit here right amount of zero blank

address here is the hex data we would

expect to be built when we do this so

what I'm going to do now is let's deploy

this raw call contract and we should be

able to call anything update the amount

update some address using this raw call

functionality here right so let's try it

so address to call is going to be this

one so let's copy that boom paste that

in here new amount let's just say 100

update address let's do the same address

pull this up let transact looks like it

went through if I scroll up amount is

now 100 some address has been updated


woo now that is

exciting now

additionally what you can do is you can

go with step further ready check this

out back in my terminal I can actually

use that cast tool to manually create

the hex as well doing the exact same

thing that we did in Viper I can do cast

call data if I do d-el I scroll up a

little bit here I can see it takes the

function signature and the arguments and

it will encode them to create that hex

object for us so let me clear do cast

call data we'll say transfer

transfer address U into

256 and we'll say what's an address

let's use just whatever is in my

metamask here for account 4 boom and for

an amount we'll do 31

337 enter so this is the raw hex here

and now if I copy this right so amount

right now

is so amount right now is 100 some

address is this one if I paste this raw

data into this lowlevel interactions I

hit transact now I scroll up Mount is

now 31337 and some address has also been

changed so this is how we can use this

lowlevel power to call anything and we

also now know why we see this hex data


in transactions so every single

transaction anytime you see something

like this we now know how this is being

generated

how we can make sure we know what's

going on here what the first section is

ETC now I know there was a lot here so

let's do a quick recap of everything we

just learned because yeah there there

was a lot there so we learned first off

about just encoding right we learned you

can encode strings you can encode

numbers you can concat strings you can

do all this kind of clever stuff and

this encoding will give you the bytes

and the hex representation of what these

objects look like in storage and as a

string and as just kind of raw data we

also learn we could encode multiple

things together we can we can combine

them together and we learn that with

this comb and we learn that with this

combination together we can actually

represent we can actually build exactly

what the evm uses to encode and decode

function calls so for example if I have

a function which takes an address and a

un 256 I know the function signature is

going to look like something like this I


then know if I ABI encode this I will

get the function selector which is the

hex data the raw hex data that tells

your contract which function you even

want to call and it's the first four

bytes of the encoding and typically

anytime you send a transaction the first

the start of that transaction to that

contract is going to be the function

selector now typically that's what

happens you know some lunatics could

code their contracts in a way that

that's not the case but that's typically

how it works for Viper and for solidity

as well Viper has a function called

method ID which allows you to give it a

function signature and return the

function selector or the function method

ID whichever terminology you prefer to

use is great once we have these function

selectors we can use that to Raw call

any method we want in HEX data ourselves

and we showed the power of doing that by

having this raw call contract where it

encoded everything itself with ABI and

code with the parameter values and the

method ID as well and then it called raw

call it said call this address with this

raw hex and then some other flags as

well and that's how we were able to call


another contract without the ABI without

the interface Etc the ABI and the

interface under the hood if we were to

use you know how we've done like before

like from

interfaces interfaces import you know my

interface whatever and we say okay you

know my interface add address you know

whatever address here. transfer under

the hood when you do this this is what's

happening Viper is doing the exact same

thing as this so now we know more about

function selectors meth SL method IDs

function signatures

ABI encoding raw calling and so much

more and you can see all the different

flags you can pass to the raw call in

the documentation for Viper here now if

some of this is going over your head

that's okay this is tricky stuff and it

might take you a couple times playing

with it to really get it so if you're

not 100% soaking it in right now that's

okay practice with it in remix play with

it in remix try to see if you can expect

what to get we'll probably have some

quizzes about it in Cypher updraft as

well and just keep plugging

along all right now we're going to learn


how to verify transactions in metamask

and this is so so powerful so that you

don't accidentally sign transactions

that you don't want to sign so you don't

accidentally sign transactions that are

malicious this is how you can make sure

that the call data that you get in your

metamask is actually what you expect now

this is going to be a little excerpt

from The Foundry solidity of Cipher

updraft so there might be references to

Foundry or solidity but it's all

basically the same so let's go ahead

let's follow along here and learn how to

verify transactions in

metamask now we can finally go back to

what we were talking about with metamask

and that decoding the transaction data

and all this weird stuff if we come to a

contract address and this is we this is

a contract that wraps native eth and

turns it into an erc20 token but if we

come to a contract right we hit right

contract let's connect to web 3 sure you

don't have to actually do this just feel

free to follow along with me we got to

open up our mens let's go to aoia here

going to connect here okay cool and we

want to call transfer from right and

let's just add some stuff in here let's


do Source address and you know this this

is probably won't go through because I

don't have any we right now but let's

just hit right right this transactions

metamask is probably to be like hey this

is going to fail whatever yeah sure

whatever but when we get a menam mass

transaction that pops up if we scroll

over to the hex we scroll down we can

now actually start to understand what is

going on here and this is what we always

want to make sure is actually correct

when we're working with our menam mask

and when we're dealing with all this so

what we can do is we can actually copy

this whole thing and pull up our

terminal here I'm just going to make

this nice and big here what we can do is

we can do cast d-el

we hit cast help and we scroll all the

way up there's a command in here called

call data to code to code ABI encoded

input data so if we do cast D- call data

decode like this we can see we need to

pass in a Sig and the call data so

luckily for this transaction our

metamask was smart enough to know that

we're calling the transfer from function

but sometimes it's actually not going to


be smart enough to figure this out so

that's where we are going to need to

match what we expect this to be calling

to to what it's actually calling right

so first off we are expecting this to be

calling the transfer from function so I

can grab this function selector which we

just learned come back here I can do

cast Sig and I'll pass pass in here

transfer from the whole function

signature which What It Takes a address

address and a unit 256 so we'll do

address address

256 and we'll see that this is what the

function selector should be so I can say

okay great the two of these match this

is indeed calling the function selector

that I want it to call okay awesome if

it doesn't match we can happen sometimes

again we can go to something like the

Sam CZ Sun signature database or open

chain. XYZ signators paste this in hit

search and we can see that there's

actually two different functions that

have the same signature one is transfer

from and one is gas prite bit ether with

an INT 128 so what's interesting here is

you can't have a function with the same

function selector so if I actually went

into remix .org let's actually create a


new contract called

conflicting doou right and we'll do a

little little zoom in here

spdx license ENT to

fire contract conflict I made a function

called transfer from with an address U

250 or address High U

256 low U 256 Su public like this and

then I also have a function function

with this one gas prite bit ether paste

it in here Gasper ether in 128 sub

public and I try to compile this guess

what's going to happen compile oh it's

pragma solidity 0.

8.18 this should be an address to and

now I try to compile we scroll down

it'll say function signature hash

Collision for gas price bit ether you

can't have a contract in solidity where

two functions have the same function

selector so in any case we could be

calling one of these two functions on

our this this is where it's important to

actually go through the contract code

and say h okay there could be a couple

different function selectors here let's

make sure it's the one that we expect

right so in any case so this is calling

this transfer from function if this


contract has a gas bit gas price bit

ether it might be calling that but in

any case we know so we could go through

the code right we go through transfer

from okay great there's a transfer from

function that is indeed what we want to

call function selector is working

perfect okay so now that we've verified

the function selector we should also

verify the rest of this stuff so now

that we know what the function selector

is and we know what the function

signature is we can take this whole hex

here and go back into our terminal and

use that call data decode so we can say

cast D- call data decode we can see what

it what we need we need the Sig and the

call data so it'll hit up the Sig is

going to be transfer from and it takes

an address an address and a uint 256

right we just double check that address

address address un 256 sure does and we

can paste in that call data and hit

enter and we can see what this call data

stuff is using for input parameters to

that function so it's our address our

address and then 1000 and then if that's

what we expected so let me reject this

for now go back to right

and that and if that's what we wanted to


call on this function we would go ahead

and put this through this is especially

important when we're using front ends

like for example if I wanted to use Unis

swap right let's go ahead and connect

here to metamask yep connect looks good

go away go to let's say if I was on eth

Main net I wanted to swap eth for so so

I'm on a test n here so obviously

nothing's showing up but when I hit swap

if I was on a real network with real

money what what I want to do then is do

that same process of going through and

checking to make sure that the

transaction that it's sending is

actually the one that I want it to be

sending right so if we want to be

absolutely sure of what our transactions

are doing we can first check the address

we can take these exact steps to say I

know exactly what transaction I know

exactly what function my transaction is

calling so we check the address to make

sure that the contract is what we expect

it to be and then we can read the

function of that contract that we want

we check the function selector that

we're using so that it is so that we

know that it is indeed the function that


we're calling and then we decode the

call data to check the parameters that

we're sending so this is how we can

actually make sure our wallets are doing

what we expect them to

do so now that we've learned a lot about

lowl encoding and ABI and calling and so

much more like I said we kind of cheated

a little bit by us doing a little bit of

copy paste but if you really want to get

to know what these functions are doing

feel free to pause the video and walk

through them yourself of course we have

our token URI but right now it is just

happy right because we have image URI

set to the Happy SVG so of course what

we want to do is create a little at

external function

exter called flip mood now in order to

flip the mood we're going to need to

have some type of State variable like

keeps track of the mood and to do that

we're going to create a little enum or a

little flag so up near the top we're

going to create a new flag mood and we

haven't worked with flags before but if

we look up flag in the Viper docs we can

look up a flag this is how we can create

a new type and we can add in here like

uh you know flag mood happy sad blah


blah blah and we can set variables to

have a type of mood we could say flag

mood we could say it's either happy or

sad and we could say happy sad excited

thrilled jealous you know whatever

amount of moods that we want we could

just as easily do a un 256 but this is

kind of a more a better way to write

this out so we'll say flag mood and then

we'll create a a storage variable this

will be in storage called token ID to

mood this will be a public hashmap U

into

256 mood so we will map the token ID of

each nft to a specific mood so when we

call Flip mood we're going to have to

pass in the token ID which will be of

type un 256 but we don't want anybody to

be able to flip the mood we only want

the owner of the nft to be able to flip

the mood so the ERC 721 contract comes

with the function built in so we can do

assert erc721

doore is approved or owner message.

sender token ID so this is this is a

function that will check if whoever is

calling this function is approved or is

the owner then we could say if self.

token ID to mood of token ID equals


equals

mood.

happppppy I'm going to hit tab because

chat GPT got itself that token

ID to mood of token ID should then be

sad otherwise make it happy and we're

also going to need at

external def mint

nft and we'll say do the same thing

token ID unit 256 equal erc721 doore

Mint or we could do safe mint uh

actually yeah we are going to do safe

mint message.

sender oh my gosh I'm losing it y'all

token ID equals erc721

counter like this we'll say ERC counter

t721 counter

equals uh token ID + 1 then we'll say

self. token ID to mood of that token ID

we'll set the default to be mood.

happppppy and then finally safe mint the

token ID with no data that looks pretty

good to me let's write a little deploy

script for this oh we already have a

deploy script oh nice okay cool mood nft

to deploy we'll say mood contract equals

mood nf. deploy then we'll just do mood

contract. mint uh does the def mint nft

NOP mint

nft then print F token URI of mood


contract. token U of zero so let's try

this out MOX run deploy mood nft we get

a token URI that looks like this okay

great that looks pretty data 64 encoded

uhhuh okay I can even pretty print this

cuz I'm brave let's see if this image

looks

correct boom we have a happy smiling

face now what what though if we went

ahead and did mood contract. flip mood

of zero we reran it let's try this now

so this is the new token U paste it in

here get this paste up here it's still

sad so did we not flip the mood look at

our flip mood flip mood it's happy make

it sad oh of course because we forgot to

switch it because we actually forgot our

to to update our token U of course um

let's do here we go CHT got it if self

the token ID to mood token ID equals

mood. sad make it sad now let's try one

more time great let's grab this boom

paste it in grab the image boom and now

it's s so and the final bit that we

should do in this in here as well is we

should really update our our nft here so

that it exports all the functions of an

ERC 721 but remember we cannot export

token URI CU we have created one ourself


what we can do is we can just cheat a

little bit typically AIS work great at

that uh but what we're going to do we're

going to come in here go to SRC mood

nft scroll down there's also some nicer

syntax in here and just grab this whole

exports and paste it right here Tada you

can see here that we didn't use token

URI we also didn't use safe Mint or set

Minter this is how you can kind of make

sure that you know you're not exporting

some functions as well just kind of com

in them out like that so nice we have

successfully created and deployed a

smart contract whose mood is updated

where where the nft is 100% onchain

because we're using very clever Bas 64

encoded token your eyes you should be

incredibly excited with

yourself this leads us to the final

Workshop of this section so you've now

learned what an nft is how to make one

how to customize it so Workshop number

two my friends remx in nft is going to

be pretty straightforward deploy your

mood nft to your locally running chain

flip its mood and view it in metamask we

learned how to deploy this right we

literally just did right MOX run deploy

mood nft we also recently deployed to


Anvil with the basic nft so now deploy

to a locally running chain flip its mood

and view it in metamask you can also

work with your tenderly virtual network

if you'd prefer but that is your task

here and your second part of this

Workshop is also to get your test for

this to 80% test coverage now in the gab

repo here we have written some tests for

you test unit mood if you want to go

check that out that can you can use that

as your starting point we've also

written some tests for the subl lesson

as well if you want to look into writing

some tests and playing around with the

subl lesson that we wrote for this

section too so those are your workshops

pause the video please please please

work on the workshop and we'll see you

very

shortly all right welcome back did you

do the workshops well if you didn't the

only person you're cheating is yourself

so I hope you did and as always you can

come look at the G repo to see some

answers see how weed did some of these

we don't always do all the workshops but

you can also jump into the discussions

jump into the Discord the discussions


wherever you want to go to talk with

other people who are working on this as

well but with all that being said we've

just learned a ton so let's do a little

refresher on everything that we learned

before moving on to the next section so

first we learned what an nft even is and

we learned that it's this

very similar to an erc20 it's an ERC 721

it's just a set of functions that you

have to Define in a contract for it to

be considered an nft or an earc 721 and

typically we can think of these as art

or digital Collectibles or some type of

unique asset that isn't fungible like an

erc20 is fungible one is IND

indistinguishable from another token

whereas with nfts each token is unique

or can be or should be unique we built

and deployed a very minimal basic nft

with a very cute adorable puppy as the

as the main image for it we had some

hard time viewing it in metamask so we

used a panata Gateway in order to view

it built a very basic deploy script as

well to deal with it then we built a way

kind of cooler Dynamic nft where all the

metadata was stored directly on chain

because we used an SVG right we used

this SVG that we encoded and and we


placed the whole thing on chain now we

did some kind of fancy smancy array

manipulation which we didn't really go

over but I don't I didn't really think

it was going to be important for me to

like take two hours to go over how and

why I did this array manipulation that I

did but you can feel free to pause the

video and you can go through it if you

would like to do so however with this

fancy smancy array manipulation we did

however go over all the functionality

all the functions that I used in that

weird array manipulation stuff and we

learned a ton about ABI and coding we

learned that anytime any value is worked

within the evm you work with its hex

representation and we learned how we

could get that using ABI and code and

then also decode it from the hex

representation with ABI decode we took

that knowledge and we extrapolated it

one step further with this call anything

contract where we learned that we can

actually call any contract that that we

want just by knowing the correct hex or

raw data to send to it or if we know the

function signature itself we can

actually build the raw hex data


ourselves in order to call those

functions so we learned what a function

selector was which is going to be this

function signature encoded and the first

four bytes of it so the first four bytes

of the function signature encoded and

the function signature is just the

function name and then the parameter

types inside these parentheses we

learned that we could get the entire Tex

data that is sent in any transaction by

encoding all the parameters with the

function selector and I know that if I

go to Ether scan or any block Explorer

right I could look at pretty much any

block and we'll we'll look at any of the

transactions in here I could see a

transfer transfer safe transfer great

let me look at the safe transfer I can

scroll down more details

decode input data excuse me uh view

input as original I can look at this and

go ah this right here is probably the

function selector for this transaction

for whatever this transaction was I can

even go back ether scan actually even

gives me this function save transfer

from address from address to U into

256 I could even take that and confirm

that the first bit is the function


selector I could say cast

Sig paste this in here get rid of the

the names and only keep the types enter

I see 42 4284

2e0 e and I can go back to the original

here and I see that's exactly what we

get here and that is the function

selector we then took all of that

together and put it into this raw call.

VI where we learned we could even call a

function directly without the interface

without the ABI just by passing in the

function signature which turns into the

function selector so we could even just

pass in you know the function selector

right here and that would work as well

which is incredibly powerful and then

finally we finished out our custom token

URI here we added a flip mood function

with a new flag which is essentially

just an Edom or just a new type it's

like okay it's either it's happy or it's

sad um we created a mapping for it and

that's how we were able to flip the mood

if you've gotten this far if you did the

workshop which if you didn't do the

workshop shame on you then you should be

incredibly proud of yourself because

this is hard stuff but you've now


learned how to deploy an nft what an nft

is how to work with nfts how to encode

and decode and do all this amazing

powerful low-level stuff you should be

very proud of yourself and now is a

great time let go for a walk go to the

gym or go get some ice cream because

you've just completed the nft section of

this course take that break and I'll see

you

soon in this video we are going to show

you how to algorithmically trade and

rebalance a portfolio not only will we

show you how to do it with fork test but

we will also be showing you how to do it

live on ZK sync with $1,000 ofy actual

money in this tutorial you will be

playing the role of a hedge fund manager

and you need to rebalance your portfolio

if you don't know what that is no

worries we'll teach you you will deposit

your money in a to gain a 5% or more

interest on your usdc additionally

deposit ethereum in there to also gain

interest on your ethereum realize your

target allocations aren't there so you

will automatically programmatically with

a click of a button rebalance to pull

your money out of a swap them on Unis

Swap and then redeposit them back in


Unis swap all in a single pythonic

script now this is an excerpt from the

brand new cyphon updraft Advanced Python

and Viper curriculum and if you want to

become a smart contract developer or if

you want to just Learn Python while

learning smart contracts along the way

with this amazing language Viper then be

sure to head on over to cphon updraft to

take it with that being said let's go

through this excerpt teach you how to

rebalance a portfolio programmatically

and begin your Quant trading in web 3

career let's begin

all right welcome back to the moccasin

or the Viper in Python full course I am

incredibly excited for you in this one

because if we scroll on down let's go to

Advanced moccasin moccasin defi

algorithmic trading because in this one

you are not going to write any smart

contract code that's right none you're

not going to do any smart contract

coding you are going to do scripting and

we are going to unlock the power of Defi

and the power of scripting and

algorithmic trading and automated

trading and even if you want to do AI

trading whatever whatever you want to do


we are going to give you the scripting

power in this section to do so and if

you want to get into defi if you want to

get into algorithmic trading if you want

to get in automated trading AI trading

whatever these are going to be the tools

that you can use to do so and here is

the final GitHub repo that we're going

to be working with here you can see

there's no Source there's no contracts

folder there's only scripts and tests

and abis and let me show you what we're

going to be building here we're going to

teach you how to balance or portfolio

using a and Unis swap which you might

have never heard of and that's okay if

you've never heard of those I'm going to

give you this super super super fast

explanation of of those in this section

however there's tons and tons of

information for you to learn so I'm not

going to be doing defi justice but I'm

going to be giving you enough

information so that you can actually

take this knowledge run with it and

maybe build your your own di scripts

maybe build your own di protocols maybe

build your own Financial applications in

the blockchain space in my opinion what

we're about to show you is what makes


Smart contracts and what makes

blockchain so fantastically fantastic

all this money stuff all this D5 stuff

makes the world more fair more

accountable and just phenomenally better

so it's both this section and the next

section where we teach you how to build

your own stable coin to me these are the

the the just the coolest things possible

in this industry now what we're going to

be building this algorithmic trading

this portfolio rebalancer it's really a

portfolio rebalancer it's technically

doing a little bit of algorithmic

trading as well if you're unfamiliar

with what portfolio rebalancing is no

worries we will give you the very high

level explainer but again there's a lot

of financial terms here and I'm going to

be using the much easier terms here and

this smart contract this autonomous code

on the blockchain that's going to be

doing this portfolio rebalancing that's

going to be doing this money stuff is

known as a defi smart contract or

decentralized finance and the protocols

and the smart contracts that we're going

to be working with here are known as

defi smart contracts so we're going to


be working in this thing called defi so

defi stands for decentralized finance

and it's kind of this catch-all term

that we use for smart contracts that do

Finance now it's kind of a catch22

because some smart contracts aren't

actually decentralized but they still

consider themselves defi that's that's a

little bit of a nomenclature debate but

I digress so defi stands for

decentralized finance and it's

encompasses all these smart contracts

that can replace traditional Finance

applications for example in classic

Finance you have a bank you deposit

money in you get an interest rate so for

example you know here's some here's a

PDF from Bank of America I don't know

why they're using a PDF here but some

standard pricing for bank accounts

you're going to get

.1% interest on your your money which is

a terrible interest rate nerd wallet's

going to tell us some better ones okay

maybe or they're making you know

between around 4% as of recording

another around 3 or 4% you know 4 3%

blah blah they're making interest rate

on these on putting dollars into these

bank accounts in defi there's several


different applications that do this

banking stuff where you can deposit

instead of dollars you deposit

cryptocurrencies and tokens and one such

application is a and that's what we're

going to be looking at today so if we

open the A app and can connect my wallet

browser wallet sure connect I can go to

you know one of these networks maybe

like ZK sync for example and I can see

different interest rates on different

tokens that I can supply so for example

usdc I get an interest rate of

4.45% and this already is kind of one of

the cool things about defi usually the

yields the interest rates are a little

bit higher usdc this is another dollar

Peg stable Co coin so one usdt is worth

a dollar but we can see we can also make

interest on our ethereum so we could

deposit ethereum into a just like you

deposit dollars into a bank then the

stock exchange analogy equivalent would

be something like either syn swap or

Unis swap so if look up like Unis swap

Unis swap is an app that looks like this

and basically you just swap tokens right

you swap tokens much like on a stock

exchange or something like a Robin Hood


or different apps where you can buy and

sell shares you can buy and sell tokens

for each other so for example I could

say hey I want to swap you know my usdc

for uh eth or the other way around and

you can do this on different chains so

on the ZK sync Network sync swap is one

of the most popular ones at the moment

which is exactly like Unis swap here you

do a little swapping here you swap

tokens between each other and this is

how you can buy and sell tokens for each

other what this is all to say going back

to what we're trying to do is we have

50% of our money in usdc 50% of our

money in eth we want to get 30% and 70%

and we want this inside of a gaining

interest as well so we are going to play

the roles of portfolio managers building

some scripts to automate this process of

what's called rebalancing rebalancing

your portfolio this is a a very common

thing in finance to rebalance your

portfolio and it might seem pretty

trivial but it's a really really

important part of your process so we're

going to build some scripts that will do

this automatically because I'm not

running around clicking a whole bunch of

buttons and to demonstrate this what our


final script is going to look like I'm

going to show you this with real money

yes with real money on the actual casing

Network on actual with actual eth and

with actual dollars so I'm connected to

the a application with my menam mask

here where I have a wallet where I've

loaded this up with a couple hundred

bucks to show you this right so in a on

a right now if we scroll down I've

deposited $180 worth of eth and $60

worth of usdc and right now this

actually is looking pretty close to that

7030 split that we have however in my

metamask on ZK sync I've got another

$160 of usdc and another $30 of eth that

we're not going to deposit but another

$160 of usdc so if we do a little so if

we pull up the calculator right we have

plus

68 and yeah I know there's some sense

but we have 228 so in total we have

around 228 usdc token and only 180 eth o

that is not our Target portfolio balance

right cuz we want to get we want to have

what that's right we want to have 70%

eth and 30% usdc right now we actually

have way too much we have way too much

usdc right in our metamask and in a we


have 228 and this right now isn't making

us any interest right on a we're making

4 and a half% interest on our dollars

that's that's awesome and we're making

3% on our eth what I can make % interest

on my ethereum that's insane right so I

have the entire code base for what we're

going to be building up in my vs code

right here if we go to scripts we have a

couple different scripts in here we have

deposit and rebalance being our main

script what it's going to do it's going

to run a deposit script it's going to

deposit all of our money into a it's

going to rebalance it's going to take

the money out trade them rebalance it

and then deposit it back in so let me

even run this script

just to show you right so remember again

this is our starting amounts here and so

we want to see this rebalanced where we

have way more eth than we do usdc and

you know I'm I'm even just going to

supply all the usdc right now to show

you what it looks like from the UI right

so I hit the supply button approving

usdc going to change this to the max

amount view the details aha I can see

the actual call data here verify third


party make sure this is the actual

address that I want to use I verified

that this is the correct pool from the a

GitHub and from the a documentation off

off camera I did that a little bit so

we're going to go ahead we do next we'll

call approve and this will take a couple

seconds as it approves and goes through

then I'll call Supply I'll make sure

that the address that I'm sending this

to is correct I will also make sure that

the hex data is correct using the tools

we were worked with already right so I

might view this on block Explorer go to

the a docks look for the scroll down

look for the addresses paste this

address in here uh look for the ZK sync

Market CK sync 78e let's look for this

address

78e okay I see it right here boom let's

copy this address let's make sure it's

the same yep it's the same address cool

that looks good

so now I feel comfortable to come back

here I've confirmed the address I

confirmed the call data off screen as

well I can now confirm and I can be

happy that this is going through now

clicking all these buttons pressing all

these approves and and verifies and


checking the call data and all that

stuff is why I would much rather do this

in a script because if I have to do that

every time I just want to deposit money

well what happens when I want to pull

the money out trade it redeposit it do

it with multiple tokens it's going to

take me forever screw that I don't want

to do that anyways now that we've

redeposited it it say all done you've

supplied the tokens I can add this a

token I'm going to skip that for now

you'll understand a tokens in a minute

but now if I refresh here now we can see

okay we've got $229 in usdc in ZK sync

and we've got $180 in eth on ZK sync in

a here we want to rebalance this so I'm

going to run my script where I have this

money actually stored as a wallet item

and what I can do is I can run MOX run

and I can grab my script here deposit

and rebalance D- Network ZK sync D-

account I have an account called small

money I'm going to get this output the

transactions will run on an actually

broadcast on this the transaction run on

this will actually be broadcasted

transmitted yes I know enter my password

for small money and it's actually going


to get my balances and send these

transactions so first it's going to

deposit everything into a it's going to

check my current percent allocation it's

saying up you're at

56% and

43% but the target is 30 and 70 okay we

got to fix that get a couple warnings

from some transactions that we're going

to send zync that's fine but now if we

scroll down we mined some blocks we did

some

transactions these transactions were to

pull all of our money out of a then it

said time to swap it's going to swap 100

usdc for this much we it does this on

Unis swap broadcasted those

transactions and then it said okay

depositing the usdc into the a contract

deposit them back in deposit deposit

deposit then depositing The Ether back

into a deposit deposit deposit get some

data about our deposits and then check

of the final allocation we're at 30.11

and 69.8 N which is close enough to what

we wanted and we just ran some

algorithmic trading we traded

algorithmically we rebalanced our

portfolio and then we redeposited into a

all in one single script so now if I go


back to the UI I refresh I can now see I

now have $284 in we in wrapped ethereum

in ethereum in a and 122 in usdc hitting

my 30 70% Target portfolio allocation

all of that in one command which is

incredibly exciting and that's why I'm

so excited to show this to you now you

do not have to do this with real money

you do not have to do this on a real

Network we are going to be showing you

how to do this on a forked Network

you've worked with fork networks you

know what forked networks look like you

could also do this on a tenderly virtual

Network and actually I highly encourage

you to do this on your tenderly virtual

networks because you will be able to to

really see and feel what it's like to do

these transactions and move things

around and see the contracts with the

values on your tenderly UI so this is

what we're going to be building we're

going to be building you some

algorithmic scripting to do all of this

in Moccasin but additionally we're going

to be teaching you how to do this using

a notebook as well to play around with

this so that you can kind of test and

write these scripts while you Tinker


with the blockchain so incredibly

exciting I'm super pumped for you here

let's go ahead let's get started working

with this and let's jump in because you

are going to become asset managers who

have the power of algorithmic trading so

let's get

started and of course the full code for

what we're going to be building is in

the GitHub repo associated with this

section so let's go ahead let's get

started here we're in our MOX CU folder

going to go ahead and clear it out let's

make a new directory called MOX

algorithmic trading CU code MOX

algorithmic trading CU or file open this

folder into a new window here as always

we have our trusty moccasin installed

already so let's go ahead do Mox and it

--vs code d-p project like so and let's

get rid of all this stuff we do not care

to see here command click and delete

bada bing bada boom okay clear so as

always let's come to the read me let's

delete everything in here and do a

little bit of what do we want to do

scope it out well first we want to be

able to

deposit into a then we want to withdraw

from a trade tokens through Unis Swap


and then redeposit into a remember a is

going to be our bank account right

that's how we're going to create

interest yield so most of the time we're

going to be passive investment managers

where we decide hey we want to do 70%

eth 30% usdc stick it into a make our

percentage yield and then every couple

of months rebalance the portfolio so

that we're still at that 7030 Target but

anytime we need to rebalance to make

sure we're on that 7030 Target Mark we

pull the money out of a we do a little

swapping and then we deposit it back in

we probably could also directly sell

these things called a tokens but you

know this is for the learning okay so um

I I will say there are probably more

efficient ways to do this but we're

doing this for the learning so that's

what's that's what's important here now

to help us build all this we obviously

can 100% do this on a forked Network so

there's a couple of ways we could get

started here

so let's first set up a forked Network

so that we can at least start testing

this as if we were on ethereum so what

we're going to do is in our MOX in.ml


let's go ahead let's delete everything

let's just create a new network called

networks. e forked we'll say forked

equals true give it a URL this is where

we could go back to our friends at

Alchemy or we could do tenderly as well

but I'm going to use alkaly I'm going to

use alchemy we're going to use we're

going to

configure ethereum mainnet being on Save

we're going to go from spolia then to

mainnet we're going to copy this address

going to create a

EnV mainnet RPC URL equals paste that in

like so make sure that the EM is in the

dog ignore it sure is okay great main an

RPC URL which means I can do main an RPC

URL the URL here this is not ZK sync and

because I want to be testing this I can

also say

default account name equals Anvil one I

can do MOX wallet list great I have

Anvil one and I'm also going to do a

unsafe password file equals anvil one

password file nm. AMV let's set that as

well say Anvil one password file equals

Tilda for home.

moccasin

slash

unsafe passwords SL Anvil one and I can


check to make sure this exists by doing

cat paste it in and I will see the word

password printed out mean meaning that

in this file the word password is in

there great and that's exactly what I

wanted so we're going to be running on

this forked Network on the ethereum

network to get started and let's create

a little gript here called deposit. pile

let's get started with the deposit

script first so in order for us to

deposit into a let's go to a let's open

the app in order for us to deposit into

what are we going to need well first

we're going to need some uh money we're

going to need some gas right we're going

to need some gas first so before I even

start running writing the deposit script

I need to write a little setup scriptor

setup

script.py and in this setup script we

can do some Network checks we could say

hey if we're running this on a test

Network or if we're running this on a

fork Network well let's um let's give

oursel some fake tokens right so so

we're going to have to do a little bit

of work to give oursel some money and


tokens and some other stuff right

because we want to test these scripts so

we need to have a account that has some

money and no it's ridiculous to ask you

to go out and like buy tokens to run a

test like that's so stupid so we're

going to give oursel the money by using

our wonderful testing tools here so I'm

going to write a new script called defa

setup script here and I'm going to have

this return us actually a whole bunch of

stuff a tle of ABI

contracts ABI

contracts and we haven't talked about

these that much yet so I will in just a

second so from bo. contracts. Abi Abi

contract import ABI contract this might

be in a different location depending on

when you get started and I'm going to

hate these yellow lines so I'm going to

do a little UV ad

moccasin in here and I can either select

yes here or directly update this

e little python environment here to Here

and Now those go away and I need to say

from typing import import Tuple import

tupo so we're going to be returning four

ABI contracts now these ABI contracts

are basically just a class to help us

call different contracts on a blockchain


if we don't exactly know their source

code and you'll see why we need this

very soon as well so first off let's do

a little print we'll say

starting setup script and what we want

to do is a few things we want to First

give

ourselves some eth then we also want to

give

ourselves some usdc and we right so if

we're on a test net we want to start

with these so we can actually test it if

this works right because if we don't

have any eth and we don't have any usdc

or weth well when we run these scripts

it's just going to say you have no money

so uh cool and that's not good so we

need some eth USD C and some we so we

first want to get those tokens based off

of their contract addresses and well we

actually know how to work with contracts

in mockasin what we can do is we can say

networks.

efor do contracts

we could say usdc equals address equals

and pass in the address here now I'm

going to go ahead and cheat and I'm

going to tell you I already have the

address for eth mainten net it's going


to be this address here if you want you

can Google it you can do like usdc

address eth mainnet and this looks

correct from ether scan it might be a

good idea to double check it with

another place come back y yep that looks

right to me so this is our usdc address

and we should also have a we address so

we is actually wrapped ether so most

protocols in defi work with Native

ethereum as a token instead so you know

how like if you open your metamask you

see like you know tokens eth or actually

better yet let's go to let's go to

ethereum network you have like your

native eth well most applications prefer

you using we instead of native eth

because it allows for composability

between the other tokens native eth is

kind of confusing for applications so

what they do instead is they wrap your

eth inside of a token so this is kind of

a a weird abstract concept to grasp it

doesn't really matter just know that one

wrapped ether or one token ether is

equal to one ether there the they're the

same thing but it does have an address

and I have the address for this as well

I'm p set in here so I have those two

addresses and what I want to do now is I


want to Mint myself some of each of

these I want to Mint myself some fake

usdc and I want to Mint myself some fake

we as well as some eth so let's start

with some eth first but let's only mint

it if we're actually on like a forked

Network so we can do from moccasin doc

config import import get Active network

and we could say active Network equals

get Active network then we can say if

active network. is local or forked

network network I know it's a a mouthful

we can say if we're on a local or Fort

Network only then should we give oursel

fake money right because if we're on a

real network uh we we shouldn't do that

so let's create a new little function

def underscore add eth balance like this

and all we have to do is import boa and

we just call BOA env. set balance just

like we do in our tests

boa

.oa and some starting eth balance so

we'll say starting eth balance equals

we'll say a th000

E18 right so we're doing this int here

to make sure this is an integer since

eth is in terms of we we're doing a

th000 E18 this just represents 1,000 eth


so if we're on a local network we're

going to give oursel a th eth to start

and let's also do

deore add token balance and let's have

this take in a couple things let's have

this take in the

usdc the we and the Active network like

this so that down here we'll also call

add token balance and we need to pass

the uscc we and Active network so for

uscc this is where we can do that active

network.

manifest named usdc you can do the same

thing for weth copy this paste it in

here now we can say okay we'll pass the

usdc in here we'll pass the weth in here

and we'll pass the active

Network in here as well if you're

working with the GitHub

repo you'll notice that for this script

where you're being a little bit more

strict with our typing right we can see

we added types to everything um that's

optional if if it makes it more readable

for you I encourage you to do so for

myself when I work with big code bases I

really really like adding types so but

up to you so we're going to pass these

in and in our ad token balances we want

want to Mint oursel some fake usdc and


some fake

we now let's start with we so this we

contract if you go to the contract this

wrapped token this wrapped we if you go

to WR contract it has this deposit

function and essentially what this

deposit function is is you deposit some

native eth you deposit one native eth

and it will give you one native we this

is how one we token is always worth one

eth is because you can always deposit or

withdraw eth from it right so for

example let's say I have one eth I come

to this contract I call the deposit

function I would deposit my one e into

the contract Boop deposit the one eth in

here by calling the deposit and then I

would get given one we that I can go

around and do whatever I want with

whenever I'm done with my one we what I

would do is I would deposit this back in

by calling the withdraw function this

would essentially delete or kill that we

and make it so that there's zero we and

I would get printed out I would get

given back that one eth that I stuck in

the contract originally so this is how

the we contract essentially works but in

order to do that on this contract there


is a deposit and a withraw function

deposit to deposit eth and get we

withdraw to essentially deposit we and

get eth so I need these functions and as

we know how do we call functions on a

contract well we need the address and we

need the ABI or you just learned you

technically don't need the ABI you can

work with function selection you can

work with function selectors and

signatures but uh in Python it's still

easier to just work with the ABI so

we're going to work with that instead we

could 100% do raw calls and build our

transactions ourselves in our python but

uh we're not going to do

that so what we can do is we can use the

MOX Explorer functionality so moccasin

has us built in Explorer functionality

if you do MOX Explorer you get a list of

just a few options that you can do as of

now what it can do though is it can

fetch abis from ether scan at the moment

it's only ether scan fetch abis from

ether scan and save it to your local

directory so in my moccasin Doo if I go

to

M.O what I can do is right at the top I

can do networks.

contracts this will be the default


contracts objects I can say weth equals

ABI equals

abis we. Json and what I can do then is

I can say Mox

Explorer get or fetch paste the address

of we in here say--

saave uh D-

name we and right at the top in my

project I can say save ABI path equals

abis I'll make a new folder in here new

folder called abis and now when I run

this command it's going to reach out to

etherscan at this address say hey give

me the ABI for this contract and then

it's going to save it with the name we.

Json in this ABI folder so I hit enter

running explore command as of today

fetching only works with ether scan

style explorers saving I to wet. Json

ABI saved and since we didn't give like

an explore URL it just defaulted to

ethereum mainnet which works fine

because we just need an ABI the ABI of

the contract is going to be the same

across all networks but boom so now we

have this w. Json ABI locally we can

assign that ABI to the we contract

address and call functions on it very

nice so this manifest named when we call


it on we what it's going to do it's

going to look in the MOX in.ml it's

going to say okay what network are we on

it's going to grab the address based off

the network and then it's going to

assign the ABI based off of the ABI here

nice so now that we have the we contract

and it has an ABI assigned we can just

do we. deposit and let's give a starting

we balance let's say starting we balance

equals

int8 so we'll just do a single we here

and we'll say value equals starting with

balance CU When you call the deposit

function you're just passing a value and

this will give us some we token we can

even do a little check we could say uh

print starting balance balance of we and

then do a little have this be an F

string quotes here we'll say we. balance

of bo. env.

eoa and then paste this line again

underneath and say ending balance of we

W that balance of and now I could even

do a little def moccasin main down here

setup script oh this should be Fork

whoops let's run that again okay great

um starting balance of weth zero ending

balance of weth is this cool so we are

successfully minting oursel some fake we


great let's do the same thing for USC

and I'm going to delete these delete

these lines

here now USC is a little bit more

complicated so I'm going to do some

stuff just roll with me here um so the

usdc contract is for lack of a better

word very centralized if we go to the

usdc address eth main net click the

contract go down to contract this is a

proxy contract which is something you'll

learn in a later section if you click

right as a proxy we scroll down you can

see a lot of these functions here like

configure Mentor uh initialize mint

pause uh remove Minter uh transfer

ownership Black List so usdc is actually

owned by the circle team and they have a

lot of governance utilities that allow

them to restrict who can use it that

allow them to mint more tokens remove

tokens Etc so we can kind of use that to

our advantage actually by mocking

pretending to be the owner and minting

oursel some usdc so what we can do is we

can say with boa do. prank just like our

test usdc do owner because this contract

if you do read as proxy it has an owner

where is it an owner function right so


we can pretend to be the owner and what

we'll do is we'll call usdc do update

Master minor and we'll send it to our

address so we'll say our address equals

boa.edd c.

configure M I promise you these are

functions on the uscc contract say my

address and we'll give oursel a starting

usdc balance equals we'll do int 100

E6 so we'll start with $100 now unlike

pretty much every other token in the

world usdc has six decimal places why I

don't know uh that's just what they

decided to do so yeah this is why

whenever you work with usdc you'll

always see like E6 six decimal places

instead of kind of the traditional 18

that most other tokens and values have

but sure you know they can do whatever

they want to do so uh uscc do configure

Minter oop excuse me our address

starting USC balance then we'll do USC

do mint so this line gives us the power

to be the master Mentor then we

configure oursel to be a regular Mentor

as well because the master Mentor for

some reason isn't also a regular Mentor

but then we can call USC

our address

and the starting USC value like so and


so right here we should be able to do a

print

usdc

balance before so make this a little

print F we'll say USC oh thank you get

up co-pilot then we'll do UCC balance

after and let's run this as well uh uh

we oops before we run this we need to do

MOX

Explorer get and we need to get the ABI

here Mo explore get-- saave d-name

usdc and it should be saved to usdc

dojon and it sure is wonderful and now

if we run MOX run setup script networked

eth forked we contract has no attribute

balance bance of H so let's look in our

us. Json let's look for balance of did I

spell balance of wrong balance of

balance of USC ah because in our

moccasin

Doo we did not give our USC an ABI so

we'll say usdc equals ABI equals ABI

usdc

dojon let's try this again and there we

go usdc balance before usdc balance

after lovely so we've given ourselves

some fake money let's go ahead and start

learning how to deposit this into a oh

and actually we don't even need this


Active network bit here so let's go

ahead

and now something important that I want

you to take note of as we continue to

build our script you know running a test

to make sure it's working is going to

get longer and longer and this is where

this is where running minimized tests

can be really really helpful but as

we're kind of exploring here we're kind

of doing a lot of tinkering right we're

tinkering we're seeing what works we're

seeing what doesn't work but every

single time we make a call to our node

right every single time we run the

script we're making a bunch of API calls

to our node so if we go to metrics in

our Alchemy let me do a little refresh

here we make requests to our Al note

right so if I scroll down I can see this

huge jump because I just recently did a

whole bunch of requests and depending on

how good our subscription is we could

end up running into limits right we

could end up running into usage limits

by sending too many requests or two big

requests so we're actually going to do a

little pivot here so we're going to

switch from working with this on as a

script to building our whole script in a


i p y andb notebook a Jupiter notebook

this is similar to the Google collab

book collab that we did way way way way

back at the beginning of the Python

curriculum here so we're going to be

doing we're going to be moving from here

to ipy ipynb so I'm going to create a

new file called

notebook.

iynb and this way as we test and build

our scripts we don't have to rerun this

same commands over and over and over

again and make all these API calls to

our Alchemy node and potentially run up

our bill right we we don't want to do

that we want to be a little bit more

fiscally responsible with our nodes here

so since we created this ipynb folder we

get this little blue notebook logo over

here and if not we should look up the J

jupter

notebook extension you should have this

installed if not um this is how we can

run all these jupyter notebook stuff is

you have these these installed with it

so once we have this set up we can go

ahead first thing we want to do is

select the kernel we'll select python

environments we want to choose that


venv and since we are going to be

working with moccasin if you haven't

added it to thatv EnV you will have to

add it with UV add moccasin and then

oops and then UV sync as well to make

sure it's all sync up here once you've

added the kernel once you've selected it

as the actual kernel you can now hit

this little code button and we can get

started working with moccasin in a

notebook so if you go to the moccasin

docs there is a how-to guide on jupyter

notebooks on the left hand side so you

can say from moxin import setup notebook

I'm going to go ahead and copy that

paste it in here press the little plus

button to set up the notebook here I'm

going to hit shift enter to run the cell

and create a new cell we can also press

the little code button to create a new

cell now that we have this set up the

easiest way to now make sure we're

working with the correct network is

we're going to add to our

moxino default network name equals eth

worked come back over here let's create

a new code section we'll do from

moccasin doc config import get active

Network like this we'll say Active

network equals get Active network and


then we'll print active network. name

like this we'll make sure we restart

terminal here we'll run this might take

some time and then we'll run this and we

should see eth fork printed out okay

lovely now that we have that set up

create a new code section where we're

going to add all of our set script stuff

here I'm actually just going to copy

this whole thing going to paste it in

here and at the bottom I'm just going to

run Mox and Main like this run the whole

thing starting setup script USC balance

40 usdc balance after 1,000 so this

should have set up our

usdc and our we rate like so we should

then be able to run these actually let's

create a new code section run these two

lines let's go ahead and run them and in

a new code section we should be able to

see usdc do balance of boa env.

eoa play and we'll see we do inde have a

balance we should be able to do we.

balance of

boaa we see a balance there too lovely

so this is how we're going to kind of

play around here and if you do not like

like the notebooks you don't have to use

the notebooks instead you can just kind


of keep building a script I'm going to

be using the notebooks here these are

kind of like a giant python shell if you

ever like stop and need to come back

what you would do is you would just

scroll to the top You' hit run all and

uh if you try to run all actually while

you're in the middle of this you might

run into an error saying hey uh you

can't set the network again you can't

Fork again um so we're going to not run

all I'm actually going to comment this

out for a second now I'm going to hit

run all and you would just run

everything right so in any case oh and

we gave oursel uh another 1,000 usdc and

that's fine so now that we kind of have

our tinkering environment setup we can

kind of keep writing our scripts we can

kind of keep tinkering keep playing with

this and eventually we can add these

back over to our scripts over

here let's learn how to actually deposit

into a now and so I'm going to run this

cell right remember and this means I now

have USC and we that I can work with so

if I just type USC here I'll get this

printed out here because I ran this cell

up here which means I basically executed

these lines in my current python


environment so anyways now that we have

that let's learn how to deposit into a

we can go over to a.com go to the

developer documentation tab to read more

about how a actually works and how we

can deposit and work with it so what we

want to do is we want to take our usdc

in our weth and we want to learn how to

stick it into a and if you want to pause

and read through the a documentation

definitely be sure to go uh feel free to

do so a is a phenomenal protocol really

really important if you want to become a

badass smart contract developer because

a influenced a lot of the defi

applications that are popular today

and it's currently one of the largest

applications according to defi llama

this is a website that keeps track of

total value added into different defi

applications with a being deployed

across 13 chains having almost $20

billion in it as of recording which is

definitely impressive so if you want to

pause read the documentation feel free

to do so but essentially we just want to

stick money into it so how do we stick

money into it well if you scroll down to

Smart contracts
you can see a list of of a lot of the

most important contracts that the a

protocol works with the first thing that

we want is we want to get the pool

addresses provider so this is a contract

that tells us the address of the

contract that we're going to use to

stick money into so a little bit

confusing but this is the first contract

that we're going to need to work with

and this has a function if we scroll

down to the view methods let me zoom in

a little bit too called get pool let me

look for get pool get pool and it

Returns the address of the latest pool

proxy contract so the pool address

changes from time to time so they have

kind of this admin address that will

always have the most up-to-date

addresses of the pool address and the

pool is where we're going to be

depositing our money so essentially we

need to call get pool so we know where

to send our money so the first thing we

need to get is the address of this so if

we scroll down to uh

dashboard addresses we can on the

ethereum V3 main Market we can look for

the pool addresses provider boom right

here it's even marked on ether scan and


we can grab this address and we can

stick this into our MOX in.ml so in here

eth for we have a V3 o address provider

equals say address equals paste this in

here and since we're going to be calling

the get pool function on it let's also

do this we'll also do MOX Explorer get

paste this in here and we'll do D- saave

d-name let's give it the exact same name

av3 pool addresses provider running

explore command and saved Abbi okay so

great we go in here abis boom we now

have the ABI in here

awesome so now up in networks. contracts

we can do paste this in here equals ABI

equals abis slav V3 pool address

provider. Json cool so back in our

notebook then we can say a V3 pool

address provider equals Active network

and again we have this atwork Active

network because we oh we uh don't have

the Active network actually oh we do

have the active M because we set it up

here cool so we can do Active network

dot manifest named avav through pool

address provider and then we'll have

this contract then we could say pool

address equals av3 pool address

provider. get poool call that get pool


and then we'll do a little print pool

address so we can see what the pool

address is oh we ran into an issue iv3

pool address

provider because we need to reload our

config so let's go ahead let's do that

so we'll do a little config do reload so

we'll do uh

config config equals get get config

config and we need to do oops from mx.

config import get config

like this we'll reload the config and

then we'll grab that address provider oh

we have another error so we'll get this

ke hey uh we cannot find this address

even though we clearly put it in here

it's because we need to update our

Active network so we just Reloaded The

config with this now we can say Active

network equals config doget Active

network like this that should update it

with the new config loaded and boom we

now have the pool address here awesome

so now that we have this pool address

this is going to be the thing that we're

going to stick money into right let's go

ahead let's look at this pool thing if

we scroll back to the a documentation we

go to smart contracts the top contract

is their pool and this is the most


important contract of them all we can

now in here there is a supply function

and this is how we deposit money how we

basically put money into this a into

this bank account and there's also a

withdrawal function which is going to be

how we actually pull money out so what

we can do back in here let's create a

new little cell new code cell oh here we

go now that I have this pool address and

we can go ahead once again we go to our

MOX and.mo now we don't want to hard

code this address into here because it

could change right but we do want to get

the API so we'll do MOX

Explorer get paste this in D-

save-- name pool like this so we do want

to get the ABI and now if I go to my

abis I have pool. Json so what we can do

in here is we can just say pool equals

ABI equals ABI pool. Json and then in

our notebook we could Manifest this as

well

by saying pool pool contract equals

active network. manifest named pool and

then we'll say address equals pool

address so this is how we force an

address with the Manifest named if there

is no Address given and if I run this


it'll probably error actually yeah it

sure did because we need to run this

again do config do reload first oops

config do reload update the Active

network and boom now we have a pool

contract that we can actually deposit

money into heck yeah I'm actually going

to grab

these paste them up here but we now have

this pool contract boom pool interface

at this address awesome okay now what

well let's get our usdc and our weth and

let's stick it in here so let's create a

function defa deposit this will take a

full contract a token and an amount and

we'll first get the approved amount we

learned a little bit about approves

before but anytime you want a contract

to interact with or take our tokens you

first need to approve it so we'll say

allowed amount equals token. allowance

allowance of

pool contract. address like so and we'll

say if the allowed amount is greater

than the amount then excuse me if the

allowed amount is less than the amount

we'll just automatically approve we'll

say token. approve full contract.

address for the amount this way we

pretty much never have to worry about


doing approvals and then we'll do a

little print statement print F

depositing

token oops token. name into a contract

or contract. address like this and then

we'll do full

contract.

supply token. address amount b.

.oa and there will always be this

referral code which we're just going to

set to zero referral code equals zero so

we'll say referral code if we go back to

the documentation here we can look up

the supply function and it's assets

amount on behalf of and referral code so

we have assets it's our token amount on

behalf of is ourselves and a referral

code and then we could just say then we

could do usdc balance equals usdc do

balance of bo. env. eoa and we balance

equals we. balance of bo.

.oa we can say if

usdc balance is greater than zero we'll

call deposit the pool contract usdc

usdc balance and same thing if we

balance is greater than zero we'll

deposit that as well chbt jumping in to

automatically let me hit those buttons

so now if I run this I'll be able to see


my user account data by calling one more

contract on this or one more function

there's this get user account data which

has a which returns how much collateral

you have how much debt you have how much

you can borrow your liquidation

threshold and health Factor we're not

going to be worrying about a lot of

these since we're not doing any

borrowing but our total collateral base

will tell us how much value we've

actually deposited into the contract

into a so we could do a little

print um pool print F actually I'm just

going to copy paste from my my project

here just because it's going to be a

little bit easier we go to script

deposit just go ahead and grab this

whole section because it's kind of a big

giant piece of code unexpected

indentation let's move that

over move this over boom so this get

user account data returns all this

information and we're going to print it

out with some nice formatting here so if

we've did it right we should see this

populated let's go ahead and run this

cell depositing USD coin into a contract

depositing a wrapped ether into a

contract user account data boom so we


have this much collateral base and we

can borrow this much as well boom so

nice so this code base we just just ran

will allow us to deposit our code into a

programmatically all of it so we don't

have to deal with it now we have all of

this code in this deposit. py script in

the gabo associated with this course so

if you'd rather try it there feel free

to do so but nice

work okay so we've deposited nice but

what about rebalancing remember what are

we looking for let's create a new little

code section we want 30% usdc and we

want 70% we that's definitely not what

we have right now um so let's go ahead

let's learn how to take the money out

and then swap it on Unis swap so the

first thing we want to do is we want to

see how much usdc and how much we we

actually have but let me show you

something pretty cool about a I kind of

skipped over this in the beginning but

let me show you it actually on my

account so here we are back in a and I'm

connected here we can see I have this

much eth and I have this much usdc and

if you look at my metamask here it's

like cool great whatever what I can do


is I if I click on usdc on this ZK sync

Market there's a whole bunch of

information in here blah blah blah

whenever we deposit into a a will give

us a token that represents how much we

have deposited into a and this is a

little bit confusing but these are known

as a tokens so a tokens are tokens

minted and burned a supply and withdraw

of Assets in the a market a tokens Den

notate the amount of crypto assets

supplied to the protocol and yield

earned on those assets the a token's

value is pegged to the value of the

corresponding supplied asset at a 1:1

ratio and can be safely stored

transferred and traded so essentially

when we deposited usdc and eth a

basically gave us a receipt that said

hey um you've you've put money in us

feel free to pull the money out whenever

you want and you can pull it out because

you'll give us back the receipt so it

basically gave us a receipt that said

this is redeemable for the tokens you

put in you go to our metamask we

obviously don't have such tokens in here

but what we can do is we can look up

the contract addresses if we scroll down

let's look for where is it


dashboard

addresses there is a contract in here

called the a protocol data provider

where is it a proto pro protocol data

provider and if we look in the contracts

here the a protocol where is it and they

don't really have any and as of

recording they don't really have any

docks on this but that's okay this a

protocol data provider we click on this

oh they do have docs on it I take it

back um they've got a few functions in

here including get all a tokens and it

returns a list of the existing a tokens

in the pool pairs including symbol and

token address so we can get the

addresses of these mysterious a tokens

using this get all a tokens so since

this is a function we want to call you

know what we're going to do oh and it's

it's actually under the view contracts

in the documentation excuse me you know

what we want to do we'll scroll down to

the dashboard we'll go to addresses

ethereum V3 main Market we can scroll

down look for the data where is it a

protocol data provider we'll grab this

address here we'll go into our moccasin

dotl we'll go to networks. efor we'll


call it the a protocol data Rider equals

address

equals paste that in here and and I've

used the a contracts to get the

addresses on ZK sync myself so if I look

in my tokens here I can do import custom

token paste this in here and I get a zks

weth next import and I can see this a

zks weth and what's really cool about

this is if you watch watch it real time

this number will actually go up and then

I also have the a zks which stands for a

ZK sync usdc so I can do import custom

token paste this

in a zks usdc with six decimals

import and I have this as well and this

little number will real time go up

although it's not going up very fast

obviously because um I only put 100 $22

in here and it's at like a 5% interest

rate but it'll be real time going up

because it represents the interest

that's being accumulated as well so

anyways so we want to get that list

using the a protocol data provider we

pass the address of that in here we'll

want to save that of course I'm just

going to hit up change the address

change the name to a protocol data

provider paste it in boom and now this


should save save it to my abis and it

does indeed so now I have that oh and

let's make sure we in the network.

contracts a protocol data provider

equals ABI equals ABI aprol dat

provider. Json in my notebook now we can

get a list of those tokens by doing

first let's do a little refresh of the

config where is that where's that script

script that we

used uh here it is config reload and

we'll update the Active network paste it

in nice and now what we'll do is we'll

Manifest this so we'll say I'm just

going to paste the name of it a protocol

data provider equals active network.

manifest named a a protocol data

provider and then we can do uh a tokens

a tokens equals a a protocol data

provider. getet all a tokens or a tokens

like this and I can even do like a

little print a tokens see what these are

and this will take some time this uh

function for whatever reason it's takes

a long time with your forked chain very

expensive to run this is another reason

why we don't really want to have these

as a script at the moment because

these a tokens take a long time to get


like I'm already at 20 seconds another

optimization that we can make for our

scripts is we could run this get all a

tokens and then save the result to some

type of file and then load it from the

file but we can also do what we're doing

here where we're just running it from

this cell only once and awesome we get

this kind of crazy long output but it's

a list of all the a tokens so for

example we have a e w we have aeth wst

eth we have aeth WAP Bitcoin blah blah

blah so the names of all these a tokens

are going to be a the name of the chain

that they're on and then the name of the

token that they represent so for us we

really only want the usdc and the we

ones so I could say for each a token in

tokens I could say if we in a token name

I'll say aore we

equals active network. man eest named

usdc or actually we so even though the a

token has a slightly different Avi than

weth we can just do manifest named weth

or actually let's do manifest named usdc

so even though they have slightly

different abis we can just use the ABI

of usdc that's fine and we say address

equals and if we look in here oh excuse


me if we in a token of Zer so it looks

like each element is the name and then

the address so we'll say if we is in the

a token Z is in the name then we'll set

it and we'll have the address equals the

a token of one which should be the

address here and then we could say if

usdc

in a tokens a tokens a

tokens uh excuse me a token zero we'll

do the same thing aore usdc equals

active network. manifest named usdc

token one and then we'll do a little

print aore

usdc print a we just to make sure this

worked boom we can even double check let

me grab this address I'm ether scan or

block Scout works too and I do indeed

see a little tag here a usdc V3 so it's

the AE usdc token and

perfect now we have these two a tokens

where are we okay hold on so well we

just deposited everything now we got all

the a tokens why do we even need the a

tokens ah because we need to use the

balance of these a Tok tokens to pull

out how much we supplied so now we have

these a tokens now what we can finally

do is well actually before we even uh we


can use these a tokens to understand how

much we placed into the AI protocol and

how much they are worth so what I we can

do now is we'll create a new code

section and we'll say okay let's get how

much they are worth to figure out what

our portfolio makeup is because remember

what are we doing we go to the readme

well I didn't put in the readme we're

looking for

30% usdc

70% eth that's what we're looking for so

now that we have these two we can get

the balances first so we'll say a

usdc balance equals aore usdc do balance

of bo.

.oa I'm going to copy paste this line do

the same thing for a we so

aore we now remember a us to C this has

six decimals decimals and this one has

18 decimals so let's create like a

normalized amount so we'll say a

usdc balance normalized equals and in

Python we do have decimals so we can

just say a usdc balance divid by six

and for we we can do the same thing

thank you Chad should be T / by 18 so

now we can get these Balan normalized we

can even do a little print statement

print this one and then print this one


let's run this so great so it's saying

this is our starting

usdc balance that seems a little high oh

my God it's because I don't understand

math duh so you don't divide it by six

excuse me you got to divide it by one 2

3 1 2 3 you got to divide by this divide

by the six decimal spots and this has to

be divided by 10 raised to the 18 so

we'll do this 1 2 3 4 5 6 7 8 9 10 11 12

13 14 15 16 17

18 there we go that should actually look

more correct math is hard huh okay

perfect okay so I didn't run it aund a

bunch of times so we have 100 usdc and

one eth that's actually exactly are

starting balances Okay cool so let's

make a new sell so we have their balance

normalized now we need to get their

price we need to get their price and we

need to multiply it by our balance to

figure out how much they are worth so we

can figure out okay do we have a 7030

split right because yes we're looking

for this 7030 split but we're looking

for a 7030 split in terms of value right

we want 70% of our money's worth to be

an eth 70% of our money's worth or 30%

of our money's worth to be in usdc so


now there's a 100 different ways we

could get the price but we could also do

it the smart contract way because way

way earlier we learned about chain link

price feeds aha so we can go to a chain

leag price feed let's look up some feed

addresses price feed addresses on

ethereum great let's look for eth

slusd great let me copy this address I'm

going to do a little up to get this past

it in here I'm going to save this as the

eth enter great so now we have eth used.

Json in my MOX and. toml I can now do

ethusd equals address equals paste the

address in here and then up here ethusd

equals AI equals ABI eusd Json and a lot

of people what they do is they go hey um

if I have 100 usdc I have $100 right but

that's not the case remember if we look

at the

usdc price usdc to usdc chart we get to

all time there have been some times when

it's not quite a dollar for example here

it was actually

967 or here it was actually

0. or

1.3 and when it gets kind of this

volatility and when it's not worth a

dollar if we have it hardcoded to a

dollar we could rebalance our portfolio


in correctly so we also want the usdc

price which we can find in here there's

a usdc slusd price boom we're going to

grab that and in our

moxino we can do usdc USD equals address

equals paste that in here and then up

here here we can actually just copy the

two and use the exact same ABI for eth

for usdc USD because they're both going

to have the same API right so we're

we're going to be using a chain link

price feed to get our pricing now we do

know that the chain link price feeds

since they're you know on chain and

they're updated as such they will be

slightly slightly delayed slightly out

of sync so there's like a a 1% a0 5%

buffer that we want to keep in mind

that's here but that's good enough for

us cuz we're looking for approximately

balanced rebalanced anyways so cool so

now that we have added those we could

create a little get price function so

I'll do def get price we'll say feed

name which will be a string and this

will return a float this will return the

price so we'll say Active network equals

get Active network we'll do price feed

equals Active network do manifest named


feed name so if we're looking for ethusd

we' pass an ethusd if we're looking for

usdc USD we' pass that in then we'll do

price equals Price fee. latest answer

right because we look at this contract

we go to contract read contract latest

answer latest answer latest answer boom

that'll get us the latest answer then we

get the number of decimals that this has

by calling the decimals function here so

we'll say decimals equals price fee.

decimals thanks chat GPT then we can do

decimals

normalized equals 10 rais the power of

decimals and we can do return price

divided by decimals normalized because

if it has

you know that's why we did this up here

we probably should have done this syntax

to make this easier to read but I

digress so now we can do like usdc price

actually oh thank you chat jbt and we

can print these out USC print out the we

so we can say the USC price get price

USC price feed actually we call it USC

eth uh oh no excuse me usdc USD and we

call this one eth USD

let's run this uh I think this is a key

error key error yep because we got to do

once again fig. reload like this boom


now let's run it tada and we see the

price of usdc is actually not $1 it's

99999 54 blah blah whatever and eth is

$3,650 right now cool so now we have the

prices let's create another little code

block we can do usdc value equals a USC

balance normalized times times the usdc

price we value like this then we can get

the total value which is going to be

adding the two of them up we can also

say the target

USC value equals

0.3 Target we value equals 0.7

then we can do usdc percent allocation

this is the current is going to be usdc

value divided by the total value we'll

do the same thing for we and then we

could finally do we can actually add

some buffer equals 0.1 let's say we'll

get give like a 10% buffer and now we

could say needs rebalance rebalancing

equals we're going to do some math here

the absolute value of the usdc percent

allocation minus the target USC value is

greater than the buffer or the absolute

value of the we percentage allocation

minus the target we value actually this

should be percent allocation but that's

okay and we'll actually put this on a


new line so it's easy to read is greater

than the buffer and then we'll do a

little print needs rebalancing we'll

print the usdc percent allocation and

we'll print the we percent allocation

let's run this wholesale and it's saying

we need a rebalance because USC

currently has 2% of the value right cuz

it's only $100 whereas we is like $3,000

so USC is only 2% of our portfolio we is

around 97%

we're over indexed on we we're over

indexed on ethereum so we need to

rebalance our portfolio so needs

rebalancing is true so we can now start

to actually rebalance our portfolio

exciting all right so to get started

here create a new code section and we're

going to just go ahead and withdraw all

of the tokens out of a now we probably

want to be a little bit clever with this

where we only withdraw depending on what

we're selling for example you know in

this case we would only be selling we

and buying usdc to bring the balances

closer so we should save gas by only

withdrawing the we and that's what we

did in the GitHub repo associated with

the section but to make this part a

little bit easier we're just going to go


ahead and pull everything out in the

GitHub REO associated with the section

we actually do some clever calculations

to figure out which one we need to pull

out and and sell and how to sell and

blah blah blah so but for us we're just

going to say okay we're just going to

grab that pool contract where is it

where that pool

contract pool contract here it is pool

contract we're just going to say uh

we're going to do a

we. approve pool contract. address and

then the a

we. balance of B

.oa now the reason we need this is

because we basically have to give back

our aeth in order to receive so we're

going to approve the pool contract to

take it out then we can just do pool

contract. withdraw withdraw aore we.

address let's just do the whole balance

again balance bo.

.oa so if we look up the

a contract again let's go to pool let's

look up

withdraw see it takes the asset amount

and two asset amount and two and

actually it's not going to be the aeth


it's just going to be the raw we.

address instead you know let's make a

little function called def print token

balances and let's just do oh wow chbt

thank you usdc balance we balance a USD

and we a w so after we run this we

should have no

usdc we should have some weth we should

have some a usdc and no we no a we

excuse me so let's try this yes because

it's all in a yes we have we now we have

a balance here okay perfect okay great

so we've pulled it all

out now we can actually do some

swapping and

additionally in the GitHub repo

associated with this we go back to mock

algorithmic trading sign updraft we go

back to the gab repo associated with

this in the

rebalance script we have this calculate

rebalancing trades where we figure out

exactly how much we want to sell and buy

and blah blah blah we're actually just

going to cheat a little bit we're just

going to copy this whole function def

calculate rebalancing trades we're going

to print it here and if you want to go

through this figure out what it's doing

great go for it but essentially we're


going to have

usdc data

equals

balance balance of a usdc balance

normalized price UCC price contract is

going to be

usdc then we're going to do the same

thing with weth and we're going to say

Target allocations equals this so we're

going to cheat a little bit and we're

going to say trades equals calculating

rebalance trades USC data wet data and

Target allocations so this function is

just a bunch of math uh it's pretty

minimal actually where we just get back

hey uh should we buy or sell usdc should

we buy or sell we and how much so let's

run this do a little print trades let's

run this sell zoom out a little bit oh

that's not pretty printed but that's

okay so it's saying we should buy

1,35

usdc and we should

sell

281 we so so I'll do a little we to sell

equals

trades of

weth trade let me run that so this is

how much weth we're going to go ahead


and sell now so let's create a new

another code section now that we know

how much we're going to sell and we have

already withdrawn it so now we can go

over to Unis Swap and pull it out so for

UNIS swap we can go over to the Unis

swap docs and learn how to actually pull

money out now Unis swap if you want to

pause the video video go over some of

the overview here please do as we said

before though essentially it's just a

place for us to swap tokens right and if

we go to the contracts section we can

learn about how to do some swapping

we're going to be using Unis swap V3 uh

if you want to do some extra credit and

rewrite this with Unis swap V4 feel free

to do so now to implement a swap we have

this Implement a swap section of the

docs so we have single swaps the

function that we're going to be creating

is going to be swap exact input signal

this is going to be the function that

we're going to be calling and to get

this we're going to want to be calling

this on an I swap router so we're going

to be looking for a router contract we

can find those in the deployments

section and we go to ethereum is right

here we are looking for the with this


one right here the swap router O2 we can

even click on this take a look what this

does this is the code base for it it's

got a whole bunch of stuff inherited and

it uses solidity we can go to Ether scan

look up this contract address or block

Scout go to contract swap Rider O2 and

if you go to write as proxy you can see

it has this exact input signal exact

input signal exact input single and this

is the function that we're going to call

it's got a whole bunch of parameters

I'll briefly go over them and if you

want want to dive deeper you can but

this is how we're going to basically

swap we for usdc so back here I'm going

to just hit up and to paste that address

that we just got in here and the name is

going to be uni swap Unis swap R um Unis

swap swap router right and it should be

saved in there now in my mo. tml create

a new Unis swap swap router

ABI equals Abi's Unis swap swap router

and then we have Unis swap swap router

equals address

equals and I just had it this address

right here great paste that in there

okay and now according to the Unis swap

docs again on the V3 protocol we go to


implement a swap single swaps swap exact

input signal signal swap exact input

signal single I can't I I don't know how

why I can't pronounce it we go to this I

swap router interface we can look for

this is going to be the struct of the

input so in this solidity contract

there's a single parameter but it's a

struct filled with all these parameters

so it's a little bit awkward we have to

encode we have to send a single

parameter but it's just like the

combination of all of these so I'll even

like copy this bring it over to our

notebook do a little save paste this in

here and comment it out just so that we

know it's an address address unit 24

address unit 256 unit 256 unit 256 unit

160 just combined into one and it's

actually really easy to do that I'll

show you how what we want to do is we

want to do we. approve oh well first

actually we want to do uni swap swap

router actually first we want to do

config do reload Active network equals

config get Active network then Unis swap

swap router equals active network.

manifest named Unis swap

V3 swap router EXC me Unis swap swap

router swap router swap router then we


can do we. approve Unis swap swap

router. address or the we to sell uh

actually that's

this is normalize so we'll say amount we

equals we to sell time 10 raised to the

18th that should be right let me just

print amount we just to make sure let's

run this line here print amount with

that looks right to me yes that looks

right to me cool so we'll approve that

amount now we'll do a little print let's

swap and we'll do Unis swap swap router

do exact input

single and to pass in all these

parameters here let me move this down

pass in all these parameters as a single

parameter we just add another set of

parentheses that's it so this will just

be one set of parentheses so this is

where it gets a little confusing and

I'll walk you through each one of these

so token in is basically what are we

selling so this is going to be the West

do address here token out is what are we

buying we're buying usdc so we'll say

usdc do address the fee is the fee

structure so different pools have

different fees we're just going to use

this
hard-coded 3,000 which stands for the 3%

fee pools so again this isn't super

important at the moment this if you want

to get deeper into Unis swap

understanding all these are important

recipient is going to be us so boa env.

eoa the deadline oh there is no deadline

did I grab the wrong one uh there is no

deadline so we can skip that oh there

shouldn't be a deadline let's let's go

look in the swap router exact input

single okay so exact input single it's

going to

take components address address unit 24

address

24 amount in yeah there's no deadline in

here so if you want to see like exactly

what parameters a function takes you can

just look for the function in the ABI

exact input s single and just like look

right above it and this will be the

parameters or the inputs so yeah we can

clearly see there's no deadline in here

huh that's weird that the doc say to do

the deadline uh well in any case we're

not going to do the deadline then we

have the recipient which it's going to

be us the amount in so how much are we

sending of we so this is going to be the

we to sell what to sell and then we have


amount out minimum so this is important

because what a lot of people do is they

just go oh well just give me whatever

the price is but actually we we do want

to kind of figure out at least how much

we should be getting back and this is to

prevent against something called me

that's a much longer conversation that

we'll go into in the security curriculum

so if you want to get into security you

want to learn about me definitely go

learn it there for now we're just going

to kind of gloss over it a bit and it's

good that you now know that me is a

thing to look out for at least but to

get the minimum out we'll do Min out

equals trades usdc trade times 10 the

6th um and we'll multiply this whole

thing by time 0

90 so we'll say okay we should at least

be 90% of what we expect to get here so

we'll say Min out and then finally

square root price limit so this is a

pretty clever optimization on like

getting pricing information for us we're

going to play it not super safe but fine

enough where we're just going to say

zero here um I wouldn't worry too much

about this value for now but if we did


this correctly L after we run this swap

if we print out I know that we made that

function to print out token balances now

print token balances let me grab this we

should have swapped a bunch of our eth

for usdc so let's run this and let's see

if we're able to run the swap correctly

okay no value not of instance type int

we. approve amount we ah value not an

instance type int so we need to do int

like this now let's run it we're getting

a different one oh it's because this is

a negative number and we need this to be

a positive number so we'll do abs to get

the absolute value now let's run it got

a different error down here what what do

we get error encoding it's because we

should be doing amount we instead of we

to cell try this again and it's because

Min out is not an INT so this needs to

be an INT let's do this now let's run it

and it's running and it's swapped and

now we have some extra usdc a new we

balance as well and we still have a usdc

oh okay this is very exciting so now now

that we've done the Swap all we have to

do in a new little block here is just

deposit it back

in and we wrote a little little script

to do the deposit I believe or a little


function so we scroll way way up to way

back when when we did our deposit so we

can just run this we just need the pool

contract token and the amount so let's

go back here we'll say amount amount

equals usdc do balance of boa .oa let me

Zoom back in a little bit here and we'll

do deposit pool contract usdc

amount um and I believe this has the

allowance yep it has the allowance baked

in so that should just work then we can

do print token balances like we've been

doing and we should see only a tokens

because we rebalance we put everything

back in and then we should also check

okay hold on hold on oh this is super

exciting we should also checked our

allocation percentages I should have

made this a function huh that would have

been a lot uh cleverer um we should

check this uh by let me and I'm just

going to rewrite it at the bottom uh we

should check this by doing a usdc

balance equals a usdc do balance of bo.

.oa a we balance equals a we. balance.

balance of boa

do.a and then we have normalized oh

actually

normalized let's just grab this grab


these two lines so we don't accidentally

screw that up again paste those here get

the normalized balance the value is TOC

value boom that looks good we value boom

that looks good total or um we

allocation

equals we value divided by them added

USC chbt is just being so helpful here

USC percent allocation usdc value

divided by the combination of the two

and then finally print f

current

percent allocation of usdc we'll do the

same thing for we thank you chbt let's

run this see if it worked depositing USC

coin to a okay USC balance is now zero

we balance is now this a USC balance is

now this current percent allocation of

USC is one current percent allocation of

we is zero uh okay something's wrong

with our balance allocation so let's

take all this out let's create a new

code section because we don't want to

redeposit what do we do we mess

something up here usdc price oh we

didn't deposit our we back

in oh my God we forgot to deposit the we

back in okay so let's deposit the we let

me create an a new little sell down here

deposit pool contract we am out there we


go hit play depositing W ether great now

let's try this one more time let me

delete this cell down here play this oh

let's okay actually let's leave those

why not play this this makes even less

sense to

me the we value is because we didn't put

the amount in here oh my goodness amount

equals we. balance of b.v eoa let's do

that now now let's run this almost there

finally after fiddling with the numbers

and making sure to actually deposit all

of our stuffing we finally get current

percent allocation of usdc

0.299 blah blah blah current percent

allocation of weth 0.71 blah blah blah

we have successfully rebalanced our

portfolio this is so exciting for so

many

reasons now if you want to go the extra

mile and you want to put these into some

scripts feel free to do so I'm not going

to do that here but what I am going to

do is I'm going to show you how to do

exactly what we just did now on ZK sync

like I've said before here's kind of the

final code for what we just did I have

that in this code base that I'm working

with here the only difference the only


thing we need to do now to work with ZK

sync is to set up a ZK sync chain and

then add the contract addresses for each

one of those so again what we did at the

beginning of this was we showed you hey

if this is your setup you can rebalance

your portfolio appropriately

now I'm going to show you one more time

the whole process I'm going to pull some

money out of AA on ZK sync trade it for

our usdc and then run the script again

and it'll automatically rebalance it

once again you do not have to do this

however if if you want and this will be

your Workshop you will be doing this on

a tenderly virtual Network so be sure to

pay attention here now I'm going to

manually withdraw my eth so I'm going to

go ahead and withdraw all of it uh we'll

do unwrap we withdraw to eth I'm going

to withdraw all of the money out of here

and let me do I'll do a little bit of

verification make sure this contract

address is correct and I'm going to

check the call data as well because now

we know how to do and check the call

data and do that off screen but after

I've done it I'm going to go ahead and

hit approve this is going to take a

second to go through now I'm going to


withdraw some of this eth I'm going to

check the data here I'm going to pause

video go verify the data so money out

now if I look in my metamask I've got a

lot more ethereum so I just withdrew I'm

going to go to Unis swap or you could do

syn swap because again I'm on ZK sync

either one of these works fine I'm

actually going to use syn swap because

the pricing here is a little bit better

as of recording and I'm going to say

we're going to swap eth to Native usdc

I'm going to do like

75% to usdc I'll hit swap I'm going to

confirm once again I got to go through

verify the address is correct verify the

hex dat is correct Etc once I've done

that I'll hit confirm and once it's gone

through I'll now see in my menam mask

after it finishes pending I now have

more usdc token and I can go back to a

go to

supply Max a pro USC to continue same as

always I'm going to select an approval

amount I'm going to verify the data I'm

going to verify the address once I've

done all that hit next and approve and

then I'll hit Supply same thing verify

the address verify the hex data itself


is correct once I've done hit confirm

we're all done here now we're way out of

whack we have way too much USC not

nearly enough eth so once again so once

again now I'm going to run my script MOX

run

deposit

and and D- Network CK sync D- account

small money I'm going to say yes I want

to put in my password it's going to run

my script get the a tokens get our

starting balances which are right here

it's going to say the current percentage

allocation is

93% and

6.9% so rebalancing is needed here are

the targets then we're going to go ahead

we're going to send some transactions to

pull the money out of a then it's going

to be time to swap swap this much usdc

for at least this much we it's going to

do the swaps it's going to then

redeposit them back into a and then

finally we see current percent

allocation usdc rebalanced we rebal if I

go back to a I do a little refresher I

see they have been successfully

rebalanced and that's what we just did

in our notebook here

ourselves so like I said these notebooks


are phenomenal for tinkering and testing

and kind of doing exactly what we just

did right we went on a forked Network we

played around we ran these scripts so we

could get what we wanted then all we

really have to do is then kind of copy

paste the code that we wrote into some

scripts for ourselves right I mean

that's essentially what I did when I was

first writing this now I'm not going to

do that for you on this video because

this leads us to our Workshop our first

and only Workshop of this section

algorithmic trading here your Workshop

is to copy the code you just wrote into

some scripts and if you want to cheat uh

we have everything in the GitHub repo

above here and then run your scripts on

a tenderly virtual Network or a forked

Network do exactly what we did but maybe

change the allocations around maybe do

like a 50/50 allocation split maybe do

like 100 Z if you run into errors try to

de buug them try to figure out why you

ran into those errors maybe work with

different tokens maybe you like

different tokens maybe work on a

different network make sure you're able

to at the very least in this script at


the very least make sure you're able to

run this run the script run the where is

it uh either MOX test- s or MOX run

deposit and uh deposit and rebalance -

Network ZK sync and then just obviously

keep Fork to be true here so that is

your Workshop pause and then come back

for a recap these workshops are so

important because they are going to be

where you take this knowledge and you

apply it right away to try to see if you

actually retained if you actually gained

the knowledge so pause the video as

always spend at most 25 minutes on these

prompts without the aid of AI to be

honest this might take you a little bit

longer than 25 minutes if that's the

case that's okay if you're unable to

solve them after 25 minutes stop take a

break and then work with AI or the disc

discussions to help you solve them

so all right welcome back did you do the

workshop if you didn't you're only

cheating yourself as always if you

didn't you're only cheating yourself

pause the video pause the course go do

the workshops this is one of my favorite

sections because you are getting into

Defi and in my opinion defi is one of

the most powerful changes to the entire


world's finance that blockchain and

smart contracts can bring making the

world more accountable more fair and

just better be sure to pause and do

this now that you've done this we're

done with this section yeah I know I I

dumped you into a I dumped you into Unis

swap you might have never heard of these

before and I gave you a sneak peek at

these very very cool defi Primitives

these Financial Primitives in this

industry and how to do python scripting

and play with them so that you can go a

portfolio manager or do whatever you

want to do so we learned a ton here and

as normal let's go ahead let's do a

little recap of what we learned in this

section so the first thing we learned

here was a little bit about defi if

we've never heard anything about defi

before now like I said there's a ton to

Defi and I glossed over so so so many

details but essentially defi stands for

decentralized finance and it's kind of

this all-encompassing term for any type

of finance that happens in the

blockchain space two di5 protocols that

we worked with are a which is very

similar to a classic Bank you deposit


money into it and you can gain interest

on it and then additionally people can

ask for and take out loans now we didn't

go over the loans at all in here but

essentially that's why we're able to

gain interest right when we went to app.

a.com we looked at these percentage

returns here these percentage returns

are given to us because we're basically

getting paid for people to borrow our

money which is very exciting we also

learned about Unis swap which is a way

to trade different assets so we needed

to sell our we or our ethereum for usdc

and we were able to do that on Unis swap

completely on chain we learned what weth

was and weth was this kind of tokenized

version of ethereum so you take weth you

stick it into this contract and it mint

you and it mint you this we token thing

sticking in the contract it goes here

here's this token and anytime we can

basically burn it to go back to where we

started with the actual raw ethereum we

used these Primitives in our script here

to say Hey you know we're going to be

portfolio managers we're going to

practice being portfolio managers we

want our Target let's go to our readme

we want our Target portfolio allocations


to be 30% usdc 70% eth we want to hold

30% of our value in usdc 70% in eth why

well because that's the investment

strategy that our boss gave us as

portfolio managers so we said okay cool

let's do that let's set that up and

let's test it let's test this on a fork

Network to make sure all of our code

works so we got started actually setting

up minting ourselves some fake tokens

and setting ourselves some fake balance

we decided we wanted to Tinker with this

in a python notebook because that would

make our testing a little bit easier so

we got everything set up we got from

moccasin import setup notebook so we

could use the moccasin config stuff in

our python notebook here we scroll down

we were able to work with a get the pool

contract by manifest named a V3 pool

contract a V3 a V3 pool address provider

we were able to get the abis of

different contracts using the MOX

Explorer get to save it to those ABI

folders as well we were then able to

deposit our contracts we were able to

then deposit our tokens into a gaining

starting to gain interest which is very

exciting and then in return we got this


receipt called an a token that says hey

you've deposited tokens into a it's a

little bit weird you deposit in we and

you get AE you deposit in usdc and

you're given a usdc so we're given these

tokens and then what we could do is we

could figure out okay how much of these

tokens worth we were able to get the

price using a chain link price feed once

we got the price we were able to figure

out how much value we were holding of

each one of these we found out 97% of

our portfolio was ethereum and 0.2% of

our portfolio was usdc which means we

didn't hit our Target allocations so we

needed to rebalance so we pulled out

some money out of a and we kind of

cheated a little bit with this calculate

rebalancing trades which told us how

much we need to sell and how much we

need to buy we figured out okay we need

to sell some we and then what we did was

we learned about Unis swap Unis swap

being kind of this Stock Exchange type

thing it's this onchain contract that

allows you to buy and sell tokens with

each other we said hey Unis swap we

would like to sell you and buy usdc so

we want to trade we for usdc so we

downloaded the ABI we decided we're


going to use this exact input singal

function on the Unis swap swap router

that was able to swap the token for us

we were we were able to then print the

token balances and we did indeed

successfully swap then we deposited all

of our money back into a after a couple

attempts sorry about that um and then

once we did we got everything back into

a so everything started gaining interest

again and we finally hit just about our

Target portfolio portfolio allocations

of 299 which is basically. 3 and

70 as python developers Finance is one

of the best applications of Finance

because we can write scripts to do

Financial movements like what we did

here very easily and with very little

code which makes maintaining our

financial applications really easy tons

and tons of portfolios and hedge funds

use python as the go-to language for

quantitative researchers algorithmic

Traders and so much more so we were

introduced to defi we learned a ton

about how to script with moccasin and

titanoboa to go in and out of these

Financial applications and at this point

you should be incredibly proud of


yourself especially if you did the

workshop and if you didn't do the

workshop you should pause the video and

go to the

workshop defi can be tricky and if it if

the defi stuff didn't sync with you

right away that's okay it takes some

time defi can be confusing and it could

be confusing for reasons that shouldn't

be confusing like for example like a lot

of people ask me like well okay why

would I want to even deposit into a why

would I not just want to hold the tokens

well you can't you can do that some

people ask oh uh why not just use

something like coinbase and the answer

is well you can but you don't get this

automation you don't get this

composability and coinbase is a

centralized entity these are

decentralized codebases

nobody is they just go they just work

there's no centralized intermediary to

block us or get in our way or anything

like that they just go so like I said in

my opinion some of the most powerful

Tools in this industry just with some

scripting here so you should be

incredibly proud of yourself and now

really is a good time to take a break go


get a coffee go for a walk go get some

ice cream because coming up next is

moccas D5 stable coin or unless I move

the order around it might be someplace

else but we're actually going to build

our own stable coin our own type of usdc

ourselves and it's going to be arguably

more powerful than usdc because it

doesn't have those centralized

components that usdc has so now's a

great time to take a break go for a walk

get some ice cream cuz when you come

back we're building a stable coin so

take that break and I'll see you soon

all right welcome back to the stable

coin section of Cypher updraft the

complete code that we're going to be

working with is right here as always now

stable coins are something that we've

worked on in the past and you are going

to build your own stable coin you're

going to do you're going to be building

one of these tokens that we worked with

over in the algorithmic trading portion

of this course however this is going to

be an incredibly powerful stable coin

and one of the most impressive defi

applications you've created up to this

point stable coins are quite often


incorrect so we're going to be learning

a lot about what stable coins actually

are as well as going through and

building our own let me go ahead and

show you what the final code base for

this is going to look like here and this

is going to be project you should try to

go all out on writing fantastic tests

making the contracts look beautiful this

is going to be your chance to say okay

I'm going to build this end to endend

I'm going to build this full project and

I'm going to make it as good as I

possibly can in fact there's the

solidity implementation of this was

actually audited on the Cod Hawks

platform and you can see a list of

findings a list of security issues that

were found on that original

implementation in the GitHub repo as

well you can even click on the Link in

the GitHub repo which will bring you to

the actual contest the known issues you

can even view the contest results as

well if you go to contest details you

can hit view results here and you can

see how well people did how much money

they made and then obviously the final

report on this GitHub on this project on

this codebase as well obviously it was


solidity so it's a little bit different

but i' digress so the final codebase

we're going to be doing is we're going

to have this decentralized stable coin

now looking at this decentralized stable

coin it looks pretty minimal right it

doesn't look like there's really

anything interesting about it but what

we're going to be doing is the owner of

this stable coin is actually going to be

this DSC engine so the owner of the

stable coin is actually going to be

another smart contract and if we scroll

down in here there is a lot more going

on in here we're going to be able to

Mint the stable coin by depositing and

redeeming collateral what we're going to

be doing here is building something

similar to if we go to defi llama and

scroll down here going to be something

similar to what this protocol called

maker created so maker the maker Dow

created this thing called die which is a

decentralized stable coin so if we hit

use die on their website you can earn

wow 99.5% on your stable coin that's

pretty crazy um but basically this die

token you go to coin gecko look up this

die token this also is worth a dollar it


looks like it's recently been rebranded

to usds which we can also look at as

well and we can see if we go to kind of

like the max timeline on this it's been

pretty much around a dollar for its

entire career keeping it's trying to

stay true to its value as a stable coin

and our stable coin that we're going to

be building here is going to be very

similar to how D works or I guess I

should say the original implementation

of D we're going to be able to deposit

collateral to Mint the die token and

redeem our collateral as well similar to

working with a or working with the we

token now the superpower of this is in

this liquidate function if people don't

have enough collateral if people have

minted more dye than they put down

collateral other users can liquidate

them and we'll talk about that a little

bit more when we get to that section

people can redeem collateral they can

burn the uscc we'll implement this thing

called a health Factor we'll be getting

pricing information and so much more and

it's this like I said it's this contract

it's this set of rules that will govern

how users can buy and sell and work with

this stable coin additionally we'll be


adding this Oracle contract to try to

make working with the oracles a little

bit safer we of course are going to have

some deploy scripts to deploy everything

and some verification scripts as well We

additionally are going to have a ton of

unit tests and you should write even

more than what we have here but

additionally we will have some fuzz

tests some stateful fuzzing fuzz tests

as well to get everything going we can

run MOX run deploy which should go ahead

deploy our token deploy well a mock

contract and deploy the DSC engine as

well and we should be able to run MOX

test which will run all of our test

fuzzing and you'll notice we're taking

quite some time to run a lot of fuzz

tests on this and yes this will highly

likely take some time but then we run

the rest of the tests as well we could

also of course do MOX test DN Auto to

run our test in parallel to run

everything a little bit quicker here

still the slowest bit is going to be the

fuzz test so we're still going to have

to wait for some time right but

everything passes so this is going to be

your Flagship project of your entire


Viper and python curriculum that's why

there's this giant star next to it if we

go to the go to the GitHub repo there's

this giant star next to it because this

is going to be one of the most advanced

projects you work on period probably one

of the most advanced products you ever

work on after we get through this we

have a couple of quick ones to end out

the course so this is the one you should

probably be spending the most time on

working the hardest on to get it really

right and make it really good and be

sure to push this up to your GitHub

after you finish and we're going to code

this as if we're going to be deploying

this every single one of your smart

contracts you want to build you want to

keep in mind I'm going to build this as

if I'm going to be deploying this I'm

going to make sure my code is clean I'm

going to make sure my tests are clean

I'm going to think about security I know

we haven't done too much thinking about

security but we're going to write very

defensible code with really good tests

and the like additionally we're going to

be going over some def stuff some def

Concepts and oftentimes that's going to

be the hardest part of working with this


so if some of this defi stuff goes over

your head if it's confusing AIS are

phenomenal at understanding Finance so

ask your AIS ask your discussions ask

your friends jump to the Discord ask

questions it'll get confusing and that's

okay there's no stupid questions I want

you to just rapid fire ask questions

here so to get started to get into this

we first need to know a little bit more

about this stable coin thing now if you

Google around on stable coins I promise

you you're going to get some information

that isn't quite right same thing with

AIS AIS kind of get this wrong a lot of

the time so we're going to watch a video

that I've made that will give us a much

deeper introduction to stable coins how

they work where the value comes from and

the like so let's go ahead let's watch

this

video when you research stable coins

today you get a lot of misleading

information and that's what we're here

to clarify today in this video we're

going to teach you everything you need

to know about stable coins but actually

what are stable coins why we care

categories and properties designs of top


stable coins and then the real reason

behind what they do what stable coins

really do this video is for both

everybody Technical and non-technical

and we're going to correct a lot of the

misleading information out there there's

going to be a lot of information here

for people less familiar with defox so

as always don't be discouraged if

something doesn't make sense the first

time you hear it buckle up buckle up dum

dum we're in for a volatile ride about

stability a stable coin is a nonvolatile

crypto asset that's it flashed out we

could rephrase it to a stable coin is a

crypto asset whose buying power

fluctuates

very little relative to the rest of the

market and this is the first place where

we disagree with traditional media if

you Google what is a stable coin you'll

see something like this response

everywhere stable coins are

cryptocurrencies the value of which is

pegged or tied to that of another

currency commodity or financial

instrument and to that I disagree I

think that's an easy initial way to

understand them but not the whole story

a stable coin is a crypto asset whose


buying power stays relatively stable a

good example of buying power would be an

Apple Market if you want to a market to

buy apples with Bitcoin 6 months ago the

number of apples you could buy would be

drastically different than the number of

apples you could buy today that's an

example of buying power changing and not

being very stable however someone buying

apples with dollars would probably be

able to buy the same amount of apples 6

months ago to now that's an example of

buying power staying relatively the same

since we could buy the same amount of

apples today than 6 months ago a dollar

would be considered a more stable asset

whereas Bitcoin would be much less

stable this is what we mean by buying

power an asset whose price fluctuates

rapidly all the time is a poor example

of stable buying power oh we went to

zero this for example would not be a

stable asset now a stable crypto asset

is just a stable asset that's a

cryptocurrency most cryptocurrencies by

Nature aren't stable but we will give

examples of stable coins so summary here

a stable coin is a crypto asset whose

buying power stays relatively the same


and if that's all you take from this

video Perfect great let's keep going now

why do we care about stable coins

because money is

important but not like I Love Money type

of important in everyday Society we need

some type of low volatility AKA stable

currency to fulfill the three functions

of money and for web 3 we need a crypto

version of this the three functions of

money are storage of value unit of

account and medium of exchange storage

of value is a way for us to keep the

value and wealth we've generated putting

dollars in your account or buying stocks

cryptocurrencies is a good example of

storing your value apples would make for

a poor storage value since they would

rot over time and lose their value unit

of account is a way to measure how

valuable something is when you go

shopping you see prices being listed in

terms of dollars this is an example of

the dollar being used as a unit of

account pricing something in Bitcoin

would be a poor unit of account since

the prices would change all the time

medium of exchange is an agreed upon

method method to transact with each

other buying groceries with dollars is a


good example of using dollars as a

medium of exchange buying groceries with

car tires would make for a poor medium

of exchange since car tires are hard to

transact with in order for our everyday

lives to be efficient we need money to

do all these three things and like I

said in web 3 we need a web 3 money we

need to be able to know the value of

stuff in web 3 be able to pay for things

without prices going crazy and we need

to be able to store our wealth in web 3

in a decentralized world we need a

decentralized money assets like ethereum

work great as a storage of value and

medium of exchange but fall a little bit

on their unit of account due to their

buying power of volatility however maybe

in the future as ethereum because more

adopted it'll become stable and we won't

even need stable coins but right now

it's a little too volatile and yet I'll

still tell you it's ultrasound money

since I do think it's an amazing store

value but that's a conversation for

another time banket don't kill me I I'd

love your content also if you're here be

sure to like And subscribe because we're

just cooking the fire up and we are


about to pop off anyways okay so now we

know what a stable coin is why we care

let's talk about the different

categories of stable coins and here is

the second place I strongly disagree

with traditional media if you search for

types of stable coins you'll get

something that pulls them into

categories like this Fiat collateralized

crypto collateralized commodity

collateralized and then algorithmic now

this isn't too bad of a categorization

it does make it easier for new people to

understand but I think it paints a

inaccurate picture

so let's categorize stable coins but

actually the categorizations that I like

are relative stability stability method

and collateral type so what are these

categorizations let's start with

relative stability when we talk about

stability something is stable only

relative to something else the most

popular type of stable coins is pegging

or anchored stable coins and these are

stable coins that are pegged or anchored

to another asset like the US dollar

tether D and and usdc are all examples

of US dollar pegged stable coins they

Follow The Narrative of one of these


coins equals $1 and that's how they stay

stable it's stable because they track

the price of another asset that we think

is stable and most of these stable coins

have some type of mechanism to make them

almost interchangeable with their pegged

asset for example USC says that for

every usdc token printed or minted there

is a dollar or a bunch of assets that

equal a dollar in some bank account

somewhere so the way it keeps its value

is that at any time you should be able

to swap your usdc for the dollar or at

least hypothetically so something like

die on the other hand uses a

permissionless overcollateralization to

maintain its Peg but we'll get to

understanding that a little later

however a stable coin doesn't have to be

pegged to another asset it can be

floating remember to be considered a

stable coin its buying power just has to

stay relatively the same over time so a

floating stable coin is floating because

its buying power stays the same and it's

not tied down to any other asset with

this mechanism you could hypothetically

have a stable coin that's even more

stable than an anchored or Peg stable


coin let's look at an example let's say

I can buy 10 apples for $10 today but in

5 years I can only buy five apples with

$10 so it would cost me $2 to buy 10

apples this isn't an unheard of

phenomenon to happen and it's commonly

just referred to to as inflation now

let's introduce a stable coin whose

buying power floats up and down with the

market for now let's just pretend it

does so magically and let's call it

Apple coin today you can buy 10 apples

with 10 Apple coins and in 10 years you

can also buy 10 apples with 10 Apple

coins which one of these assets would

you say is more stable yes the Apple

coins buying power stayed the same over

the 5-year period so we'd say it's a

more stable asset even though it's not

pegged to something like a dollar and

Yes stable coins like this do exist and

they use a lot of clever algorithms to

do this one such example is the Ry

stable coin by reflexor Labs how Ry

Works might be its own video but we've

left some links in the description for

you if you want to learn more about how

it works because this concept can be a

little hard to grasp to further explain

it let's go through another analogy


let's look at the anchor and the buoy in

this image which of these do you think

is more stable the anchor or the buoy

well it depends on what you're comparing

them to compared to sea level the buoy

is more stable since it'll always be at

sea level as the water level rises and

Falls the distance between the anchor

and the sea level is constantly changing

the buoy is an example of a floating

stable coin now if we compare these two

to the ocean floor though the anchor is

more stable of the two since it'll

always be right on the ocean floor this

is analogous to a pegged SL anchored

stable coin now if we're going to be

really serious with this analogy then

the question might be well what happens

when a storm comes or what happens when

the water's crazy or the Tide's crazy or

something and to that I'd say you're

right and a stable coin needs to take

extra precautions to take these into

account and maybe get the average sea

level over the course of time and most

popular floating stable coins have some

mechanism to account for turbulence like

that summary Peg stable coins are tied

to that of another asset while floating


stable coins use different mechanisms to

keep the same buying power over time

number two stability method the

stability method is this mechanism that

keeps the coin stable if it's a peg

stable coin what is the pegging

mechanism if it's a floating stable coin

well what is the floating mechanism and

it typically revolves around minting and

burning the stable coins in very

specific ways and usually refers to who

or what is doing the minting and burning

these are on a spectrum of governed to

algorithmic in a governed stable coin

there is a governing body or a

centralized body that is minting and

burning the stable coins you can imagine

the maximumly governed and least

algorithmic coin would be a single

person/ entity minting new stable coins

promising that the coins are not

volatile but it could also be an

organization like a government or even a

dow choosing to Mint and burn new coins

these govern coins are typically

considered centralized since there's a

singular body that is controlling the

minting and burning you can make them

more decentralized by introducing a dow

and that kind of makes them more


algorithmic but we'll get more into that

later coins like usdc usdt and T USD are

examples of governed stable coins on the

other hand an algorithmic stable coin is

a stable coin whose stability is

maintained by a permissionless algorithm

with no human intervention and this is

the third place where I disagree with

traditional media a coin like dy I would

consider much more algorithmic than

govern because uses a permissionless

algorithm to Mint and burn tokens

whereas traditional media might say an

algorithmic stable coin is always under

collateralized or follow seniorage

shares or something like that but an

algorithmic stable coin is just when a

set of autonomous code or algorithm

dictates the minting and burning there

are zero meddling humans would have been

mine if it hadn't been to those meddling

kids examples of algorithmic stable

coins are going to be D frax Ry and yes

the $40 billion disaster us yes we're

going to talk a little bit more about

classic us and Luna now a token can have

algorithmic and govern properties in the

same way that it can be somewhere in the

middle of being floating and pegged D


for example does have an autonomous set

of code that dictates the minting and

burning but it does also have a dow

where they can vote on different

interest rates and what can be

collateral types and different things

like that so technically it is a hybrid

system it has some governance mechanisms

and also some algorithmic ones usdc

would fall purely in the governed

category because it's controlled by a

centralized body us and Luna would fall

almost purely in algorithmic the dirt

roads Blog has some amazing takes on

these pieces and a wonderful

visualization of where on a spectrum of

coins that are more algorithmic or

govern they use dumb as the opposite of

algorithmic instead of govern which

probably isn't wrong most classically

categorized Fiat collateralized stable

coin almost all fall into the Govern or

dumb section since they are dealing with

fiat currency and you need a centralized

entity to onboard that Fiat to the

blockchain you'll also notice on this

chart they have anchored versus

reflexive on the x-axis that's referring

to how the collateral type affects the

stable coin and collateral type is what


we're going to cover next so the summary

here though is algorithmic stable coins

use some sort of autonomous

permissionless code to Mint and burn

tokens whereas a govern stable coin have

some human interaction that mints and

burns the coins and keeps them stable

now before we go into our final category

let's look at this chart again we could

replace the word anchored with exogenous

and reflexive with endogenous and we'd

have a chart that shows collateral type

versus stability mechanism which brings

us to number three collateral type now

when we say collateral we mean the stuff

backing our stable coins and giving it

value for example usdc has the dollar as

its collateral and it's the dollar that

gives the usdc token its value because

you hypothetically can swap one usdc for

$1 die is collateralized by many assets

for example you could deposit eth and

get minted dye in return and US was in a

roundabout way collateralized by Luna

exogenous collateral is collateral that

originates from outside the protocol and

endogenous collateral originates from

inside the protocol so one of the easier

ways to Define what type of collateral


protocol is using is to ask this

question if the stable coin fails does

the underlying collateral also fail if

yes it's endogenous if no it's exogenous

if usdc fails the protocol does the

underlying collateral the dollar fail no

so the protocol has exogenous collateral

if the usdc stable coin fails the dollar

is going to keep being the dollar if die

the stable coin fails does the

underlying collateral eth also fail no

so the die system is exogenous the value

of eth isn't dependent on the value of D

if us fails does the underlying

collateral Luna Terra fail yes

absolutely and this is exactly what

happened that caused the system to lose

$40 billion in what seemed like a day

exogenous collateral originates from

outside the protocol endogenous

collateral originates from inside the

protocol two other good tests that you

can ask are was the collateral created

with the sole purpose of being

collateral or does the protocol own the

issuance of the underlying collateral if

the answer is yes to either one of those

then it's endogenous collateral now the

traditional media usually says that

algorithmic stable coins are to blame


but I think what they're really

referring to is endogeneously

collateralized stable coins it makes

sense that they can be scary and

potentially dangerous because their

value kind of comes from nothing

exogenously collateralized stable coins

are typically over collateralized

meaning there's more value of collateral

than there is of the stable coins here

we have another image from dirt roads

comparing different stable coins the

exogenous versus endogenous collateral

of the protocols and how much they have

maker dow die has almost all exogenous

collateral frax which is another stable

coin we haven't really spoken about too

much has a mix of exogenous and

endogenous collateral and the old taluna

and US system had mainly endogenous

collateral which is how the system was

able to crumble so quickly so yeah

endogenously collateralized stable coins

don't have a great track record so why

would you want to make one well the

answer is scale and often times people

also say Capital efficiency with

exogenously collateralized stable coins

the only way you can mint more stable


coins is by onboarding more collateral

you can only have a stable coin market

cap that is high or as high as that of

the value of all your collateral so if

you want to have 68 billion dollar in

stable coins that that means you need to

have $68 billion worth of collateral and

that's a lot of money that you would

need to on board to your system if you

have an endogenously collateralized

stable coin you can have $0 worth of

collateral meaning it's much easier to

become massive faster now I agree with

the dirt roads publication when they say

that exogenously collateralized stable

coins can't scale and I talk more about

that in the blog associated with this

video so if you're interested be sure to

check that out after the rest of this

video but watch the rest of this video

cuz we're just getting started in the

blog we also talk more about seniorage

shares and shelling coin logic which if

you're interested in that stuff

definitely check it out most of these

endogenous coins can be traced back to a

paper written by a man named Robert Sams

where he talks about how to build an

endogenously collateralized stable coin

using a seniorage shares model which


again I'm not going to go into but I

wanted to mention it because it's

probably one of the most influential

papers when it comes to these

endogenously collateralized stable coins

endogenously collateralized stable coins

there a lot of words now there's more

information on the endogenous collateral

debate in the blog but let's do a

thought experiment that I do think is

compelling for endogenous collateralized

stable coins endogenously collateralized

stable coins imagine you have a currency

and it's collateralized 100% by gold and

you run a bank and it's open 24/7 to

allow people to exchange your generic

coin for gold and your vaults people

love the convenience of our stable coin

instead of having to Lug around their

gold so they treat our stable coin as if

it was gold because they know that at

any time they can exchange it at the

bank this is an example of our generic

coin being exogenously collateralized by

gold pegged to its price and governed by

us by Me by our entity since we own the

issuance and burning of the coin you

come to our bank we'll issue this coin

or we'll burn it once you redeem your


gold and since you can always exchange

our coin for gold our coin keeps its

value now let's say the bank is only

open five days a week does our coin lose

its value now that you can't always

exchange it for gold well probably not

the market probably won't even care now

let's say you need to close the bank for

a week for renovations does our coin

lose its value now well let's say we

close the bank for a month or a year or

a decade forever if we get to the point

where you can never actually exchange

our coin for gold or the underlying

collateral again maybe do people just

use the coin as it's currency backed by

nothing in a way now it's moved from

being exogenous to now being endogenous

since it's downb backed by well itself

this is why dirt roads has reflexive on

their chart one of our coins is no

longer equal to some amount of gold it

now equals one of

itself okay I know there's a lot here

and there's even more in the blog so if

some of this confused you don't be

discouraged you can always come back

there's a ton of supporting do doents

and blogs and links that I personally

watch to learn a lot of this as well so


be sure to use that if you get confused

but now let's look at some of the top

stable coins what their properties are

and then we're going to get to some

really interesting stuff we're not going

to go too deep into the architectures of

the stable coins we are going to go over

d a little bit more though because the

d/ makerd system is a pretty standard

model for what a stable coin could look

like and it was one of the most

influential stable coins ever created so

there's that and it's important that we

go through these so we can understand

what's currently out there and why

they're currently out there and then we

can

reveal why they're really out there why

there's so many stable coins what are

the incentives for people to Mint them

and it may just blow your mind so let's

start with Dy as we've mentioned before

Dy is a pegged algorithmic and

exogenously collateralized stable coin

it's one of the most influential D5

projects ever created and was a huge

factor in supercharging the D5 space

roughly the way it works is you deposit

eth or some other crypto collateral into


the smart contract that has this die

algorithm code and based off the current

collateral to US dollar or eth to US

dollar price it'll mint you some amount

of die you can only mint less dye than

the total value of collateral or eat

that you have this way the system always

has more collateral than they'd have

minted die additionally every year or so

you'll get charged something called a

stability fee users around like 2% and

now you're free to do whatever you want

with your die if you want to get your

eth back you have to give your die back

to the smart contract which will then

burn your die it'll use the current

price of e to figure out how much money

it should give back to you it's because

of this stability fee and collateralized

E that people often refer to this system

as a collateralized debt position since

we technically owe D back to the

protocol at some point so yes all the D

that's an exist

somebody minted from the makeer protocol

and needs to pay it back at some point

if you can't pay your stability fees or

the price of e tanks and now the value

of our collateral is less than the value

of the Dy that we minted people can


liquidate us which means they can take

our collateral protocol always needs to

have more collateral than mint to die so

this is sort of your punishment for not

keeping the collateral up and a way to

save the system from becoming under

collateralized and then there's also a

maker token that's used to vote for

stuff now the reason I give this

overview is I want your brain to be

asking the question hey uh I get charged

to Mint a stable coin all the die in the

world somebody's being charged to have

it out there someone could take my

collateral if I don't monitor the

balance and most importantly why would I

spend money to Mint this stable coin why

would I be the one to do that great

question that is the fundamental

question and we'll get to that usdc usdc

is a classic pegged governed exogenously

collateralized stable coin it's back by

real world dollars in a bank account not

much else to say here USD and Luna the

classic old us and Luna we know it

collapsed but we can learn from what

happened to hopefully prevent it in the

future us was a stable coin pegged to

the dollar algorithmic and endogenous


and it imploded on itself using what we

know about stable coins can you guess

why well since the system was endogenous

once Us lost its Peg Luna became less

attractive to hold since people weren't

holding Luna the price fell and it made

it harder to keep the Peg of us which

made Luna's price fall which makes us

harder to hold its Peg which makes you

see the pattern people still want to try

using these endogenously collateralized

stable coins because they do scale so

quickly so protocols like frax have come

a long way to do some type of hybrid

between endogenous and exogenously

collateralized stable coin Rye Ry is one

of the few floating stable coins where

it's not pegged to any other asset it's

focused on minimal governance being

floating and using only ethereum as

their type of collateral with a nearly

purely algorithmic stability mechanism

in a way one could argue that because

their collateral is only eth the price

of Rye will always be somewhat pegged to

the price of eth but that might be a

longer argument due to these it's

floating algorithmic and exogenously

collateralized now they use some really

cool supply and demand mechanisms to


keep the price stable and nonvolatile

but it's not really important how it

works for the purpose of this video so

once again I'm going to leave some links

in the description if you want to learn

more about Ry the video on screen right

now I think is particularly good at

explaining exactly how it works and

explaining why it's such a good stable

coin for normal average people to have

so now that we've gone over some stable

coins we've gone over the categories why

we care what is a stable coin let's talk

about what they really do we can start

by asking the question okay which one of

these is the best stable coin and to

that I need to ask the best stable coin

for who centralized govern coins

obviously have the issue of centrality

which sort of defeats the purpose of

being in web 3 so maybe we want some

flavors of algorithmic stable coins

maybe that's probably what we want for

web 3 but these algorithmic coins might

feel untested to non- crypto people and

the fees associated with them might be a

little bit scary for me personally like

I said I really love the idea of Rye the

idea is to have stable buying power as


opposed to being pegged to some other

asset and it's algorithmic nature as

opposed to being centralized so it's a

decentralized stable coin that's what we

want but every coin has their trade-offs

and I'd argue there is definitely no

best coin right now the stable coin

that's best for the average person might

matter much less it's the stable coin

that's best for Rich whales might be

what's more important here yes the

stable coins the whales like might be

what's more important now for most

algorithmic stable coins you'll see this

some sort of fee associated with minting

the coins protocols do make money off of

the stable coin systems which I think is

good sometimes they need money for

maintenance incentives for the stability

of the coin or money for improvements so

I do think these fees are good and we

need stable coins for the three

functions of money storage of value unit

of account and medium of exchange but

are you going to be the one to pay these

fees to Mint them and keep them in

circulation someone has to pay to Mint

these coins and often keep paying the

market cap for some of these stable

coins is in the bil ions if there is a


1% fee on these and the market cap is 1

billion we're talking about $10 million

are average people going to collectively

pay $10 million a year to keep these in

circulation no so average people aren't

printing these for the three functions

of money well then who is minting these

so let's play a little thought

experiment let's say I have eth as an

investment and I've bought up all the e

I've sold my house I've sold everything

I own and I've used everything I have to

buy a

but I want more what can I do I can put

my eth into one of these stable coin

protocols get the minted stable coin and

then sell the stable coin for more eth

you might have heard Concepts like

Leverage investing or margin trading and

this is essentially the web 3 equivalent

it's kind of funny why are stable coins

good well because we need those three

functions of money but why are stable

coins minted well because investors want

to make leveraged bets in fact most

stable corn platforms have this as one

of the biggest reasons to minth their

stable coin to multiply exposure or to

maximize your position on some crypto


asset now for sophisticated investors

this isn't new information at all this

is like investing 101 however it does

feel weird that we need stable coins for

the three functions money but that's not

why they're minted so even though I said

I really like Ry as a stable coin for

the people a reason D might be higher

market cap is that investors like The

Leverage opportunity much more than they

like The Leverage opportunity that Ry

offers it could be something else but

that might be a big reason how much

stable coins are minted are based off of

how much investors think they can use

that stable coin to get more exposure to

assets that they really want so I know

we've gone over a lot here and the

rabbit hole really doesn't end there

curve. Finance being one of the most

important protocols for stable coins is

a really interesting story as well my

friend Garrett who teaches about

technology and finance has a fantastic

example as to why a stable coin exchange

might be so important you might wonder

how a stable coin exchange ever got off

the ground is there really any demand

out there to trade $ for $1 then I think

back to my university days one weekend


my laundry pile grew so disgusting I was

desperate to use the washing machine

immediately but the laundry machine took

quarters and I only had dollar bills

quarters were in such short supply

around the dorm room that I was willing

to pay more than $1 for four quarters in

this urgent moment I had specific

utility in mind and that changed my

person person equation for this and a

and curve both looking to launch their

own stable coins soon is going to be

really interesting as well so we'll just

have to see how these unfold I do think

though that we are going to get better

and better at creating these stable

coins because we do need them they are

important and for you developers

watching who want to build one of these

we have some minimal stable coin

contract examples in our defi minimal

repo Link in the description so if

you're looking to tackle this problem

definitely be sure to get started there

I'm really excited for the future of

defi and for the future of stable coins

as I think they are a wildly important

primitive for Defi and I know that this

was a long video but I hope you all


learned something and I hope this gives

you a better idea of what stable coins

really are and how they're created if

you learned something leave a comment in

the comment section if you didn't learn

something leave a comment in the comment

section or if I got something wrong

leave a comment there thank you all for

watching and I'll see you next time

all right well now that we know a little

bit more about stable coins and how they

actually work let's create a new repo

for MOX stable coin CU code MOX

stablecoin CU and at this point you've

been working with moxin you've been

working with titanoboa you've been

working with Viper for quite some time

so I'm going to be going a little bit

quicker here so if you need to slow me

down if you need to pause me feel free

to do so going to create a new folder

we'll do a MOX andit do-- vs code d P

project like so cool I'm going to come

in here we're going to delete everything

we have so far boom boom boom boom

goodbye so now that we've got this up

let's jump into our read me let's talk

about what we're going to be building

we're going to be building a stable coin

so here's how it's going to work users


can deposit ethereum so for example

maybe like $200 worth of ethereum and

then use that to Mint maybe $50 of a

stable coin in this scenario scario they

would have a 4:1 collateral to stable

coin ratio right cuz they would have 200

ID 50 equals 4:1 right we will set a

required collateral ratio of 2:1 so if

the eth price were to drop to 50 others

would be able to liquidate those users

and take their eth out of the protocol

and we would have to incentivize them

some way to actually liquidate the users

so that the protocol could always stay

healthy right because the of the stable

coin is that the price of a stable coin

is always worth

$1 and people would take out these

people would mint these stable coins to

go leverage up to go buy more eth to go

get more exposure to some other asset to

short the dollar Etc we talked about it

a little bit in that video that we just

watched so if this already is confusing

for you that's okay now it's a great

time to pause maybe even grab this

prompt go to Claude and say this is what

we are

building in my Viper SLS smart contract


class I don't get it what's going on and

then paste it in and we'll see Cloud's

usually pretty good and it's giving us

some more information on how this is

working so AIS are really good at

working with Finance please feel free to

work with AI on a lot of these defi

questions here so but this is what we're

looking to build let's get cracking so

let's first create the actual stable

coin and we'll call this

decentralized

stable coin. VI like this we're going to

do

pragma version

0.4.0 we going to add some natspec at

license MIT no colon here at author U at

title the central ized stable coin at

Dev follows the erc20 token

standard uh so we've made a couple

stable coins before we're going to be

grabbing snackmate so we'll do MOX

install snackmate like this now I should

be able to do from snck mate. tokens

import

erc20 then we're going to have to do

from snack mate do o or what is it lib

Oh Yeah from o s. o import ownable as ow

initializes ow

initializes here C20 with ow ex me


ownable wus ow

ownable okay we're going to create an

ATS

deploy Deathcore uncore init uncore

uncore.

init then erc20 do

init and we've done this a few times so

we know we're going to need a name which

will be a

constant string 25 equals centralized

stable coin thank you chat gbt the

symbol looks good decimals look good

except for this should be a uint 8 thank

you chat youb T and we need the

EIP

72 version which will be a

constant

string 20 equals 1 so ERC $20 knit we

need to pass it name

symbol decimals name again and then the

EIP 712 version like so great now we

need to do some exports so we're going

to do exports pretty much all of the

erc20 stuff but we're going to be very

specific we'll do erc20 do I

erc20 this is actually a very clever

fancy way of exporting all the stuff in

the I erc20 interface so we're kind of

like exporting this interface which is


really nice we're also going to we're

going to do erc20 do burn from Burn from

we're going to do erc20 mint erc20 doet

minter. owner owner and. transfer

ownership Tada we might even go an extra

step the header

functions like this even though we only

have one function we might even do do

State variables but that looks pretty

good for our token here now I'm just

going to do MOX compile make sure it

compiles and it's

compiling and great and we're pretty

much done with the actual token now the

way it's going to work is another

contract is going to own it and that's

where all the crazy stuff happens so

nice work here let's go build the engine

now so we going to create a new contract

DSC engine. VI

and in here we're going to do the same

thing we did over here I'm actually

going to copy all of this paste it over

here I'm going to call it title DSC

engine and I'm going to do a little at

notice here notice to talk about how you

would categorize this stable coin so the

collateral of this is going to be what

exogenous because we're going to be

using like eth wed Bitcoin or we I guess


wrapped Bitcoin Etc so it's going to be

unrelated to this protocol the stability

mechanism is going to be decentralized

or Al

algorithmic because it's going to be

this contract that governs what can mint

and what can burn so this is sometimes

also known as the minting mechanism the

value or the relative stability

is going to be anchored going to be

pegged to the dollar or pegged to USD so

it's going to be an anchored

decentralized or algorithmic exogenously

collateralized stable coin here and then

the collateral lateral type of course is

going to be crypto so let's go ahead

let's get started so we want people to

be able to deposit collateral and only

when they've deposited a certain amount

of collateral can they mint

tokens but one of the most important

things is we want to create some type of

white list to Fig to figure out what

tokens we can even use and we should

probably Define that right in the deploy

function so I'm going to make a new vhe

header external

functions and right in our at

deploy we're going to do def uncore init


uncore uncore we're going to take in

deploy the Ploy we're going to take in a

list of token

addresses and I'm going to kind of cheat

and just make this an address array of

size two if we wanted this to be really

cool this could be like a d array right

like a dine array of addresses of maybe

maximum of 20 and then we could have 20

different kinds of collateral but we're

just going to keep this nice and simple

we're going to say you can only have two

types of collateral and the collateral

collateral types are going to be eth and

wrapped Bitcoin so we can even do a

little little dock string we could say

at notice we will have we have two

collateral token types eth and wrapped

Bitcoin like so and since we have the

token addresses we're also going to need

to be able to price the collateral right

so how will I know if I have $20 worth

of eth unless I have have a price feed

we know how to work with price feeds

we've worked with chain link several

times already we know that those are

just going to be price feed addresses

like this and that'll just be an address

array as well and then we should also

get the address of the token that we're


going to own or that we have ownership

of so we'll say DSC address which will

be of type address now I'm going to

create a new vhe header State variables

zoom out just a little bit we'll scroll

up State variables we're going to create

one called DSC which should be a public

mutable of type

iore decentralized

stablecoin and we don't have a an iore

decentralized stablecoin so let's create

that interface iore

decentralized

stablecoin

buy this should actually be

interfaces paste that in here

and I'm going to kind of cheat I'm going

to copy paste excuse me vyi like this

and I'm going to kind of cheat I copy

pasted from the GitHub repo associated

with this because we only have these two

functions that we're really going to be

working with burn from and mint and to

make sure we actually have these it's

best practice in here to also do from

interfaces. iore decentralized

stablecoin excuse me inut import import

from

interfaces import iore decentralize


stable coin stable undor coin boom and

then

implements iore decentralized stable

coin this way this iore decentralized

stable coin this will be the place of

Truth where all functionality that we

need will be defined in here burn from

and mint and we exporting those here

burn from and mint so this will compile

still so MOX compile uh well okay it's

not actually compiling because we didn't

finish building this um but great so

let's do from

interfaces import iore decentralized

stable coin and we need to Define this

down here we'll say DSC equals iore

decentralized stablecoin at address DSC

address and that error goes away great

now these token addresses we can

actually just save this to a state

variable as well we'll say collateral

tokens will be a public

immutable address to fixed sized array

so it'll say collateral tokens equals

token

addresses and then we'll do kind of this

gas inefficient thing but we're doing it

because this will make it so that if you

wanted to you know refill back to this

to be like like I said like 50 of these


this would be pretty easy so this is

going to be the one stipulations that I

say isn't really production because it's

not really gas efficient but I digress

so under our state variables we're going

to save these price feed addresses into

a mapping object of token address to

price feed so we're going to create a

little mapping so I'm going to say

storage token to price feed this will be

a public

hashmap of address to address and we'll

say

self. token to price feed of token

addresses at

index0 is going to be equal to price

feed addresses and index zero and we're

going to do the same thing with token

addresses one and price feed addresses

one the reason we're doing this is this

is going to make it pretty easy to look

up what price feed is associated with

what token right from the GetGo here

okay

nice so now we have our token addresses

our price feed addresses so that we can

price our collateral and our DSC token

now we can create a little deposit

collateral function and we are going to


have an external One external def

deposit collateral

cat all we're also going to have an

internal one but we're also going to

have an internal one def

underscore deposit

collateral we'll do a little pass here

for now so this is going to be very

similar to how a works right people are

going to be able to deposit the

collateral the protocol our DSC engine

will price that collateral and will be

able to figure out how much they can

mint but first we need to obviously let

them deposit this so for depositing

collateral we should probably let them

choose the token

collateral address which will be an

address the amount collateral which

would be a u into 256 we'll say amount

colateral and then uh that's pretty much

it so just those two so in here we first

should do a little assert assert the

amount collateral is greater than zero

otherwise we'll say

DSC

engine needs more than zero for a little

error here we will also make sure the

token collateral that they pick has a

price feed associated with it so we'll


do assert self. token to price feed of

token collateral address does not equal

an empty address or the zero address

here otherwise we'll say

DSC engine token not allowed this and

this is kind of the solidity style

reverts that I'm putting here it's not

ideal actually probably we would do yeah

let's let's do the Viper style needs

more than zero

DC engine in uh token not supported like

so nice okay so now we're going to need

to keep track of how much they've

actually deposited so back up in the

state variables down in the storage

section we'll create a mapping called

user to token to amount

deposited which will be a public

hashmap of an address who's going to be

the user which is going to be mapped to

another hashmap Ash map of an address

which is going to be the token and then

the ENT 256 so when somebody deposits

we'll say

self. user to token to amount deposited

of message. sender of token

collateral address

plus equals

amount
lateral for all like so we should emit

an event because we're updating storage

here so let's create a new type so we're

going to do v v header

types paste here so we'll say oh excuse

me this is not a new type this is a an

event so do vhe header events and this

is going to go and this is going to go

under the state variables so we'll say

event

collateral

deposited and we'll take a user which

will be a indexed

address and an amount which will be an

indexed un

256 like this user

indexed I don't need the

comma this is also a colon looks good so

then down here we'll do log collateral

deposited message. sender amount

collateral and then we will finally

transfer the token to this contract so

we need to do from

ethereum do erc's import I erc20 so

we're going to import the I erc20

interface and then what we can do is we

could

say success

bull equals x call

ic20 token
collateral

address.

transer from message. sender to our self

with the amount flat or all and then

we'll do assert success otherwise we'll

emit DSC engine transfer failed so this

is following that checks a effects

interactions thing we learned briefly

about a while ago so this is the checks

this is the effects which are internal

and then finally we have the

interactions which are external again it

might not be super clear why we need

this CI thing but if you go on to

continue to the security portion of

Cypher updraft you will definitely know

why we want to do this format logging is

something that's so bizarre to me that a

lot of people will put the logging down

here but that's technically wrong um and

can actually result in exploits so this

is the proper checks effects

interactions that we want to work with

here cool so for our external deposit

collateral we'll have it take same

parameters here and then we'll just have

it call

self. deposit collateral thank you chat

gbt just like that now if we were going


to go the extra mile here we would then

also add some natat speec to this as

well we would do like at Ram you know uh

at

pram uh at notice we would talk about

what this does etc but I'm going to skip

that for now if you want to go back

later and add some comments into this I

highly recommend you do so because

that's going to make this look way nicer

and additionally we want to do V header

internal

functions like this and paste that in

here cool so we have a way to deposit

collateral now we have a way to deposit

collateral we probably want to be able

to give people the power to finally mint

the token so let's create that mint

token or mint DSC so we'll create an at

external

external def mint DSC we'll just pass

for now and down here we'll create at

internal deore mint

DSC and they should be able to take an

amount DSC to Mint which would be of

type un 256 so let's do a quick assert

here assert the amount is greater than

zero otherwise we'll throw an airor DSC

engine need more than zero thank you

chat gbt we will need to keep track of


how much each user has actually minted

so up at the top we're going to create

another storage mapping we're going to

say user to DSC minted minted which will

be a public hashmap of address to you

into 256 if we go back down we can now

after we do our checks here we'll now

I'll say self. user to DSC minted of

message. sender plus equals amount oops

amount DSC to Mint like this and what we

want to check like what we said before

is we want to make sure that they have

this ratio right they have some type of

ratio that we defined so we shouldn't

let them mint right we shouldn't let

them mint if they break that ratio so

we're going to have to actually come

back to this so I'm going to do a little

to do because before we can finish

implementing this we need to figure out

okay what's this what's their health

Factor have they broken this ratio so

I'm going to create a new internal

function called Health factor and it's

this health factor that we're going to

use to determine if a user can Mint or

must be liquidated so I'm going to

create at internal defcor health vector

and this is actually going to take a


user address and we're going to

calculate based off of how much

collateral they have and how much

they've minted what is their health

Factor so in order to calculate their

health factor I need what I need how

much

DSC they minted and also how much

collateral collateral they they have

deposited so we're going to have to make

a couple of more functions here so let's

actually make another internal function

at internal called

deore getet account

inforation user address and this is

going to return a u 256 and a u

256 so we're going to return and I'll

even put this in a do string ATS notice

Returns the total DSC minted and total

collateral deposited and we don't need

that second one there and so we're going

to say total DSC minted un

256 equals self.

user2 DSC minted the user

collateral value the total collateral

value deposited right because we want

the total DSC is going to be in dollars

we're also going to need the total

collateral in dollars so total

collateral collateral value in USD uh


and this we're also going to have to do

we're have to create another function we

got a whole nesting amount of at

internal functions this is going to be

defcor get account collateral value

which will be a user address which will

return a u

256 Returns the total collateral value

deposited yep that looks good so what

we're going to do is we're going to say

total collateral collateral value USD un

256 equals z and we'll say for each

token address in collateral tokens we'll

first get the amount that they have

which will equal self. user to token to

amount deposited of user token and then

we'll have to get the USD price of this

so I'm going to have to do 2do a two-d

do here we're going to do a 2do here

because we need another function look at

all these functions that we need at

internal def uncore get USD value of

some token and amount this should return

256 and this is where we're going to use

some price feed information so I'm going

to do pass for now now we've worked with

chain link price feeds a few times so if

you want to just grab this from the


SRC

interfaces aggregator V3 interface St by

feel free to do so I'm going to copy

this create a new interface

aggregator V3 interface .

vyi baste it in there great that looks

good to me now I'm going to import this

into my DSC engine from interfaces

import

aggregator V3

interface like this and in our get USD

value we're first going to say price

feed of type agregator V3 interface

equals aggregator V3 interface wrapped

around the self.

token address to or token to price feed

of the token then we should get the

price now if you look at the GitHub repo

associated with this section you go to

SRC we actually do this thing called

oracle. stale check latest round data

and in in the mock stable coin in the

get repo associated with this we've

actually created this Oracle lib which

has a couple of extra checks to make

sure that the price is not stale so you

can see we have this stale check latest

round data what we're doing is we're

getting the latest round data and we're

basically checking that the time stamp


is newer than I think it's what up at

the top 3 hours so it's kind of

hardcoded to that it's it would be

better to make this modular and

upgradeable depending on the actual

contract that we're working with and the

stale check is kind of this fail safe

where if the price hasn't been updated

in a certain amount of time the whole

protocol basically bricks and pauses

this is actually what we want however

for the purpose of this video I'm going

to be skipping writing this Oracle lib

however for production code you would

want to use something like an oracle lib

but for us we're just going to do um

we're going to say price of type into

256 equals Price feed. latest

answer like this and then we're just

going to return a whole bunch of stuff

first we need to convert the price to a

unit 256 and then we need to multiply

this by some additional amount of

decimals because the price feeds that

we're going to be working with ethusd

and we USD only have eight decimals so

up at the top we're going to make a new

variable called

additional feed Precision which will be


a public

constant 256 which will be equal to 1 *

10 raised to the 10th and we're going to

say we need to convert the price to un

256 multiply it by this additional feed

Precision then multiply this whole thing

by the amount and then divide this whole

thing integer divide by some Precision

amount so I'm going to scroll back up to

the top say

Precision public constant U into 256

equal 1 * 10 ra to the 18th so and this

divided by Precision oh so this is going

to be token of type address and amount

of Type U into

256 oh and this of course needs to be a

static call Price feed latest answer and

this means to be a at view

function and and that looks good and

this is some mathy math stuff trust me

it works if you want to pause and figure

this out for yourself feel free to do so

but so now we have a whole bunch of

to-dos now that we finally have this

let's go back to get a collateral value

because now that we have this get USD

value we can say the total collateral

value in USD plus equals self doore get

USD value of the token and the amount

and then after we do this full loop


we're going to return the total

collateral value in USD now we can go up

to the next um to-do block here and now

we have the collateral value in USD

equals self

doore get

account collateral value for the user

this is a un

256 and then we can return total DSC

minted and collateral value in

usdc and what other two dos do we have

and then finally we can come back down

here we can say self. get account

information User and it'll be total DSC

oops total total DSC C minted F Type un

256 equals z total collateral value in

usdc thank you chat

GPT then we'll say total DSC minted

comma total collateral value USD equals

self. get account information and using

these two we can now create a new

function called calculate health Factor

I'm going to do another little to-do

here I'll do at internal defcor

calculate health factor and we'll take

in the total DSC minted which will be of

type un 256 total collateral value USD

which will also be a un to 256 this will

be return a un to
256 and what we'll say is if total DSC

minted equals equals z return the max

value of a u 256 so if they hav't mitted

any DSC they've only deposited

collateral that's great we'll say you

get the maximum health Factor if they

have Meed some DSC now we need to figure

out okay what basically we want to

figure out what's the ratio of DSC

minted to Collateral value and we need

to create some type of liquidation

threshold so up at the top I'm going to

say

liquidation threshold equals 50 and oh

excuse me this is going to be a public

constant U 256 and I'm going to copy

paste it to make

liquidation

Precision which will be 100 so basically

we're going to say you need a at least a

2:1 ratio so you need to have at least

double

the collateral that you have in DSC

minted and we'll see what that looks

like in a second and how we can math

that we'll say collateral adjusted or

threshold which is going to be U and 256

equals total collateral value USD times

the liquidation threshold and this whole

thing integer divided by the liquidation


precision and if you want to pause and

do the math here feel free to do so once

we have that we can just say return

collateral adjusted for threshold times

Precision divided by total DSC minted so

this will return our final Health factor

and now that we have our health factor

and when we run tests you'll see this

working in reality we can finally do

return self do calculate health Factor

total DSC minted total collateral value

in usdc and then we need this to return

Au into 256 like this now that we

finally have a health Factor we can go

all the way back up to our mint function

and we should say this should revert if

the health factor is broken so we're

going to create a little function for

that as well at internal def revert if

Health

Factor

broken

broken address or user is going to be an

address and then we'll just say the user

Health Factor will be of type un 256

equals Self doore Health factor of user

assert the user Health factor it's

greater than or equal to some Min Health

Factor
for us I'm going to go to the top we're

going to make this a public constant you

to

256 equal 1 * 10 ra to the 18th so if

their health factor is less than this

will revert and that's what we want if

it's greater than it'll pass uh then

we'll just say DSC

engine Health Factor broken if this

reverts great so in our mint DSC we can

now just call self. revert if Health

factor is broken message. sender isn't

that nice now we just did all that work

but then finally we can do X call

dscm message. sender amount DSC to

Mint so I know we just did a lot so

let's do a quick little refresher of

what we just did so we have a way for

people to deposit collateral right it

must be it must be on the allow list of

token addresses we set in our deploy

function they can call deposit

collateral which causes calls which

calls us internal function here and once

they have collateral deposited they can

call Mint DSC but they need to have at

least double the collateral as they

decide they want to Mint we created this

calculate health Factor function which

calculates the health Factor based off


the total DSC minted and the total value

in

usdc and the total value in USD which we

got using the chain leag price feeds and

we did some weird

fancy integer Division and

multiplication and precision stuff but

again if you want to feel free to pause

the video play with it yourself but just

know that this is essentially how we're

going to make sure that 2:1 ratio is

enforced this is the math behind how we

enforce that and if that's enforced then

we go ahead and we call XC call DSC do

mint now the reason that this is going

to work is because on the decentralized

stable coin right when we deploy this

we're going to set the minor to be the

DC engine and we're going to set the

owner to be the DSC engine so only this

contract will be able to Mint

decentralized

stablecoin and that's how we're going to

keep the price parody with the dollar

nice so then finally in the mint DSC

function

they can call they can well they can

pass amount pass 256 and they can do

self doore mint DSC amount


boom okay great so we have a way for

them to deposit we have a way for them

to mint we should probably give them

away to redeem their collateral so let's

make a little external function at

external

external

external external def redeem collateral

and we'll let them pass in the token

collateral address which will be of type

address and then the amount which would

be a un

256 and we're going to have them do a

little self.

uncore

redeem collateral with the same

parameters and then now that we have

this wonderful little revert if Health

Factor broken we can also do self.

revert if Health factor is broken

message. sender so when they pull their

collateral out we'll make sure they

don't pull out too much to break their

health Factor but we got to do this

redeem collateral function so we'll do

at internal internal def redeem

collateral and I'm going to just do pass

for now now quick note that I want to

make when you're actually building code

it's usually not going to be as seamless


as what we're doing here all right then

we're going to do this function then

we're going to do this function then

we're going to do this function often

times the way that I will kind of build

is I'll do a lot of testing as a

building so I'll have like maybe a

deploy script already set up and maybe

like a minimum test setup as well where

I might go okay test getting the pricing

information is correct okay test the uh

Health Factor calculation is good okay

test they can actually deposit okay

let's test that they can can redeem now

as I'm going along this will end up

actually saving you more time in the

long run because you won't have to go

back and refactor everything or there

won't be some weird piece of code that's

broken that oh if you just caught it as

you were coding it you it would have

been an easy fix but for the sake of the

video I'm kind of coding it through but

like I said there's no one right way to

write your contracts to write your code

so this is how I'm doing it here however

when I was first building this that's

more how I was doing it I would write a

function maybe write a test the I would


write a function maybe I would write a

test to test the function I would test

it then I would move on write the next

function write the test for it move on

some people even prefer something called

test driven development where they

actually write all of their tests out

first and then write the code to match

the tests that's something that you can

do as well but anyways so for us redeem

collateral this is going to be an

internal function and and we're going to

make this kind of have some superpowers

here and you'll see why soon so we're

going to say okay token

collateral address this will be of type

address then we'll have amount which

will be a

unit6 and we'll do underscore from which

will be an address and underscore 2

which will also be an address the reason

we're doing a from and a two is because

pretty soon when we add the liquidate

functionality we're going to want to be

able to update these accordingly so up

here when we call redeem collateral

we're actually going to pass in as well

message. sender and message. sender but

later on we're going to have a situation

where these are different and uh you'll


see when we get there so to get started

redeeming collateral we're going to do

self.

user to token amount

deposited of from

collateral address minus equals amount

so we're going to subtract the amount

that they are redeeming we should also

have a log for this collateral redeemed

so I'm going to make a new event event

collateral redeemed this is going to

have a few different parameters we're

going to have redeemed from index

indexed address we're going to have

amount indexed unit 256 and we're just

going to have from which will be an

address and we're going to have to which

will be another address so then we'll do

log collateral redeemed

underscore or I guess we don't need this

or excuse me I guess this should be

token not redeemed from but anyways

we'll log collateral redeemed we'll do

the token collateral address we do the

amount and then the from and then the

two why does it mad at me because I

spelled address wrong okay then we'll do

a little

success bull equals x call


ic20 token

collateral token collateral

address.

transferor 2 comma amount so we're going

to give that token from this contract

back to the user and then we'll do

assert success and if not we'll just do

dce transfer failed beautiful okay so we

have a way to deposit collateral mint

DSC redeem collateral we also probably

want some combinations here so let's do

a little at external at

external

deposit and mint and this will take a

token

collateral address an amount

collateral be a u 256 and a mount

DSC which also be a ENT

256 and we'll just say self

doore deposit

collateral actually CH that looks pretty

good great what else do we need here we

have a way to redeem collateral we also

are going to need a way to burn DSC so

we're probably going to need an at

external

redeem or

DSC token collateral

Catal address amount collateral un

256 and amount DSC U into


256 and in here we're we going to have

to burn some

DSC which we don't have yet we're going

to have to create a little burn DSC

internal function so at internal def

burn

DSC we're going to need to have an

amount you

256 on behalf of an address then a

DSC from which will be an address so

we'll say self. user to D DC minted of

DSC excuse me on behalf of minus equals

amount then we can do X call DSC do burn

from DSC from comma amount and now that

we have this burn from we can do

self. burn DSC Mount DSC

message. sender message. sender so on

behalf of whoever calls this then we can

do

self.

redeem colat collateral collateral

collateral and that looks good chat TBT

thank you and then finally self doore

revert if Health factor is broken

message. sender thank you chat chat GPT

again so again probably one of my

favorite uses of chat gbt is just

hitting tab or get a co-pilot I guess

once you start a line it's usually


pretty good at knowing what the rest of

your line is going to be

here okay so we have pretty much all of

our functionality in here that we need

actually we probably want to have an at

external def burn as well burn DSC and

we want to have an amount to burn bur

and we would just call Self doore bur

DSC amount message. sender message.

sender and then self. revert if Health

factor is broken Okay cool so now we

want to add the main and most important

functionality of this entire codebase

the

liquidation so we're going to create a

new function at external Def liquidate

and we kind of glossed over this but

essentially back in this read me here if

anybody's collateral Falls below the

ratio right if their health Factor Falls

below one we want to liquidate them

basically we want to incentivize people

to take away their money so that the

protocol always stays what's called

solvent we always want there to be more

collateral than there are stable coins

because if there's less collateral and

someone were to call redeem and they

couldn't redeem their collateral well

then the stable coin basically loses its


value and it doesn't become stable

anymore because the whole reason that

this is stable is because you can always

redeem $1 worth of this stable coin for

$1 of the underlying collateral that is

how it it keeps its

dollar so if someone Falls below the

ratio we want to liquidate them we want

to take away all of their collateral and

say uh-uh you are abusing the system so

you will be punished and someone else

will be rewarded for punishing you so

that's how that is going to work and

this liquidate function is usually the

most confusing out of this entire stable

coin section so per normal if you have

questions feel free to work with your AI

feel free to ask in the discussions ask

a ton of questions here because this is

going to be the most confusing part of

the section we're going to liquidate a

user so they're the user has more DSC

minted than collateral so we're going to

say okay we're going to liquidate them

and the way we're going to liquidate

them is we're going to follow a couple

of steps here we're going to first check

if their health factor is bad you know

can they even be liquidated then we're


going to cover their debt by us burning

our

DSC but reducing the their DSC minted

and this is probably the hardest part so

basically we are going to burn our own

DSC but apply the burn to their balance

to their debt to their amount they owe

the protocol then finally we will take

their collateral so that's the reward

we're given for doing this so we burn

DSC we basically we basically call burn

DSC right we call this burn DSC function

which reduces our user to DSC mined but

we call it for them and that's kind of

the the trickiest part so we were we

will so you can almost think of in this

protocol as the amount of DSC that's

Minted as debt you kind of owe the

protocol at some point you got to give

back the DSC that you've minted so

whoever calls liquidate will essentially

cover this debt will cover the DSC

minted and as a reward will be given the

users collateral so let's go ahead let's

write this so we got to say what

collateral that we want to get what user

we want to liquidate and then how much

debt of theirs we want to cover because

maybe they have a huge massive debt and

we can only recover some of it so let's


get started doing this first thing some

classic assert you want to assert the

debt to cover it's greater than zero and

if it's not we'll just revert with needs

more than zero then we want to get the

starting Health factor which would be a

un 256 equals Self doore Health factor

of the user then we want to make sure

that the starting Health factor is

actually less than the Min Health Factor

otherwise the health factor is good

right we shouldn't liquidate somebody

who has a good health Factor so these

are our two checks the checks look good

next we should figure out how much of

the collateral we would get based off of

how much debt we're going to cover so

this is a little bit confusing but we're

going to say the token amount from debt

covered type un

256 equals self.org

token amount from USD and we'll pass in

the collateral and the debt to cover get

token amount from USD and this is

actually a function we don't have yet

what we do have is we we have the

opposite we have get USD value let's do

the opposite let's do at internal at

view def get token amount from USD and


we'll pass in a token address and a USD

amount in way and so this gives us the

price this is going to give us the token

amount like based off the dollar amount

how many tokens are there so it's kind

of the reverse of that so it's going to

return a 256 and we'll say we'll

actually just copy this for btim here

and we'll return USD amount in way times

Precision divided by convert the price

to un

256 let's put this whole thing in

parenthesis here times additional feed

Precision so again this is some mathy

math here essentially what we're doing

is we're saying hey if if I have $100 of

token X how many tokens do I have right

so up here we're saying if I have 100

tokens how much is that worth in US

Dollars down here it's saying if I have

$100 how many tokens is that and the

reason we're getting this value for the

liquidate is we want to figure out what

kind of reward we can give the

Liquidator here so we're going to say

total amount from debt covered equals

self. getet token amount from USD we're

going to be using collateral you know X

and we're going to be covering $100 how

many tokens of collateral is $100 of


that token so hopefully that makes sense

if not feel free to pause and then we're

also going to give them a bonus so we'll

say bonus collateral and this is how we

incentivize people to always be watching

this protocol so that if someone's

Health Factor does go too low we give

them some extra money bonus collateral

is going to be U into 256 equals

this token amount from debt covered

times some

liquidation bonus divided by the

liquidation Precision so let's come up

with a liquidation bonus so up at the

top we'll say liquidation bonus public

constant let's say it's 10 so we're

going to give them 10 over 100 or a 10%

liquidation bonus so now now we can say

self doore redeem collateral

collateral token and we will give the

user that amount of collateral plus the

bonus bonus collateral and we're going

to do it on behalf of the user and we're

going to send it to message. Sender so

underscore redeem collateral hold on

redeem collateral so collateral amount

from is going to be the user who we're

liquidating and two is going to be the

message. sender the person who's


actually doing this once we've redeemed

the collateral we can then do self doore

burn DSC debt to cover user message.

sender so we're going to give whoever

calls liquidate the collateral but we're

going to burn the person has the debt

we're going to remove their debt from

the system because this person's going

to cover it this person's going to burn

their own DSC so once we do that then we

can do ending Health Factor un 256

equals Self doore Health factor of the

user and we need to assert the ending

Health factor is greater than the

starting Health Factor otherwise we'll

say didn't improve health Factor right

because the whole purpose of this is to

improve the health factor and then we

should also do a self. revert if Health

factor is broken of message. sender so

we don't accidentally deplete the

message. sender's own health factor and

surprisingly that's actually our whole

contract wasn't as long as you thought

it was or maybe it was depending on how

long you kind of looked into stuff but

this is essentially it

so we have a way for people to deposit

collateral into the system and that

those deposits will allow them to mint


DSC mint this stable coin they can also

redeem their collateral and they can

burn the amount of stable coins that

they've minted if all of a sudden their

health factor is bad meaning their ratio

of collateral to DSC minted is bad other

people then come in and liquidate them

and they are incentivized to do so

because they get bonus collateral to

lick them to liquidate them so you

really don't want to be liquidated

because someone's going to take a lot of

your collateral to just slightly improve

your health factor and we don't want

that so this is kind of our final code

base but not quite yet cuz you know

we're trying to test this you know we're

trying to make sure this works so let's

go ahead over to our script and let's

create a deployed. now in the GitHub

repo associated with this you go to

script we have everything kind of in

this deploy DC engine uh we are we're

going to create two more we're going to

do

deploy

dscp and deploy DSC

engine. so we have to deploy our

decentralized stable coin first so we'll


do a little Def moccas and Main deploy

DSC def deploy oops deploy DSC and we'll

say from SRC

import

decentralized stable coin and we'll do

decentralized stable coin. deploy and we

will return this so this is going to

return a Viper contract which we're

going to say from m. booat tools

import Viper contct cont ract I'm going

to do UV add moxin just to get rid of

those squiggly lines I'm going to hit

yes to update my python environment in

my vs code that looks great and we'll

also have this return a Viper contract

as well cool now in deploy

dsce deploy DSC engine we're going to do

defa deploy DSC engine which will take a

DSC which is a Viper contract

as an input variable so we'll do from

moccasin booat

tools import Viper contract and what

we'll do is we need a number of things

in here we go to the decentralized

stable coin engine in our init we need a

list of token addresses and price feed

addresses so what I'm going to do is I'm

going to go to our moccasin

DOL I'm going to go ahead and delete

everything
and we're going to grab some contract

addresses let me zoom out a little bit

here so I'm going to do

networks. ZK sync. contracts and because

you've done this a 100 times at this

point I'm not going to make you do it

again if you go to the MOX stablecoin

Cipher updraft we can grab all these

addresses from the ZK sync Network we

can see we have ethusd price feed here

we and wrapped Bitcoin coin we and R

Bitcoin are going to be our two

collaterals and we have price feeds for

both of them so I'm going to go ahead

copy these

all boom paste them in here and then if

we scroll up we see we have some mock

deployer scripts as well for everything

I'm also going to copy all of these

paste them into here as well because

we've written these kind of deploy mocks

100 times as well and because of that

I'm also going to save you all the

trouble you can go to scripts mocks

deploy price feed we can grab this

because we've already done that I'm

going to add it to mine as well new

folder new folder

MOX deploy price fee. py paste this in


from Sr c. mocks import mock V3

aggregator which means we need a new

folder mocks in here and a new mock B3

Agra G

tor. VI this is also one you've done a

few times now so I'm not going to make

you do that either we're going to grab

that from SRC mock mock V3 aggregator

Dov we're just going to go ahead and

copy this whole

thing and paste it in

here looks good to me so from

SRC MOX mock V3 aggreg that looks good

now we have a little deploy price feed

here that looks nice great we're also

going to need a deploy collateral script

let's go ahead let's create that to

deploy collateral. Pi this one's also

going to be pretty simple I am going to

make you write this one because we

haven't done this that often return

deploy collateral coll

def deploy collateral do a little print

ploying token dot dot

dot mock token contract equals we're

going to need a mock token as well you

can copy this as well from the giab repo

associated with this because you don't

need to spend your time and efforts

writing mock contracts when they're


already done for you so mock mock token.

byy B that in and now that we have that

I can do from SRC MOX import mock

token and I can just say mock token.

deploy like

this I can actually just do return mock

token. deploy

lovely okay then I'm going to need

deploy D youc okay

lovely now that we have all of that

stuff where where even was I deploy DSC

engine deploy DSC deploy DSC engine oh

okay now that I have all that stuff we

can finally do from moccasin dot config

import get Active network Active network

equals get Active network now we'll say

btcusd equals active Network dot

manifest

named

uh what do we call

it btcusd price feed BTC USD price feed

paste ethusd will be ethusd price feed

then we'll say wrapped Bitcoin equals

active network. manifest named wrapped

Bitcoin and then we'll do the same thing

for we here we we now that we have our

price feeds and we have our tokens and

we've given them deployer scripts so

that if we run on pvm our pvm will


deploy them as mocks for us I can

finally do

DSC engine contract equals from

SRC import

DSC engine DSC engine. deploy and it

takes in what again takes token

addresses and price feeds so we're going

to say wrapped Bitcoin and weth let's be

more explicit. address we. address comma

btcusd do address comma ethusd do

address comma

DSC

then we're going to

say on the DSC contract we want to do

DSC do set Minter to the DSC engine

contract. address to true and we also

want to do DSC do

transfer

ownership to the DSC engine contract

address and then return DSC engine

contract

okay and then if we want to we can do a

little defa moccas

main I'll do Active network equals get

Active network DSC equals active

network. manifest named

DSC go to our moxen to TL we're actually

calling it decentralized stable coin so

let's do medifest named decentralized

stablecoin and then


return Ploy DSC engine DSC do

address so let's try this out see if

this works MOX run deploy DSC

engine address has no attribute set

minor so we go here

DFC oh uh yeah DFC is being set to a

address instead of a contract at the

moment that's not right

because this shouldn't be dc. address

this should just be straight up DSC

let's try one more time deploying token

deploying token and we'll even do a

little print here print F DSC engine

deployed. here clear

run o this is coming along great my

scripts seem to be working I don't know

if the code base if my code is actually

good but I can rip through the deploy

scripts really quickly because I've done

them a 100 times I can write a stable

coin really quickly I haven't done that

100 times Well I have but you haven't

done that 100 times but you're getting

the feel of it and this is incredibly

exciting now at this point you're

looking pretty good actually but what we

need to do of course you already know is

write some tests we need to to make sure

this is actually going to do what we


want it to do so let's come to our test

area and let's begin writing some tests

so since we're going to be writing a lot

of tests let's go ahead let's do a comp

test.py and let's start creating some of

those fixtures that we know we're going

to have to make and I like to start with

a little vhe header oops vhe header

session scoped what are the fixtures

that are going to last for the entire

duration of a test run so let's go ahead

and import py test I'll do at pest.

fixure scope

equals session we'll do def Active

network might be useful and we'll just

return get Active

network like this and we're going to

have to

do

from moccasin doc config import get

active

Network all of our tokens are probably

not going to change at all so at pest.

fixture scope equals session death we

return uh and this will actually take

in Active network as an input

fixture return active network.

manifest named we we're going to do the

same thing for wrapped Bitcoin so

wrapped Bitcoin
we're going to same we're going to do

the same thing for ethusd so we'll say

ethusd eth usdc price feed I think

that's what we called it right marks.

toml eth USD price feed great we're

going to do the same thing for Bitcoin

USD BTC BTC USD BTC USD now if you

pointed out hey Patrick um wrapped

Bitcoin and Bitcoin technically have

different prices you are absolutely

correct and this would be something that

would show up in a Security review that

the price feeds actually should be

different WRA Bitcoin and Bitcoin aren't

necessarily the same and there's a

little bit of risk in assuming that they

are the same so these are going to be

our session scoped fixtures let's create

some function scoped ones now V header

function scoped paste this down here

we're probably going to need at pest.

fixture we're probably going to need def

DSC so we'll do return active network.

manifest named

DSC we're probably going to need pest.

fixture def DSC or decentralized stable

coin engine and this will take all of

these other fixtures that we've created

so it'll take the decentralized stable


coin we wrapped Bitcoin ethusd and

Bitcoin USD and we can do return return

deploy DSC engine pass all these in

which means we have to pull this in from

the script so from script. deploy DSC

engine import deploy DSC engine great

and we will probably need some more

fixtures as well but let's leave this

like this for now this is looking pretty

good so to get started with some tests

we should first do test

DSC engine. Pi we should also do oh

actually let's create a unit folder and

we'll put this in here we should also

create a test

dscp but you know for now I'm just going

to put this in here and when we get to

the workshop you sure know it we're

going to have you create some more

yourself so these these these two tests

are rightly in the GitHub repo

associated with this lesson but you

should go ahead and you should write

more tests yourself we're going to go

ahead we're going to write some unit

tests for the DSC engine we're going to

write some of them and then I'm going to

tell you to write the rest of them very

shortly if you go to the GitHub repo

associated with this section and you go


to tests you go to unit test DSC engine

there are a lot more more tests in here

than what we've gone over traditionally

and this is the minimum amount of tests

that I want you to write by the end of

this project we are soon going to get to

the workshop where the workshop is you

going to be writing tests if you can

write all the tests here if you can

really get that coverage up above 80%

that's going to be a sign that you're in

a good spot so let's write a couple of

tests together and then we're going to

leave the rest for you to write once we

get to the workshop I'm also going to

show you as well I'm going to show you

the test fuzz setup as well and then I

want you to take a few hours trying to

write some fuzz tests yourself so we're

going to get you set up with a couple of

unit tests a couple of fuzz tests and

then I want you to go take a crack at it

so let's write a couple of unit tests

together so let's first do a little so

what do we want to test well if we go to

the DSC engine we probably want to test

that our init is correct so maybe we say

Okay def test

reverts if token
lengths are different like what if we

pass the wrong tokens so we'll do

DSC eth USD

btcusd we wrapped Bitcoin as parameters

here and we'll do from script or excuse

me from

SRC import DSC engine this and we'll do

with pest. raises and code error so this

is we'll do import py test and this

encode error is something that we're

getting from eth which comes built into

moin we'll say from e. codex. ai.

exception

import import encode error with P test

that raises encode eror DSC engine.

deploy and we're going to give it some

bad parameters we're going to do WAP

Bitcoin we and then we again and then

just

ethusd

btcusd this should air and we can test

this with MOX

test key error DSC and we got a

different error

uh so that's bad actually so let's

scroll up let's debug this okay this is

the get or deploy

Nam saying return active network.

manifest named ah yes in the com test

it's not DSC it's going to be


decentralized we called it decentralized

stable coin so this needs to be

decentralized stable coin let's clear

run this again boom now it's passing or

we could run this test in specific MOX

test- K paste it in oh it's not running

this test for some reason because it

should be test DSC engine not test let's

try it one more time oh getting another

one bad

args expected three got two oh we forgot

to also pass in DSC do address here now

let's try this and it passes Mark test

all three now pass

and this passes because this reverts

nice now I'm going to write just one

more test and then I want you to write a

ton of tests to get the coverage up so

let's do a little deposit collateral

test so we'll do def test

reverts if

collateral zero and we'll even do a

little beheader

deposit

collateral so that we know these tests

are going to going to be about deposit

collateral and so in here we're going to

need

dsce we're going to need we and we're


also going to need some user so back in

our conf test let's create another

fixture called atpy test. fixture def Su

user and we'll give this user some we

and some wrapped Bitcoin to start so

we'll do like entropy entropy equals 13

or whatever entropy you want to do and

we'll say account equals account. create

entropy this will give us a random

account we've learned a couple of

different ways to make random accounts

but this is what we're going to do we're

going to do from eth account import

account and we're going to say boa EMV

oh we got to import boa as well import

boa boa

env. set balance

of account. address to some balance

let's set up at the top we'll say

balance equals 2way 10 ether let's

import from eth

utils import to way so we'll give this

user 10 eth to start with and we will

also do with Bo em. prank account.

address we'll say

W.M mint and we'll do rap bitcoin. mock

mint and return account. address so in

our mock tokens that I gave you they

each have a mock mint which just gives

10 tokens to the message. sender there's


also a mint amount where you can mint a

specific amount in here so now that we

have this sum user they have collateral

that they can actually deposit but if we

say they want to deposit zero we should

revert so we can do with bo. em. prank

some user we. approve

dsce comma

collateral

collateral amount so we don't have any

collateral amount let's go over to our

com test let's create a a collateral

amount and we'll say this equals 2 way

let's do 10 ether for this as well and

then in this test we'll say from conf or

uh test test.c test import collateral

amount and we also have to import boa

import boa great we. approve and we can

do with boa reverts dc. deposit

collateral we Z and we could put the

revert code in here as well if we wanted

but I'm just going to run MOX test oh

deploy DSC engine takes one positional

argument but five were given uh on the

fixture go to com test

deploy DSC

engine five were given that's correct we

only need passin

DSC but we still need all of these as


requirements because we need to make

sure that all of these contracts have

been created before we can call this so

that is correct let's run test again and

everything passes

fantastic now Workshop one is very

simple if we run MOX test D coverage

let's see what we get get a whole bunch

of stuff here we care about DSC engine.

VI and we are at 9% your Workshop your

first Workshop here is very simple get

this above 80 now if you've been

skipping the workshops you shouldn't do

that but this is one you especially

shouldn't skip I really want you to

drill in writing these tests and

understanding these tests this is a

great time to work with AI and use AI to

write these tests and these are just the

unit tests right we're not even talking

about the fuzz tests here here if you do

get lost we've got a ton of tests in the

GitHub repo associated with this section

so you can come back here and you can

pick and choose any number of the tests

in here or multiple of the tests in here

but I really want you to get this down

because writing good tests is a

prerequisite to deploying your contracts

you cannot get a security review you


should not deploy unless your tests are

Ironclad so you should get really good

at writing tests I want you to pause I

want you to do this workshop and I want

you to write the rest of these tests so

pause the video write these tests and

refer to the ones that I wrote and

unlike all the other ones where I say

hey don't use any help feel free to use

some help with the ones that we wrote

however don't just like copy paste and

say hey look I did it try to really

write these yourself try to take at

least 30 minutes to an hour to write

some tests yourself so that really

understand what's going on so pause the

course write some tests and I'll see you

soon all right welcome back did you

write some tests because if you didn't

you're only cheating yourself the reason

we want you to pause and write these

tests is because it's absolutely

critical that you understand how every

single piece of this codebase actually

works so if you did write some tests

great job if you wrote some tests and

you struggled a bit that's okay that's

why for this Workshop in particular I

know we don't always do this but for


this Workshop we have written the tests

here that you should follow along with

some ones that should have come to mind

Hey test reverts with unapproved

collateral can deposit collateral

without minting can deposit collateral

and get account information you should

test to see that it actually reverts if

the DSC breaks the health Factor when

you mint the DSC should tested that you

can mint once somebody deposits

collateral and so on and so forth so if

you haven't written the tests be sure to

pause write the test come back here and

ask questions come back here and compare

and if you don't understand why some

tests are in here great go to the

discussions in the course I'll scroll

all the way up in here go to the

discussions ask a question ask your AI

Etc but anyways let's

continue so now that you have written a

lot of unit tests great job you know

what's next that's right we're going to

write some fuzz tests so I'm going to go

ahead and get you started here but

similar to the unit test I want you to

take some time and write your own fuzz

tests as well so let's go ahead let's do

some fuzz tests together let's create a


new folder call it fuzz and we'll just

call our test file test fuzz. piy like

this so to get started working with

fuzzing we're going to need to do from

hypothesis

do

stateful import rule based State machine

like this and we'll do class stable coin

buzzer rule based State machine like

this we'll do def under Thunder

init

self

super do Thunder and it thunder and and

same as what we did with the St and same

as what we did with the erc20 all those

lessons ago we're going to initialize

our test Suite here with the initialize

function or excuse me with our

initializer and we also have to import

ini she all lies and we can do at she

all

lies

def setup self

and here's where we're going to set up

all of our contracts so we'll do from

script. deploy DSC import deploy

actually deploy DSC it's import deploy

DSC from script. deploy DSC engine

import deploy DSC


engine and in here we'll have self. DSC

C equals deploy DSC self. dsce equals

deploy DSC engine and we'll pass in

self. DSC we'll also probably want to

get like we the price feeds Etc so let's

go ahead and also do Active network

equals get Active

network let's grab that from moxin Doc

config import get Active network we say

self. we equals active network. manifest

named We copy paste this line for

wrapped

Bitcoin copy this copy paste this line

for

ethusd and this will be ethusd price

feed copy paste this line for coin USD

for

btcusd nice okay so now we have those

contracts as well and let's create an

array of users as well so I'm going to

say self. users equals this is going to

be some clever array

manipulation address of 0x plus let's do

from eth

constants import excuse me e. constants

excuse me import zero address plus zero

address and then we need to import

address from Boa do

util a import address this will be zero

address. heex and then we'll say


while address

0x plus Z address. heex oops in well

thanks

JT wow it pretty much got the whole

thing s. users equal oh no it almost got

the whole thing self. users equals boa

env. generate address or uncore in range

let's come up with a a user size at the

top we'll say users size equals 10 I in

range user size and then we need to

import

boa okay so this is just some clever

setup here to have a users array of 10

different users and we can even do like

print self. users let me just show you

what this looks like let's initialize

this at the bottom we'll say stable coin

buzzer equals

stablecoin buzzer. test case and then I

should be able to now do grab this do

MOX test- s s-k paste this in zoom in a

little bit type St corn fuzzer defines

no rules uh good shout I should have a

rule so let's import a rule real quick

just so I can show you what I just did

here so rulebase State machine

initialize I need to import rule as well

and let's just do at rule def pass me

pass now it should work let's try again


pass me takes zero positional arguments

but one was given it's cuz I need give

this self let's try this one more time

ah boom okay so it's printing a million

of these um but you can see it's just

kind of an array of 10 different

addresses right that's what we end up

generating with that clever code there

nice let's get rid of that rule let's

get rid of that print line so we have

our setup here let's now create some

rules for our protocol to work

with and let's also work with an

invariant now we haven't actually worked

with the invariant keyword but we know

what an invariant is right what's an

invariant again it's an invariant is

going to be the property of the system

that should always hold true that should

always be true and that's what these fzs

are really powerful really good at

testing whether or not these invariants

are broken we did them previously by

doing like at Rule and then doing like a

rule like defa um minting must

increase user balance or something right

and then then we would call like the

mint function and then we would check

you know check that the balance

increased right and we can check


invariance through rules but we can also

check invariance through this invariant

keyword so in hypothesis fuzzing using

this invariant keyword essentially what

will happen is between every single rule

that's run it'll run this invariant

decorated function will be run after

every rule R and can raise an exception

to indicate failed invariance so this is

basically a way to just every single

time anything happens you automatically

always run our invariant so looking at

our stable coin system we want to ask

the question what is an invariant we

should test and go ahead pause the video

try to think of an invariant that we

should test should be remember an

invariant is going to be the property of

the system that should always hold true

so go ahead pause the video try to write

down and think of it in variance that we

should test for our testing Suite here

so there's lots of different invariants

that we can actually use here in fact

the trailer bits team or the krytic team

has this repo called properties where if

you scroll down in here they have

Properties or invariance for tons and

tons of different basic smart contracts


for example in rc20 they've written some

invariant tests or Buzz tests in a

different framework but if you go to

test erc20 or hardap go to the test file

in here CCT test. or CCT test x.s scroll

around in here now if you'll see they've

got this whole test Suite where each one

of these functions is a property or an

invariant that should hold for an erc20

so there can be a lot of invariants for

different protocols and it's up to you

as a developer to figure out which ones

are the important ones and which ones

you should test in your fuzzer so for us

here's the one that I'm going to do one

of the things that's critical for our

protocol to have for the whole thing to

work is the protocol must have more

value in collateral than the total

Supply right because the reason this

protocol works is because there's more

collateral than there is DSC or there is

the stable coin minted so this is going

to be a protocol this is going to be an

invariant that we always want to hold

now there are obviously a number of

things that can affect this what happens

if there's a drastic change in a price

feed for example the price of eth in one

block is a ,000 and the next block is $5


what if there's a bug somewhere in the

contract these are the things that we

want to find out what happens in our

fuzzing test and this is where fuzzing

can be incredibly powerful because it

can do a lot of this stress testing for

us so I'm actually going to start off

writing this invariant I can do that by

doing this at

invariant keyword which I should have

imported from up top and in here we'll

say def

protocol must have more value than

total Supply excuse me so to test this

we'll just say total

Supply equals self. DSC do total

Supply like

this total Supply equals then we'll say

the amount of we

deposited going to equal self. we

balance of self. dsce do address so how

much does the decentralized stable coin

engine have we're going to do the same

thing with wrapped Bitcoin self. WRA

bitcoin. balance of self.

d. address we're going to get the we

value of course by doing

self. dsce doget you D value of self. we

and the we deposited we're going to do


the same thing for wrapped

BTC self. WRA

BCC wrapped BTC

deposited and then we're going to write

assert that the we Value Plus the WRA

Bitcoin value is greater than or equal

to the total Supply like this

and we could even run our fuzzer right

now of course nothing's going to happen

because no rules are defined so I take

it back we can't write run it right now

so great now we have an invariant here

where we're always going to be checking

that this holds

true so let's go ahead and let's get

started creating some rules let's create

our first rule called mint and deposit

or deposit and mint and these rules

remember are not just rules but they

also Define the actions that we can take

on our system we can we can optionally

add asserts in these rules I'm going to

skip writing the assert because this

invariant is really the only thing that

we're going to be testing here so I can

do add rule um and let's just leave it

blank for now we'll say def oops say def

deposit and mint self pass so how do we

have this rule actually deposit on our

protocol well we could do you know uh


self.

dsce do deposit collateral oh actually

sorry we should just have this be like

deposit collateral so we could do like

self. dce deposit collateral call the

function but we probably don't have any

DSC we probably don't have any

collateral to deposits so we should do a

couple things number one select a random

collateral then number two deposit a

random amount so how do we actually

select a random collateral here well

this is where we're going to use these

rule inputs so we'll say collateral seed

equals and up at the top we're going to

import those strategies from hypot

thesis import strategies as St so

collateral seed is going to be St do

integers Min value is going to be zero

max value is going to be one since we

only have two types of collateral and

this is going to give us a random number

basically that's going to be either 0o

or one and down at the bottom we can

create a little helper function defcor

get collateral from seed and we'll say

self seed and we'll just do if seed

equals z return self. We else return

self. WRA Bitcoin so basically we're


going to get a random collateral to

deposit one or zero and we could say

colateral equals self self. get

collateral from seed collateral seed

cool so that's how we're going to choose

a random uh collateral amount we also

need to pick a random user so we're

going to do the same thing in our rule

we'll do comma user seed user seed

equals St do

in we'll say Min value equals

z max value equals going to be the users

size minus one like this and then to

pick a user we'll say user equals self.

users user seed oh and we're going to

pass the user seed here too and this is

how we're going to pick a random user

right so maybe we'll get four and we'll

pick the fourth person in the array and

get a random user like that cool so we

picked a random collateral we picked a

random user let's also pick a random

amount so we'll do a final one amount

and the amount is going to be how much

collateral we're going to put in so this

should be a un 256 strategy so to get

the boa strategies we'll do from boat.

test.

strategies

import like this and now we can do


amount is going to be a strategy U into

256 where the Min value is going to be

one because we have some reverts on if

it's zero

and let's come up with a Max deposit

size just so that we don't run into some

weird like U and 256 bound array issues

so we'll say Max deposit size equals 2

way th000 ether and then got to get 2way

in here from eth utils utils import

import tway like so lovely and so for

depositing here we'll say the max value

is going to be the max deposit size like

this and now we have an amount to

deposit so we have a collateral we have

a user let's go ahead now and let's have

them deposit this amount so we'll say

with bo. prank user we'll first mint

this collateral so actually let's yeah

let's change this to Mint and deposit so

let's first mint this user some

collateral because they probably don't

have any right so we'll do collateral.

mint mint amount and we can do this

because we have in our mock token we

have this mint amount function that we

added specifically for testing so we can

mint them some amount so we'll say

collateral. mint amount we pass in


amount we'll do collateral. approve

self. DS c. address add comma amount

amount oh we need to pass this in here

as well amount there we go and then

self. DS c.

deposit

collateral collateral and amount cool so

we're going to Mint and

deposit uh if we want we could even do a

little print depositing

collateral and we could say print

collateral

dotame say print Mount like this and if

we run our fuzzer now with- s we should

see all these prints kick out oh unless

I messed something up did you mean Min

value no I meant mix value of course no

I meant Min value of course

uh no strategy available for type string

U into

256 cuz this is unit uint 256 and now

let's run this again there no attribute

get USD value or we calling get USD

value down here get USD value it's

because in our DSC engine I have not

added this external view function so I'm

going to make a new section here B

header

external view B this in we'll do at

external at view def get USD


value and we need to pass in the

collateral address and the amount so we

need to have

collateral collat all address which

would be an address and an amount which

is a 256 it should return Au into 256

and if you don't have a unit test for

this already that would be bad we would

need to write the unit test here first

I'm going to skip though because I've

already written a unit test outside of

me filming and then we'll return self.

getet USD value collateral address and

amount let's go see if that's right

collateral address and amount that looks

good okay so now we have that function

oops let's run this again and great we

can see deploying token DC deployed at

depositing collateral choosing we

choosing an amount we choosing an amount

we choosing an amount and then we ran

into an error module boa has no

attribute prank it's because it should

be boa EnV bo. env. prank let's try this

now ah much better

and does it ever pick wrapped Bitcoin I

don't see any wrapped Bitcoins happening

in here that's because

go to our mock token the name is always


we so okay I guess that makes sense why

it's always W even though we named it a

Bitcoin at agress Okay cool so it looks

like this is working pretty well nice so

we are randomly calling mint and deposit

let's also randomly call redeem so we'll

do at rule we're actually going to do

pretty much the exact same thing as what

we did up here collateral seed user seed

but instead of amount we're going to do

percentage and this is going to be the

percentage of collateral we want to

redeem st.

integers we'll say the Min value will be

one the max

value will of course be

100 and we'll say def

redeem collateral say self collateral

seed

user seed and

percentage like this we could say user

equals self. users with the user seed

the collateral is going to latal is

going to be the self.org

collateral from seed collateral seed the

max

redeemable is going to be self.

dsce do get collateral balance of user

with the user and

collateral and this is another function


that we need to check to make sure we

have

dsce or D Center DSC

engine we don't so let's create this

function at

external at view def get collateral

balance of user it looks like chat is

given

me this output user token amount user to

token amount deposited yes this looks

correct to me great we should write a

unit test for this of course I'm going

to skip it because I already did

elsewhere so their balance is going to

be the maximum amount that we can

actually redeem so we can say to redeem

is going to equal the max

redeemable times the percentage

percentage integer division by right

because we don't want any decimals so

we're going to do the double slash to do

integer Division and then we'll say

assume to redeem greater than zero

because if it's zero then this will

error assume is another tool we can

import from hypothesis and just do it

from here so we'll say from

hypothesis import

assume and what assume does is it'll


skip running this step here if two

redeem is equal to zero or somehow less

than zero then we can just do with bo.

env. prank user self. dsce do redeem

collateral collateral comma to redeem

and just with this we can run our test

Suite again we can run our test fuzz

again and all this stateful fuzzer is

going to do is going to Mint deposit

redeem mint deposit mint deposit mint

deposit redeem redeem redeem redeem mint

deposit redeem mint deposit it's just

going to go back and forth and it should

never break our invariant because

there's never any DSC minted and I ran

into an error

ings integers

integers and spelling would be a

superpower for me if I could nail it and

boom looks like it's running deposit a

whole bunch of collateral and it's

running our fuzzing test suite and of

course our fuzz test here passes because

well we're not doing anything

interesting we're not uh minting any

tokens still

so all right great so we have a way to

Mint collateral and redeem collateral

obviously though that's not going to

break our invariant here right because


we're never actually minting any DSC so

let's go ahead let's make a way to

actually mint DSC and in this one we're

going to do this a little bit funky and

you'll see what I mean so we'll do at

roll user seed we'll have a random user

once again st. integers with a Min value

of zero max value actually I'm just

going to copy I'm going to copy just

everything from mint and deposit CU

we're going to be pretty similar here

except at first glance we probably won't

need a collateral seed I'm going to

comment it out but we secretly will need

it and I'll show you why in a second so

then we'll do def mint DSC this will

take in self the user seed the amount

and the collateral seed like this and

we'll say user equals self. users of

that user seed get a random user and

then we could just do self. dc. mint DSC

amount now right here we can go ahead

and run this oh excuse me this is

actually with bo. em. prank user like

this now we can go ahead and run this

and I'm going to tell you right now this

is going to fail so let's go ah and run

it oh uh well failed

because I got rid of collateral seed now


let's go ahead and run it and it'll

still fail but for a different reason

okay this failed here

with we can see this line state. mint

DSC amount equals 1 user seed equals z

because Health factor is broken so

anytime we send a transaction here our

fuzzer is going to fail it's going to

automatically fail now there's a number

of ways we could get around this we

could update our

entire class here so that any failed

transaction we just let through but

ideally don't want to do that ideally we

want this to work with valid

transactions so what we could do is we

could say okay we could do a try catch

and if these are new to you in Python

you're going to learn about them right

now we could basically say Hey try to

call this function but we'll say accept

boa error as e and we have to import boa

era so we'll scroll to the top we'll do

import excuse me uh from Boa import boa

eror and we'll say if we'll say if what

was the error if Health factor is broken

is in the error then we're going to

actually give this users some collateral

so that they can mint so we'll say if

DSC engine Health Factor broken is in


and this is where it's going to be a

little bit funky Str Str e do stack

Trace

z. VM error I know that's kind of really

annoying the way we then I'll do like a

little pass the way we found this was

you know I could do like a little break

point here run this test again and we'll

drop into an ipdb shell here like what

we see here and if we Type e we can see

the air here right because we have

essentially hit this spot and the

breakpoint drops us in the Shell so we

can view what the aror looks like just

by typing e and if we paste in this e.

stack trace. VMR we get kind of the

bites of the air then if I do string

stringified this is kind of the the

error directly from Viper so that's how

we were able to get that and let me kill

out of this so if this is in the error

if we have this error inside the error

then what we're going to do

is we're going to go ahead and we're

going to give this user some collateral

so that they can actually mint the DSC

we're going to give the user collateral

they're going to deposit in and huzzah

so I'm going to uncomment this and I'm


going to add the collateral I'm going to

add the collateral seed as a parameter

to this function and now we'll say colet

or all equals self. uncore get

collateral from from seed give it the

collateral seed we'll say amount the

amount of collateral we want them to

deposit is going to be self.

dsce doget token amount from USD and

we'll say collateral. address and amount

so we might not have this

function DSC engine we have an internal

one get token amount from USD where we

give it a token an amount of dollars and

it'll give us the token amount of those

dollars so let's actually make

this an external view so we'll say right

here external

external at view def get token amount

from USD looks like my get up co-pilot

gave me the whole function here and this

looks correct to me so I hit tab that

looks good now I can call this I can get

the amount and this amount should be

enough to cover how much DSC I want to

Mint and we'll just say if amount equals

zero cuz we can't have zero amounts

we'll just say amount equals 1 and then

we can call our rule up here mint and

deposit so then we can say self. mint


and deposit amount collateral seed and

the user seed and then once they've

deposited some collateral then we can go

ahead and we can run self. d dce mint

DSC amount because now they will have

some collateral and we should be good to

go here great okay so now let's go ahead

and run this fuzzer and see if we get

that same error let me get rid of the- s

so that we don't get all those print

lines okay we ran into a different era

here DC needs needs more than zero for

deposit collateral scroll up we see DC

engine needs more than zero for some

reason we're depositing

zero ah okay collateral seed user seed

amount okay collateral seed user seed

amount I had these in the wrong order

let's try this now and obviously we'll

have to wait some time if you want to

put the print lines it back in and do

the- s so you can see them being printed

out feel free to do so and this indeed

passes

excellent lovely okay so we have a way

for people to Mint

DSC now we're going to get into what are

probably arguably the most important

pieces what happens when the price


changes so I'm going to make a new rule

at Rule and this is going to be called

def update

coatal price and this is going to update

the price of those assets now we want

this to be somewhat realistic we want

this to to be somewhat realistic so we

could have the price update you know

from $1,000 to $0 in a block but that's

kind of ridiculous so let's have this

price updater update the price to be you

know 10% or 15% greater or 15% less than

it was the previous block this way we'll

actually give Liquidators time to jump

in and liquidate and keep the protocol

solvent so just by us updating the price

we should actually get a failed Buzz

test before we write our liquidation

scripts so for uh this rule we'll say

percentage new price equals st. floats

we'll have this be a value like you know

Min value of uh 85 so we're going to

times we're going to multiply the

current price by 0.85 or max value of

1.15 so this will be a 15% increase or

15 % decrease on the current price we

will say uh and then we'll also need a

collateral seed which will be st.

in Min value of obviously zero max value

same as always is going to be now first


we're going to have to get the

collateral collat all equals thank you

get up co-pilot and then we have to P

self collateral seed and percentage new

price thank you get up co-pilot so

collateral is going to be the self.

getet collateral from seed collateral

seed then we'll say price feed equals

well we have to do self. dsce doget or

excuse me dot uh what is it token DSC

what is it token to token to price feed

token to price feed of the lateral.

address and we need to wrap this up in

the price feed contract so up at the top

we're going to say from uh SRC MOX

import mock do we have a mock V3

aggregator great mock V3 aggregator and

then means down here in our price feed

we'll wrap this whole thing up we'll say

mock V3 aggregator do this address here

lovely and then we'll say current

current price equals

Price feed. latest answer and since we

have a way to update it on this mock

aggregator we'll say new price is going

to be an integer of the current price

times the

percentage new price new price current

price times a percentage new price and


this will either be a 15% increase or a

15% decrease and then we can just say

price feed update answer with the new

price now since we added this rule

pricing is going to change and we should

and our fuzzer should find a way to

break our invariant right because if our

collateral gets put in and the price

just keeps dumping to 0 eventually the

protocol will no longer be solvent right

the protocol will have less collateral

than DSC minted which will essentially

break it which is what we want to test

for so let's make sure that updating the

price randomly like this will break it

and it looks like it passed uh that's

not good so we might have to update our

settings so let's scroll down we'll say

stablecoin fuzzer dot settings equals

settings and we have to import

settings scroll up to the top comma

settings import settings will say Max

example

equals 64 and state full step count is

also 64 so I think it's just quitting

out a little too early let's try it now

and hopefully it should break and yes

you will probably have to wait some time

to get this break to happen because like

we said it's trying a ton of random


inputs here and it looked like even that

passed so I'm actually going to update

my Min value to minus to be4 and my max

value to be 0.15 this is where fuzzing

can be kind of tricky you might not wait

long enough you might not set your

parameters enough and we're not really

so worried about the price going up

we're much more worried about the price

going down so if we set it like this it

should go down more than it goes up and

let's go ahead and rerun and then

additionally we should double the

collateral amount because we have a

collateralization ratio in the project

where you need at least twice as much so

we're also going to have the collateral

amount doubled so i' been running this

for some time and in my debugging I

found I needed to set this to Collateral

amount instead of just amount which was

an issue why I was never running into

any issues and additionally I wasn't

thrilled with how long this was taking

yes I know when you run these you have

to be patient however it was taking me

you know maybe 10 minutes to run into an

error and as I'm filming this that was

quite annoying for me so something that


you can do is we can create a rule where

we kind of force play the example that

we want so I'm going to do a rule called

mint and update where we're going to

call Mint DSC and then we're immediately

going to update the price of the asset

so collateral seed user seed amount self

collateral seed user

seed amount so first we're going to do

self. mint and deposit with the

collateral seed user seed and amount

collateral seed user seed and amount and

then we're going to immediately update

the collateral price collateral seed

percentage new price with the collateral

seed and the percentage new price is

going to be

0.0 or

0.3 so we're immediately going to dunk

the price and this should result in US

hitting our Edge case more often so

let's try it now and after what seemed

like ages here I finally was able to get

the error that I was looking for so we

have a little falsifying example here

where we update the collateral

collateral price looks like it's about

40% of the original one then we call

this protocol must have more value than

total Supply and this errors obviously


because

this dropping of the collateral price

dropped the collateral to be underneath

the total Supply and boom we have a fuzz

test failure which is what we were going

for it took a really long time and this

again is why is something that you're

going to do as your last step you'll run

it you'll come back and then you'll fix

the fuzz there are a lot of improvements

being made to pythonic fuzzing and for

fuzzing for smart contracts overall

but anyways now that we have that in

here the final thing that we want to do

is add the liquidation functionality so

that we don't actually get that break

anymore because if we liquidate the

users as soon as someone's Health Factor

Falls to low then our protocol should

always stay solvent and this leads us to

our final Workshop of this section is

for you to write the liquidate function

for this one yes we'll come back and

I'll show you what we did and why we

made the choic that we did

but now I want you to pause the video

pause the course work on this Workshop

you should create a liquidate function

So Def liquidate date and this could be


a rule this could be an invariant

whatever you want to do here but it

should have it such that your fuzz tests

always pass basically anytime the price

is updated you can even do something

where in this update collateral price

you could say like if you know someone's

Health factor is bad

then liquidate and this would kind of

simulate the assumptions of the market

effects the fact that if you liquidate

somebody you're going to get rewarded

for that so ideally this would simulate

that environment so that our true

invariant down here always stays true so

pause the video pause the course and

write your own liquidate Rule and or

invariant all right welcome back so

here's going to be the solution here or

one such solution so what I decided to

do was I decided to make my liquidate

and invariant and basically after every

single rule was run we would flip

through a list of the users check to see

if their health Factor was bad and if

their health factor is bad we would go

ahead and liquidate them and we would

use some clever tooling to liquidate the

users that way after the liquida

invariant would would be run this


invariant would be run and this would

pass because any bad debt or any people

who were underwater or under

collateralized we would have already

liquidated them so our system should

remain solvent now I will say that there

is a bug with the smart contract that we

wrote where if the price drops too

drastically no amount of liquidation

would save the protocol and this is why

originally we set this to you know 7 or8

however so so if we wanted these fuz

tests to be better we would this be like

7.8 or something higher for this update

collateral price however uh we wanted to

run into the bugs so we set this way way

lower to run into the bugs but we should

really set this higher to make it more

realistic and this can be this can be

nice and low here so now we have some

fuss testing in here that looks very

nice we have some unit tests which you

went ahead and you wrote yourself if you

didn't be sure to do that and this is

looking pretty fantastic wow

the final thing is if this is a real

codebase the final thing is we want to

prepare this for audit or competitive

audit or an external Security review we


haven't really spoken too much about

what these are what they look like and

the like so we're going to go ahead

we're going to watch this quick video on

what is an audit and what are they for

and what to expect then we'll come back

and we'll see what we need to do to

level up our code

here a smart contract audit is a

timeboxed Security based code review on

your smart contract system an Auditor's

goal is to find as many vulnerabilities

as possible and educate the protocol on

best security best practices and coding

best practices moving forward Auditors

use a combination of manual review and

automated tools to find these

vulnerabilities now why are these so

important why is it critical that you

get an audit before deploying your

codebase to a live blockchain well for

starters there our entire website's

dedicated to how many hacks happen last

year we saw the most value ever stolen

from Smart contracts with almost four

billion dollars stolen due to the

immutability of the blockchain once a

smart contract is deployed you can't

change it so you better get it right the

blockchain is a permissionless
adversarial environment and your

protocol needs to be prepared for

malicious users but even more so than

that an audit can improve your

developers team's understanding of code

improving their speed and Effectiveness

in implementing features moving forward

and it can teach your team the latest

and greatest Tooling in the space often

just one smart contract audit isn't even

enough and protocols go on a security

Journey that includes many Audits and

many different services like formal

verification competitive Audits and Bug

Bounty programs we'll break these down

in a future video there are a lot of

companies that offer smart contract

auditing services like TR of bits

consensus diligence open Zeppelin Sigma

Prime spearit Dow mix bites watch pug

trust and of course cyphon additionally

there's a lot of independent Auditors

that do great work as well a typical

audit looks like this price and timeline

first a protocol needs to reach out and

they can reach out before or after their

code is actually finished ideally they

reach out sometime before their code is

finished so the otter can have time to


slot them in once they reach out the

protocol and Auditors will discuss how

long the audit will take based off of

scope and code complexity the scope of

the audit is going to be the exact files

and commit hash that's going to be

audited how long the audit usually

depends on how many lines of code slash

complexity you can see a very very rough

approximation of how long an audit takes

on your screen now of course this

depends from firm audit to audit and

tool to Tool so take these with a very

large grain of salt additionally it's

this duration that sets the price and

same thing at the time of recording

Prices range wildly depending on who's

doing the audit how many people are

doing the audit how complex the code is

and more and these initial conversations

are really just to get a ballpark

estimate and Slot you into the auditor

schedule commit hash down payment start

date once you have a commit hash you can

finalize the start date and final price

the commit hash is the unique ID of the

codebase that you're working with so the

a Auditors can know exactly what code

they're going to be looking at some

Auditors will ask for a down payment in


order to schedule you in audit Begins

the Auditors will use every tool in

their Arsenal to find as many

vulnerabilities in your code as possible

we'll give you some tricks in a minute

to make this a successful step initial

report after the time period ends the

Auditors will give you an initial report

that looks something like this with all

their findings listed by severity

usually categorized into highs mediums

lows informational SL noncritical and

gas efficiencies High mediums and low

represent the Varity of impact and

likelihood of each vulnerability

informational gas and non-critical are

findings to improve the efficiency of

her code code structure readability and

best practice improvements that are not

necessarily vulnerabilities but more

ways to improve your code mitigation

Begins the protocol's team will then

have an agreed upon time to fix the

vulnerabilities found in the initial

Auto report sometimes depending on the

severity of the findings this might mean

you have to start from scratch but more

times than not you can just implement

the recommendations the Auditors give


you this is usually much shorter than

the audit itself final report after the

protocol makes these changes the audit

team will do a final audit report

exclusively on the fixes made to address

the issues brought up in the initial

report then hopefully the protocol and

Auditors have a great experience

together and will work together in the

future to keep web 3 secure now there

are a few key things that you can do to

make sure your audit is successful as

possible to get the most out of your

audit you should have clear

documentation a robust test Suite

ideally including fuzz or invariant

tests code should be commented and

readable modern best practices are

followed there should be an established

Communication channel Channel between

developers and Auditors during the audit

and an initial video walkthrough of the

code should be done before the audit

starts the most important part of the

process is going to be during the audit

to get the best results you want to

think of you and your Auditors working

together as a team one of the best ways

to do this is to have a dedicated

Channel where Auditors can ask questions


to the developers the developers will

always and forever have more context

over the codebase than the Auditors ever

will because they have spent so much

more time working on the codebase and

then more documentation context and

information that you can give to the

Auditors the better this way it can be

easy for anybody to walk through the

code and understand what it's supposed

to do in fact 80% of all bugs are

actually business logic implementation

bugs this means that these are bugs that

have nothing to do with some weird

coding error and are just somebody not

knowing what the protocol should be

doing so it's vitally important that the

Auditors understand what the code should

be doing having a modern test suite and

tooling can also make Auditors spend it

less time fidgeting with your tooling

and more time finding issues post audit

we highly encourage you to take the

recommendations your Auditors give you

seriously additionally after an audit if

you make a change to your code base that

new code is now un audited code it

doesn't matter how small the changes

we've seen a ton of protocols saying oh


I'll just slip in one line of code and

sure enough that's the line of code that

gets exploited and often depending on

the seriousness of your protocol and how

many users you want to use it one audit

might not even be enough working with

multiple Auditors and getting more eyes

on your code will give you a better

chance of finding more vulnerabilities

what an audit isn't now here's the thing

an audit doesn't mean that your code is

bug-free an audit is a security Journey

between the protocol and the auditor to

find as many bugs as possible and teach

the protocol different methodologies to

stay more secure in the future security

is a continuous process that is always

evolving no matter how much experience

someone has people at all levels have

missed vulnerabilities on the

unfortunate day that that happens be

sure that you and your auditor can jump

on a call quickly to try to remedy the

situation and maybe consider getting

insurance for your protocol as well so

now with that being said now you have a

good idea of what a smart contract audit

entails and what to expect end to end a

smart contract audit is a security

Journey end to endend leveling up your


protocol so that you can have all the

best practices and security know how to

deploy your code to a live blockchain

forever and of course if you're looking

for an audit be sure to reach out to the

cyphon team Link in the description and

as always stay safe out there and we'll

see you next time so just by watching

that video there was a number of things

we would need to do to clean up our

codebase for audit so first off in our

read me we would need to clean up our

readme we would need to do set up like a

how to run piece of documentation we

then we need to go through our code and

we probably would need to add some more

dock strings because right now a lot of

this is kind of like woozy right like

we're not really sure what these

functions are doing so we would need to

update doc strings additionally we would

need to write some docs in our read me

as to like what this protocol even does

right often times auditing and doing

Security on our protocol is going to be

just making sure that the code matches

what it's supposed to do but if security

researchers don't know what this

codebase is supposed to do then like


there's nothing for them to check

against so we want to write some docs

saying hey here's what the codebase is

supposed to do here's how the stable

coin Works here's how the

collateralization r ratios work etc then

we'd want to create a scope for this as

well a scope of the project

so we would say hey for this audit we

would want you to audit these two

contracts decentralized stab coin. VI

and DSC engine we could optionally also

add our library files from snik mate but

most of the time those are going to be

ignored we go over security way way more

in depth in the smart contract security

section of cyphon updraft and we go into

Security even more in assembly inform

formal verification these are both

written with solidity in mind however at

this point in your career pretty much

all of the knowledge will transfer over

pretty much all the examples in The

Foundry and solidity curriculum are the

exact same examples you just did in

Viper and python so to get deeper into

security you'd want to head over to here

but one other thing I always point out

is this thing called the wct test these

are a list of 12 questions you want to


ask yourself to make sure you're ready

to deploy your smart contracts now

there's some more advanced things in

here like do you have a team member with

security defined in their role do you

require Hardware security keys for

production systems which are things we

haven't gone over but these are some of

the things that you really need to

consider when you're actually going to

deploy your contract security is

absolutely crucial when it comes to

these smart contracts because if you

have a bug there goes all your money

there goes all of your hard work down

the tube so this is a good thing to

check out before deploying as well and

if you're a little bit confused still on

what even is an audit don't worry once

you get to a point where you're ready to

deploy a smart contract that's when

you're want going to want to start

thinking about one or if you decide you

want to go down the security route

that's when you can start thinking about

them too and in my opinion some of the

best developers on Earth are also

security focused so I highly recommend

you checking out code Hawks where there


are competitive audits that you can

participate in to actually get better at

security yourself so couple of things we

wanted to do to get this a little better

we would add some docs how to write this

update our doc string docs about what

this codebase even does include the

scope of what our audit looks like and

there's a couple other uh things as well

a highly recommend people who want to

become either a better developers or B

get into security definitely go check

out code Hawks sign up try to compete in

some competitive audits because even

just doing one or two your skills and

your understanding of how audits work

and what they look like will Skyrocket

just by doing one or two additionally

code Hawks has this thing called first

flights which are incredibly easy

competitive audits so it's easy to get

in start doing some code reviews and the

like all right and with that being said

you should be incredibly proud of how

far you've gotten because you just wrote

stable coin and not just like a a lame

old like oh yeah this is centralized

stable coin I'm going to me you wrote an

autonomous

decentralized algorithmically
algorithmically controlled stable coin

where you have a minting and a burning

facility governed by how much collateral

people put into your protocol this is

absolutely wild could you even imagine

when you started the beginning of this

course that this is something you were

going to have the power to do now you

might not understand everything in here

in its entirety and that's okay this is

a journey you're part of the journey

here you learning you're growing every

step you're getting better and better

and better so let's do it quick recap

here before we send you on your way to

your next one or to your break you

should probably take a break so we first

learned a lot about stable coins we

learned a lot about different types of

stable coins we watched that very long

video of me talking about collateral

exogenous endogenous minting

capabilities value collateral type Etc

now these are all incredibly important

for you as a developer and for you as

somebody who may engage in defi or

decentralized Finance right when you

look at these different cryptos when you

look at these different stable coins you


can now go okay is this a collateralized

stable coin yes or no if yes is it

exogenously collateralized or

endogenously collateralized if it's

endogenously collateralized yikes I

should be a little afraid cuz those ones

have a history of going to zero What's

the minting capability is it centralized

is it some type of entity like usdc

who's actually doing the minting

themselves or is it decentralized where

it's out algorithmic where some type of

contract like what we built here governs

what is minted and what is not what's

the value yes you can have a stable coin

that isn't pegged to a fiat currency you

can have a stable coin that's pegged to

maybe like a basket of assets or it has

floating buying power there's different

types of stable coins and then obviously

what is your collateral type we learned

a lot more about deploying production

code and working with production code we

learned a lot about defi about deploying

collateral redeeming collateral minting

burning liquidating and if again if this

didn't make sense all the way that's

okay cuz this is tough this defi stuff

takes some time to sink in we built a

lot of external functions and a ton of


internal functions to deal with the math

and the minting and the burning and the

price feeds and all that good stuff we

then wrote some amazing unit tests I

only have two in here um as of recording

however if you go to the GitHub repo we

have a lot more and if you didn't write

the tests shame on you cuz that is one

of the biggest learning pieces from this

entire section is writing those tests

yourself We additionally wrote some

insane fuzz tests here and these fuzz

tests allowed us to have even higher

assurance that the code we wrote is very

good we worked with mocks we worked with

interfaces we worked with scripts and we

even did a little bit of thinking about

audit prep now if we wanted to go one

step further we could do a little

formatting here with a UV run rough

check-- select i-- fix or a UV run Ruff

check.

dfix and then a UV run mamushi oh I got

to do UV add mamushi like this and then

we'll UV run mamushi SRC to reformat all

of our Viper files and looks like python

we go to our scripts our python has been

now reformatted with the Imports looking

much better and additionally our


decentralized stable coin has been

reformatted with everything looking a

little bit nicer as well this is another

phenomenal project that you should

absolutely put in your GitHub and

absolutely scream at the top of your

lungs hey I know how to write a

decentralized stable coin because this

is incredibly powerful here so since

you've made it this far you should be

incredibly proud of yourself we have a

few sections left to go here but this is

the giant project that you should be so

proud of yourself for so now's a great

time to take a break go for a walk go to

the gym get some ice cream because we're

almost done so take that break and I'll

see you soon

all right welcome back to the next

section as always if you scroll down in

the GitHub repo associated with this

course we go to the moccasin signatures

you can see the final code base

completed here now what we're going to

be doing here is we're going to be

building a airdrop smart contract so if

we look in here we have this function

called claim which allows people to

claim their air so essentially we want

to give out tokens to a ton of ton of


people however we don't want to keep a

giant mapping or a giant list of every

single address that's allowed to claim

why well because that would be crazy gas

expensive to do all of those SL loads to

add all of those to storage so I have my

code base here in my IDE and I can run

Rox test- s do a little zoom in here and

we'll see our test pass what we're doing

here is we're going to be making two

scripts number one is make Merkel and

we're actually going to be copy pasting

a lot of this I'm not going to make you

write this whole script out but what

this is going to do is it's going to

make something called a Merkel root and

that's how we're going to do this

airdrop thing we're going to make a

Merkel rout and we're going to deploy a

smart contract with this root here this

root is going to allow us to store a

single Hash a single bytes 32

essentially onto our smart contract and

that single route is going to enable us

and to essentially keep track of every

single user who we've aird dropped

tokens to and this could be thousands of

users but we only have to store and

storage one single slot which is kind of


crazy right if we look at our make

Merkel we scroll down in here we've got

a whole bunch of constants and the only

thing we have in storage is this has

claimed mapping which is just going to

be a true false mapping that's it

there's no list of people who can claim

there's no mapping of people who can

claim all we have is this immutable

meral rout and it's with this one single

value that we can keep track of

thousands of people who are eligible for

this airdrop now a couple years ago

doing aird drops were a very popular way

of getting people interested in your

project you would launch a token and

then you would airdrop many people with

the token as of recent this has become

worse for lack of a better word people

do this less and less a lot of people

started gamifying the system figuring

out how to get more of the airdrop and

it kind of defeated the purpose of doing

these however these still show us some

really cool things about signatures

about hashing and the like and some of

the amazingly powerful things we can do

with hashing additionally we will

finally understand what this

e712 thing is we've been doing this for


pretty much all of our tokens right

we've had this EIP 712 version thing

that we've had to go over so many times

and we haven't explained it in this

section we will finally understand that

you'll also learn what a Merkel tree is

what a Merkel root is and the likes and

I'll tell you right now Claude and most

AIS are very very knowledgeable about

how Merkel trees work how hashing works

so feel free to use them as resources as

we cut along here so let's go ahead

let's get started developing our own

Merkel tree based air dropper smart

contract in Viper all right so we're in

our

vs code here in our MOX CU folder I'm

going to create a new folder because

we've done this so many times now we can

go kind of quickly here MOX signatures

Cypher updraft code MOX signatures

cyphon updraft or file open folder this

folder here let's open this up boom like

so then we're going to do a little MOX

init --vs code-- py project like so

great we're going to come in here we're

going to delete a lot of this stuff

delete delete delete delete goodbye

delete great and now we have a blank


project here let's jump into the read me

and write about what we're going to do

so here's what we want to do this is it

we want to airdrop tokens to X number of

people and we want to utilize the pull

over push meaning the user has to come

get it rather than us giving it to the

user they have to come get these tokens

by calling a claim function and the

important thing is we don't want to have

to store a thousand people in an array

or a mapping on chain that's going to be

very gas intensive and we don't want to

do that so this is what we're looking to

do that's it let's get started coding so

let's first make a little snck token. VI

this will be the token that we're going

to airdrop to everybody and I'm going to

cheat a little bit we've done ec20

many times so I'm just going to grab it

from the get a repo associated with this

boom I'm going to paste it in feel free

to do it however you like here but very

simple snck token it's got an initial

Supply here everything else seems good

and filled out we're getting this red

squiggly underline because we need to

run MOX install

snackmate like this and then and it

looks like we're good to go here awesome


and that looks good let's just make sure

with a mock

compile great that looks perfect okay

next now let's go ahead and make a new

file called Merkel airdrop Dov and I

will explain what a Merkel tree is what

a Merkel root is and all that good stuff

so let's get started with a pragma

version

0.4.0 we'll do a little at title Merle

airdrop we'll do at license MIT and if

you want to put an author and a notice

in there as well great go for it now

we're only going to have one main

function and we'll probably have some

view functions as well in here but our

main function is going to be at external

def claim and that's it right and what's

this and what is this going to do well

allows users to claim the air dropped

aird dropped tokens so in our deploy

script when we deploy the snck tokens

we're going to send them to the smirl

airdrop so the smirl airdrop will have

all the tokens to

send so like I've been saying what we

could do is I could create a address

array uh public or excuse me say uh our

keole which is a din array


of address with maybe a maximum of a

thousand people I could fill this up and

then I could just when we call claim I

could just say something like okay if

you know message. sender in our people

you know send tokens right but now we

have to Loop through this whole array we

have to add this whole array of people

this it's just very gas intensive and we

don't want to do that we're software

Engineers we're more clever than that so

what we can do instead is use something

called a Merkel proof and a Merkel root

and this will allow us to I kid you not

to have a single Merkel Merkel rout as a

public bites 32 we can even make this

mutable and this Merkel root will have

everything we need in order for people

to claim so in order for us to

understand how this works we first need

to understand a little bit more about

Merkel roots and Merkel proofs so let's

go ahead and let's watch this video from

Kira to help explain that so Kira is

going to go over a Merkel proof and

Merkel root example and a merel tree

example but it's going to be in solidity

what's nice about this is that even

though it's solidity Viper the Viper

code will be actually incredibly similar


to the solidity

code have you ever heard the terms merel

tree Merle proof root hash what the heck

do all these words mean Merkel trees are

a data structure in computer science

Merkel trees are used to encrypt

blockchain data more securely and

efficiently it was invented by Ralph

Merkel in 1979 he also happens to be one

of the inventors of public key

cryptography in order to understand what

a Merkel tree actually is it's easier to

just see a visual representation this is

a Merkel tree here you can see at the

base of the tree there are four distinct

pieces of data these are known as the

leaves or Leaf nodes of the tree and

each one represents the hash of some

data and at the top or the root of the

Merkel tree is the root hash and it's

created by hashing all of the individual

nodes together as Leaf node hashes so

adjacent nodes are hashed together and

then the output hashes are also then

hashed together in a tree likee

structure a miracle proof is a way for

someone to prove that some data is in

one of those leaves to someone who only

knows the root hash for example example


if we had some data which we could hash

to produce hash one we could prove that

that data was in the Merkel

tree so for example let's say we had a

club where there were different tiers or

levels to the club maybe we had like a

bronze silver gold Platinum situation or

something like that and for each of

those levels you have a password to

prove you're part of the club you could

create a Merkel tree and then a Merkel

proof for someone to be able to prove

that they are in a club so in in order

to prove that the data in hash one was

present in the Merkel tree or if someone

wanted to prove that they were part of a

club all we need to do is provide hash 2

and hash 34 so the proof would simply be

the array of these two hashes since we

can compute hash one we can then hash

that with hash two to produce hash one

two and given that hash 34 is in the

proof we can then hash that together

with hash1 two to produce the root hash

which we can then compare with the

expected root hash and this provides the

root verification note here that for a

successful Merkel proof you need to

provide all sibling nodes at every tree

level which since we were able to


calculate these values we have done

since secure hashing functions like kak

256 are used to create the hashes it's

practically impossible to create a hash

Collision so the likelihood of two

different messages two different pieces

of data two different inputs creating

the same hash is practically impossible

and won't happen in practice therefore

if you receive a matching root has in

the Merkel proof you know the item

really must have been in the Merkel tree

and part of the original root has

calculation Merkel trees are used in

lots of different circumstances most

notably proving smart contract state for

example they are used in rollups to

prove State changes and verify the order

of transactions they are also used in

efficient airdropping to prove that a

potentially claiming a dress is part of

an allow list of addresses which are

able to claim using Merkel trees we can

enable able some addresses to claim and

others not by including the addresses

that we want to be able to claim as Leaf

nodes as part of a Merkel tree now you

might be thinking hang on a second Kira

why would I need Merkel proofs for my


airdrop can't I just use an array of

addresses and so if we look at this

example where we are in fact using an

array of addresses you can see that

every time someone calls airdrop they

would have to Loop through all of these

allowed addresses now imagine if this

allowed addresses array is extremely

long maybe thousands tens of thousands

hundreds of thousands of people are in

this allowed address array at some point

the gas to cool this airdrop function is

going to exceed the gas limit and it's

going to become extremely expensive to

cool and Loops through unrestricted

arrays can lead to a denial of service

in which someone is unable to claim the

airdrop therefore we need to use Merkel

proofs instead the Merkel proof. smart

contract from open Zeppelin is an easy

way to implement Merkel proofs into your

smart contract

let's take a look quickly at how they

Implement that the verify function in

this smart contract takes the proof the

Merkel route and the leaf that we want

to verify as inputs typically the route

is stored in the smart contract

somewhere and the proof will be created

offchain this then calls process proof


which then iterates through each element

in the proof array provided we start by

taking each Leaf node and then the

computed hash is updated at each step by

hashing it with the next element in the

proof note here that hashing to hash

hases together it will always take the

smaller of the two hashes first and open

Zeppelin uses kak 256 for the hashing

algorithm here you can see that they are

in fact using assembly but this is

essentially the same as ABI encoding the

two values together and then hashing

that output process proof then Returns

the computed hash and this is a

calculated route which is then compared

to the expected route to determine

whether the provided Leaf was in fact

present in the Merkel tree and that is a

very brief summary of Merkel trees and

Merkel proof proof Merkel trees are just

a cryptographic data structure using

hashes and Merkel proofs are just a way

of proving that some data is in fact in

the tree and they are often used in

airdrops and also verifying State

changes in smart contracts and in

rollups and that was a very quick video

on Merkel trees and Merkel


proofs okay so now that we've learned a

little bit more about what Merkel roots

are let's keep writing this contract

some of this some of this won't make

sense until you we kind of see the whole

thing put together so if it's a little

bit hazy right now just roll with me so

what we did learned from this Merkel

proofs part is that I can do an at

deploy def Dunder AIT we'll saycore

Merkel rout will be a bytes 32 and what

I can do is I can set this Merkel rout

equals underscore mer root and somehow

just by us adding this single bytes 32

we will somehow kind of have a full list

of people who can claim the token uh

okay that that seems insane but let's

keep going for now just assume it is the

case next we're also going to need the

airdrop token which will be an address

and then we will also say we'll call

this uh immutables

MBL we'll say token or airdrop token

public immutable

mutable address like this airdrop token

equals uncore airdrop token like this so

how does this claim thing work what does

what does this actually look like here

well what the user is going to have to

pass and again if this doesn't make


total sense right away that's okay is

they're going to have to pass in the

account which is going to be an address

who is going to be doing the claiming

how much they're going to be claiming

for

the Merkel proof which is going to be a

d array of bytes 32 bytes 32 and some

proof max length which we'll scroll up

to the top we'll do

constants proof max length we'll say is

going to be a constant constant uint 8

equals let's just do the max value of a

u 8 so the biggest U 8 I think that's

going to be like 20

255 we can even ask Claude or something

or what is the max size of a un 8 255

okay there you go perfect so Merkel

proof will be a by 32 Max size of

255 and then finally something that is

Vaguely Familiar the V 8 the r the bytes

32 and the S which is a byes 32 and you

may recognize these as the values of a

signature so in order for somebody to

call claim here they have to pass their

address the amount some weird Merkel

proof thing that we're not really sure

what this is quite yet and then a

signature for this as well so before we


keep going here this is kind of in my

mind like a chicken or the egg problem

of like learning this do you learn the

claim or do you learn the script first

it's kind of both at the same time but

here's what I want you to do I want you

to go to the repo signatures cyphon

updraft go to script go to make mel. py

and I want you to just copy everything

just copy this whole thing yes I know

it's a lot of code and this is why I'm

not having you do it but we're going to

do make

m.p and paste this in here I'm not going

to have you write this all out because

there's a lot of code here there's a lot

to explain and if you really want to get

in your bones the process of making this

you can abs try to do so yourself but

I'm going to walk you through this and

tell you what's going on here so that we

can understand how we're going to use

this Merkel route to claim the tokens on

this contract here so we have this make

Merkel dopy and what this contract is

going to do is it's going to make our

Merkel tree AKA it's going to make our

Merkel rout and Kira just briefly went

over this but essentially this top

Merkel rout is going to be created by


hashing everything together so we're

going to so we're going to Hash the leaf

nodes or the you know the bottom of the

tree together and then we're going to

Hash the result of those hashes together

and then we're going to finally end up

with this Merkel rot so you can almost

think of it as like just hashing

yourself many times until you only have

one hash left so for example what we're

going to do is we're going to have these

be our different leaves right so this

first value here is an address and a

default amount and you can kind of think

of this zero this you know this address

and this default amount as this first

Leaf node that we're going to Hash so

you can almost think of it as like we're

going to Hash this whole thing and

that's going to be this bottom one then

we're going to Hash this whole thing

that's going to be this hash two then

we're going to Hash this whole thing and

it's going to be this hash three then

we're going to Hash this whole thing and

it's going to be hash four and what you

can see here obviously is it's just a

list of addresses and amounts so this is

the default input default amount is


going to be this number here which is

like I think it's going to be 25 tokens

so it's like 25 E18 I guess that it's

probably a better way to represent it

2518 as an INT and we're basically

saying this address can have 25 tokens

this address can have another 25 tokens

this address can have 25 tokens blah

blah blah blah etc etc and we can make

this default input we can make this

dictionary hundreds of inputs long and

our contract would still work perfect ly

but we just have four in here just to

kind of demonstrate what's going to

happen so this is our our list right and

we could put this on chain into our

contract but again that's going to be a

huge waste of gas so what do we do

instead well if we run this do MOX run

make Merkel we're going to get get an

output that looks like Merkel tree data

written to Merkel output. Json and we're

given a Merkel rout so what this

actually does is if we run this it's

going to do MOX in main it's going to

call CLI run and it's going to run this

generate Merkel tree so this is kind of

where the secret sauce is here and

essentially what we do is we Loop

through all of the entries in our input


data right which is this again this

dictionary at the top here we get the

address we get the amount and we

basically

create this Leaf node by combining the

two so we have this function called

generate Leaf if we click on this we're

basically going to generate a leaf node

by encoding and hashing the address and

the amount so we we convert the address

to an integer yes I know that's very

bizarre we convert that to a bytes and

then we add it to this array we do the

same thing with the amount and then we

encode it so This Is Us basically taking

the RW address and amount data and

coding it into into hashes here so we

generate these Leaf hashes if you will

and we append it to this array called

leaves like so and then what we do is we

call this generate Merkel root with all

the leaves so the first step we

essentially did was we Loop through all

these inputs we hash each one of these

inputs and that's it so right we kind of

get the first step of this Merkle tree

here we have hased each one of our Leaf

nodes we did a very specific kind of

hashing algorithm here like this is


essentially the way we hash them so that

it's specific and it will work no matter

what we input with once we do that we

obviously need to take all those leaves

and then you know hash the pairs

together to get the next hash and then

we need to keep going until we have a

single Merkel root so we have this

function get Merkle root where

essentially that's all it does here so

we have this this code in here which is

literally going to do that so it's this

is kind of this giant while loop where

it's just going to go through every

single pair and hash them together with

this hash pair function which just kind

of looks like this hash 2 bytes 32

values in order boom that's how it does

it and that's doing this hashing over

and over again will get us end up with

this Merkel root at the top then once we

have the root and we have the leaves the

final thing we need to have is we need

to create a proof so we have this get

proof function which generates Merkel

proof for the leaf at the given index

and so we're going to Loop through all

the leaves and also create this proof

for each one of

them now how does the proof thing work


this is probably the the trickiest thing

but once you kind of get it it becomes

the easiest if I Am Hash one if I am let

me let's scroll up to the top if I am

this address with this amount right and

I want to claim my tokens I need to pass

in this Merkel proof I need to pass in

some hashing proof that says hey you

know I am part of this the Merkel rout

right because all the contract is going

to have again is going to be this Merkel

rout here so I need to prove that I'm

this hash and I'm part of this whole

tree the mirle proof is essentially

combination

of as few as possible other hashes to

recreate the tree as few as possible

other hashes to recreate the tree and

what does that mean well if I'm hash one

right if I am this address with this

amount what is the fewest number of

hashes that I can input to recreate the

Merkel root remember the Merkel root is

you hash these together you hash these

together you hash that the hashes of

those together and that's how you get

the mer roof so what is the least number

of hashes that I can pass in that's

right I can pass in hash number two and


then this hash up here and we can

recreate the entire Merkel rout just by

having these hashes right because if I

have hash two I can now hash them

together to get this green one and if I

have this one over here I hash those two

together to get the Merk rot so if we're

looking to get proofs if I'm hash one I

would pass in hash two and then you know

let's let's say this is Hash 5 # 6 hash2

and hash 6 # 6 right that's how I would

get it what if I'm hash two what is the

least number of hashes I can pass in to

recreate the root well it's going to be

hash one and this hash over here right

because if we combine these together we

get hash five boom so if I'm if I'm hash

two then I just pass into hash one and

hash 6 okay what about hash three what

if I'm this hash well if I have hash

four I can combine together get this

green hash over here and then if I have

this one combine those together I get

the root so if I'm hash three I would

pass in hash four four and then hash

five this hash up here hash five same

thing if I'm hash 4 I would want to pass

in hash three

and then hash five so essentially all

this Merkel proof is this is actually


why I don't love the name it's just okay

if I'm hash one what is the fewest

number of hashes I need to pass in to

recreate this Merkel rout and that's it

so at the end of this kind of get Merkel

tree function we get the proof of each

one of those and essentially that's what

it does here is it looks for siblings

and it adds them together and that's

pretty much it to get that proof for us

and then we are given this output which

is essentially just like a list of the

inputs the proofs the root and the leaf

if we run this from the CLI this will

say Merkel tree data written to merkl

output. Json we if we can see if we go

to Merkel output. Json we can see a list

of all kind of the inputs and outputs so

for example once again if this is us

right and this is in here

if we are this address and we want this

much the proof would just be these two

it' be these two hashes and that would

be the Merkel proof why well because

this well because this this hash is

going to be the exact hash as one of the

other Leaf nodes so let's scroll down

aha it's the hash of this Leaf node down

here we know that if we combine these


together we'll get a new hash and if we

combine that new hash with this hash

we'll get the root so hopefully that

makes sense like I said AIS are great at

explaining this so if you want to pause

ask an AI to make sure that you're

following along please feel free to do

so I think Merkel roots and Merkel trees

seem very complex and very confusing

when you first approach them but once

you play with them a little bit they

actually become relatively easy but it's

just getting over that first knowledge

hump that's kind of confusing here so

and then each one of these all the roots

in all these entries are going to be the

same because of course they are they all

have the exact same root because again

this is what the tree looks like they're

all going to have the same root here

so with all that being said now we know

a little bit more about what's actually

going to go on here so this Merkel proof

we know is just essentially going to be

a list of other hashes from the tree

that's what this proof is we know what

the account is that's going to be our

account count we know what the amount is

that's going to be what our amount is

and the vrf and the v r and s is going


to be some signature thing we'll get to

that shortly now it might make sense on

here to add like an is eligible function

or something so people could check if

they're eligible for the airdrop but

we're just going to assume that giving

the root is good enough because everyone

is going to have the same account and

amount and we can pass out on like a

spreadsheet off the chain kind of the

different hashes so that people can

claim you know we don't have to actually

store those those hashes on chain people

can figure them out people can get them

from some offchain Source the mirle

proof okay so we'll get to this vrns in

a second let's write the functionality

for at least this part of here so first

off we should check to see if these

users have claimed so let's create a

little storage has claimed and this will

be a hash map of be a public

hashmap of address to Boolean and we

should first do a little assert has

claimed of account equals equals false

account has already claimed and we'll

say uh Merkel airdrop like this or

actually better yet assert has claimed

account excuse me self. has claimed


assert not self that has claim this is

essentially the same as doing assert

that is false then we're going to have

to do something with the signatures

we'll get to that in a little bit but

what we can do now is we can say okay

let's get the Leaf node the byes 32 so

we first want to get okay what is the

leaf node what is the leaf hash of these

two so we are going to actually do a kak

or kak

256 of ABI and code uh and this is where

it's a little confusing API and code KCK

256 of ABI and code account and amount

um there's a reason we have to do the

double encode here as of recording that

reason is failing me if someone wants to

make a PR to the GitHub repo associated

with this for the reason why we should

do this uh please do so and so now what

we want to do is we want to assert that

this Leaf is indeed in the in the Merkel

root by combining it with the mer proof

now we could write a script to do that

ourselves however guess what our friends

at snackmate have already created this

functionality for us so this makes our

life actually crazy easy so right at the

top we could say from snackmate do

utils import Merkel


proof

verification verification like this and

down here we can now do seert

Merkel proof verification

doore verify Merkel proof Merle root and

the leaf and we'll say comma invalid

proof so we can go check this out we can

go to lib pii snck mate utils and this

is in the Merkel Merkel proof

verification defcor verify we can see

this takes a d array a root and a leaf

it's going to call this process proof

down here it's going to do some hashing

to get it's going to say for each proof

in the proof it's going to compute the

hash for each one of those and once it's

processed the proof with the leaf it'll

just check to say hey is all the hashes

combined equal to the root if yes return

true if no return false right so all

this verification thing is doing is it's

just recreating this Merkel route it's

basically just saying okay with your

hash with your leaf and then all the

hashes you gave me can I recreate the

route if yes congrats you're in you can

have the tokens if no you're out you

can't have the tokens once we do this

assert we would want to do self. has


claimed of account equals true we

probably would do a want to do log

claimed count amount so let's make a

little Event Event claim named like this

count indexed amount will also be

indexed like so because we're updating

storage and then we would finally want

to send the user the airdrop tokens so

we' say success bull equals x call

airdrop token token transfer so we would

want to make this actually an I

erc20 so we could say from ethereum

erc's import

ic20 like this and we could say airdrop

token is going to be a public immutable

erc20 and that means we just got to wrap

it in our anit function but now we

should be able to directly call The

Transfer function we'll transfer it to

account for the amount and then we'll

just do assert

success otherwise transfer failed boom

lovely so this is looking pretty good

here now you might be asking hey Patrick

this is looking pretty good except we

have this weird vrns thing why don't we

just do like you know like this and

instead of doing account we just do like

message. sender now we could 100% do


that but sometimes we want to let

somebody else claim our tokens or often

times maybe we want to have a smart

contract where you you can send

transactions by signature instead of

directly checking message. sender so we

have leveled up this claim function so

that somebody can input the vrns

somebody could sign the claim function

here somebody else could call it but

whoever's money it is they would still

get it so that's why we have this vrns

thing here but yes as a design choice we

could 100% remove these instead of

account we could just say message.

sender right that would work perfectly

fine but we don't want perfectly fine we

want some really cool contracts here so

we're going to make it so that anybody

can call this function so long as this

account has signed something that gives

them the vrns to actually send this

claim now what's nice is you know the

account will still get it but they have

to have the vrns they have to have the

signature in order to call this claim

function and this is a really common

methodology for a lot of functionality

for example voting on Dows there's often


this functionality called vote by

signature where somebody will vote maybe

they don't have the gas fees they will

give their signed vote to somebody else

who will then send the transaction for

them and vote for them basically the

other person will then pay the gas fees

we see things like when we're when you

work with multi signature wallets which

is some pretty advanced stuff you should

definitely check out we have some

multisig curriculum on cyphon updraft

where users will need to where multiple

people will need to sign something in

order to send a transaction but again

you don't have to waste the gas of the

multiple people signing you can all just

kind of sign offchain give one person

the collection of signatures and then

they can send it this saves a lot of gas

this is a lot more efficient for the

chain this doesn't clog up the chain

with unnecessary transactions Etc

there's a lot of reasons to have

signature-based proofs on your smart

contracts so let's go ahead let's flip

over to Kira who's going to teach us a

little bit more about signature

standards what are the different types

of signatures how do they work how there


different eips with different signatures

now she's going to be showing you

solidity examples but we're going to go

ahead we're going to rewrite a lot of it

into Viper ourselves and a lot of the

solidity code is pretty much dead

similar to what we're going to be

writing in Viper so let's go ahead let's

learn about signatures let's learn about

signature standards and let's finally

learn what this weird let's go over here

where is it what this weird EIP 712

version thing is that we keep adding to

our tokens so here's

Kira in this video we are going to go

through everything that you need to know

about signing and verifying signatures

by learning about an understanding

ethereum signature standards we will be

going through EIP 91 EIP 712 and how you

can verify your signatures in your smart

contract let's jump into it in order to

understand signature creation signature

verification and preventing replay

attacks EIP 1 191 and 712 must be

understood first let's quickly go

through why these ethereum Improvement

proposals were

introduced when signing transactions we


needed an easier way to read and

understand transaction Data before these

standards were created the following

message was displayed in metamask when

signing a transaction pretty ugly right

difficult to understand whether what I'm

signing is correct not what you want to

see these standards meant that the

transaction data could be displayed in a

nice readable way additionally EIP 712

is key to preventing replay attacks

spoiler the data to prevent replay

attacks is encoded inside the structured

data so let's go through these standards

now step by

step let's first start with simple

signature verification and implement it

into a smart contract so if we create a

function get simple signer which takes a

message to sign and this can be any data

at all preferably the string c is

awesome but it's up to you notice here

the VR and S arguments these are

components of the signature that we're

providing this function get simple

signer hashes the message and then

retrieves the signer using the

pre-compile EC recover and then Returns

the result as I said EC recover is a

pre-compile so it's a function that's


built into the ethereum protocol and

retrieves the signer from any message

using the VR and s components of the

signature we then create a function

verify signer simple which then compares

the retrieved signer to the expected

signer and then it reverts if they're

not the same this is how signatures work

at a fundamental level take some hash

message plus the signature of the

message retrieve the signer and check

that the address was as expected there

was an issue with this though there

needed to be a way to send transactions

using pre-made signatures AKA sponsored

transactions there will be a future

video on account abstraction so remember

this as this will be important this was

already possible outside of smart

contracts however there needed to be a

way to build this into functions in

smart contract for example Bob signs a

message AKA a transaction and gives that

signature to Alice Alice then uses that

signature to send the transaction

meaning that Alice pays for Bob's gas

fees and so EIP 191 was

introduced EIP 191 is the sign data

standard and it proposed the following


format for signed data first off ox19

this is the prefix and this just

signifies that the data is a signature

the decimal value of ox19 is 25 and this

was chosen because it wasn't used in any

other context and due to how ethereum

transactions are encoded it ensures that

the data associated with the sign

message cannot be a valid ethereum

transaction next we have the one bite

version this is the version that the

sign data is using and this allows

different versions to have different

signed data structures the allowed

values are 0x0 which is data with an

intended validator the person or smart

contract who is going to validate the

signature is provided here 0x01 which is

structured data this is the one that's

most commonly used in production apps

and is associated with EIP 712 which

we'll discuss shortly and finally 0 x45

personal sign messages you then have the

version specific data this is data

associated with that version and it will

be specified for instance for 0x01 you

have to provide the validator address

the next section is the data to sign and

this is purely the message we intend to

sign such as a string K is awesome let's


now modify our code for EIP 191 the

following get signer 191 function

demonstrates how to set up an EIP 1 191

signature so you can see here we have

the bytes one prefix which is that ox19

you then have the bytes one EIP 191

version and we're using version zero

then we have the version specific data

so the validator address which we're

saying is this smart contract and then

we have the application specific data so

some message and we can see it follows

that format that we said just a second

ago we then ABI en code this data we

hash it together to produce a hashed

message we then use the EC recover

pre-compile with the hashed message and

the signature to recover the signer as

you can see here retrieving the signer

is much more Vose now as before we can

then compare this calculated signer with

the expected signer however what if this

data to sign the message is a lot more

complicated we still don't really have a

nice way to display this information for

instance in metamask so we needed a way

to format this data that could be more

easily understood so we needed to

standardize this which was done in EIP


712 EIP 712 structured this data to sign

and also the version specific data this

made signatures more easy to read and

that we could display them inside

wallets and also that we could prevent

replay attacks so now the signature has

the following structure we again have

the prefix from before and the version

we now have this domain separator and

this is the version specific data Note

that we're working with here with 0x01

and this is the version that's

associated with EIP 712 the domain

separator is the hash of the struct

defining the domain of the message being

signed and in the case of EIP 712 the

EIP 712 domain looks like this so you

have a struct that has the name the

version the chain ID and the verifying

contract this means that smart contracts

can know whether the signature was

created specifically for that smart

contract because the smart contract

itself will be the verifying contract

and it will be encoded in the data so we

can rewrite the data as

ox19

0x01 the hash struct of the EIP 712

domain and then the hash struct of the

message now we need to Define what hash


struct is the hash struct is the hash of

the type hash plus the hash of the

struct itself so the data the type hash

is a hash of what the actual struct

looks like so what are the types

involved here what is the name of struct

and what are all the types inside that

struct and then we hash that together to

create the type hash we then create a

domain separator struct by providing all

of the data necessary and then we hash

to together the typ p with all those

individual pieces of data by first ABI

encoding them together to create some

bytes and then hashing that data but the

hash struct is basically what does the

data look like and what actually is the

data hashed together now we have the

hash struct of the message and this

follows very similarly so what is the

type of the message and then what is the

message itself so we have a struct

message which has the member number so

then the message type hash will then

just be the hash of the type message un

256 the hash struct of the message then

becomes the ABI encoded type hash

alongside the actual message struct data

encoded together and then hashed and


this is the hash struct of the message

so we can think of this EIP 712 data as

just ox19 ox1 who verifies the signature

and what the verifier looks like a hash

of the sign structured message and what

the signature looks like putting this

together we then create a get signer EIP

712 function which first takes the

prefix the EIP 712 version which is

ox1 the hash struct of the domain

separator which we created by hashing

together the type hash and the domain

separator struct data we then encode

together the prefix the version hash

struct of the domain separator and the

hash struct of the message

and this combined together is known as

the digest the definition of a digest is

just any data resulting after a hash and

you often see it referred to when

talking about signatures after you have

hashed the message and combined it with

all of the other data associated with

EIP 712 so don't be confused if you see

digest in another context we then call

EC recover with this digest and the

signature to retrieve the actual signer

we can then compare that to the expected

signer as before in this verify sign 712

function this may sound extremely


confusing but using open Zeppelin a lot

of this can be done for us all we need

to do is create the message type hash

and hash that together with the message

data to create the hash struct of the

message we can then pass this as an

argument to the function uncore typ data

V4 and then this will add the EIP 712

domain and the domain type has and hash

it all together to create the digest so

we pass our message through to get

message hash to do all of that for us do

all of the hashing for us and get the

fully encoded EIP 712 message and then

we pass that through to our get signer

open Zeppelin and this does the same as

what we were doing before so when we

were using EC recover directly but

instead it uses ecdsa do TR recover from

open Zeppelin try recover then checks

the S value of the signature to check

for Signature malleability and then uses

the EC recover pre-compiled to retrieve

the signer it then also checks if the

signer returned is the zero address

because if the signer is not valid then

e recover will return the zero address

and we'll retrieve the expected signer

which we can then compare to the actual


signer that we had to verify the

signature so as mentioned earlier EIP

712 is key to preventing replay attacks

replay attacks are where the same

transaction can be sent more than once

or the same signature used more than

once the extra data in the structure of

EIP 712 prevents these replay tabs so

that is a lot of information and it may

sound super confusing but I encourage

you to try and use this in practice

because this is where the knowledge is

really going to be solidified and so to

summarize EIP 191 standardizes what the

signed data should look like EIP 712

standardizes the format of the version

specific data and the data to sign so to

implement signatures and signature

verification into your smart contract

it's imperative to understand the these

two eips so now we're well on our way to

writing secure smart contracts this is

super confusing stuff and it took me a

long time to get my head around so don't

worry if you're a little confused this

is confusing stuff now before we go

ahead and implement this into our smart

contract let's take a little segue into

ecdsa signatures what are those vrns

components that we passed through we


said that they were components of the

signature but what actually are they

let's go into that now

okay so now that we know a little bit

about signatures now we can finally

understand why this snake token we keep

seeing this weird EIP 712 version thing

so as Kira just spoke about this EIP 712

version is going to be the version of

EIP 712 that we're working with which

we're working with number one we can

look up EIP 712 in the ethereum uh in

the ethereum Improvement proposals

website which is this typed structured

data hashing and signing this this what

Kira Sun just went over and if we scroll

down we can see in here we see version

where is version version we can finally

see what these EIP 712 things are for so

right anytime we create a token we

usually add this name and this version

thing for some reason so if we go to the

erc20 we see it's the name EIP 712 and

the version EIP 712 so the name EIP 712

is going to be the maximum 50 character

user readable string name of the signing

domain and then the version is the

maximum 20 character current main

version of the signing domain signatures


from different versions are not

compatible if we scroll down all we

really do with these two is we do this

EIP p712 domain separator do init so we

can look that up as well in the utils

scroll down EAP 712 domain separator we

can look in the init here all this is

doing is it's making is it's setting

this contract up so that it can do these

signatures without running to security

issues like signature replays or chain

replays Etc so there's just a ton of

stuff in here a ton of boilerplate in

here that has to do with the different

versions of EIP 712 the main separators

getting hash data Etc so everything in

here is just making doing signatures

much better now one of the questions is

okay cool Patrick but like why is this

why is this here like what what do we

care about signatures does this erc20

have any signature functionality and the

answer is absolutely so on here there's

this function called permit and if you

look here you can see this looks pretty

similar to approve except it has a VR

ands at the end here so as you've seen

by now having done many different tests

anytime you want to interact with a

smart contract you need to send two


transactions right you need to First do

an approve and then you need to call the

transfer from now this is incredibly

annoying for a lot of people for a lot

of reasons because the user has to call

this approve every single time so what a

lot of people in the ethereum community

did was they said hey it would be great

if the approver could just sign

something somebody else could pay the

gas costs of approving that way I could

just roll up and call my single function

have a much better experience there's

this EIP 2612 which talks a lot about

this permit extension to EIP 20 signed

approvals and so a lot of tokens have

taken on this permit functionality to

make people's lives with working with

tokens a lot easier so this a bit of a

mouthful but essentially this name and

EIP 72 version this makes signing and

working with this permit functionality

much easier prevents replay attacks and

prevents a lot of attacks like that so

it is incredibly powerful and we're

going to be using some of it here now if

you want to go to the extra mile in the

Mox and full course we have this subl

lesson signatures called signatures and


solidity where we have all the code that

Kier went in from her video now granted

this is all solidity code but it does

walk through exactly what's going on

under the hood of this e712 domain these

different functions Etc how they

actually work and it starts all the way

at the top with kind of the simplest way

to do a signature you just Hash a

message which really just starts with

the simplest way to work with and deal

with signatures and if you go to the

tests in here you can even see how the

signatures are created you scroll down

to the bottom of the test in here

there's a little helper function called

sign message simple where you just sign

a message you have sign message EIP 191

which signs a message in the style of

EIP 191 then you have sign message EIP

712 which signs a message in the format

of EIP 712 if you want to go a little

bit farther go a little bit deeper like

I said I know this is in solidity but

this can help you learn a little bit

more now we're not quite done learning

about signatures because Kira mentioned

this thing called ecdsa recover in that

last video and that's something that is

going to be incredibly important to what


we're doing here with our Merkel airdrop

so let's keep giving kir the spotlight

as she explains what ecdsa signatures

are how they work and how we can apply

them have you ever heard of ecdsa and

ecdsa signatures before and what are

these VR and S values where do they come

from everyone just says ecdsa is just

some math magic and don't worry about it

and that VR and S are basically just the

signature but like what are they really

I'm going to take you through that right

now but don't worry you don't need to

have some crazy in-depth math knowledge

you don't need to have a Math's degree

to understand this I'm going to be

taking you through things from a high

level so we can understand ecdsa

signatures how they work and what the

heck vrns are let's get into it ecdsa

stands for the elliptic curve digital

signature algorithm bit of a mouthful

and it's based on elliptic curve

cryptography don't worry we'll go

through what that means in a second but

it's used to generate key

authenticate sign and verify messages

but first of all what actually are

signatures let's do a brief explainer


signatures provide a means for

authentication in blockchain technology

allowing operations such as sending

transactions to verify that they have

originated from the intended sender

proof of ownership in ethereum is

achieved using public and private key

Pairs and they are used to create

digital signatures signatures are

analogous to having to provide ID to

withdraw from the bank they're kind of

like a digital fingerprint and they are

unique unque to you the user this public

private key pair is used to verify that

the sender is the owner of the account

this is of course known as public key

cryptography and involves asymmetric

encryption which sounds confusing but

more on this later the private key is

what is used to sign the message and is

used to derive the public key the public

key is used to verify the owner knows

the private

key it is extremely difficult and we can

assume impossible to to derive the

private key from the public key even for

a computer ignoring Quantum Computing

but don't worry about that right now and

this means that knowledge of the public

key does not Grant access to the account


this is why if you share your private

key that is a big problem because you

can access the account but if you share

your public key then you're fine if I

give Patrick Collins my address he can't

steal anything these public and private

key pairs Define ethereum externally

owned accounts or EAS and they provide a

means for interacting with the

blockchain by signing data and sending

transactions without others being able

to access accounts they do not own an

ethereum address is used as

identification and is the last 20 bytes

of the hash of the public key but how do

we create public and private Keys how do

we create signatures and how do we

verify signatures let's now dive into

ecdsa how it works and what it is ecdsa

is a signature algorithm based on

elliptic curve cryptography

and it is the cryptographic algorithm

used to do those operations we were

talking about create Keys create

signatures and verify signatures and we

need to understand how they work from a

high level in order to be able to

implement these things into our smart

contracts and ensure that they are


secure the specific curve used in ecdsa

in ethereum is the setp 256 K1 curve and

it was chosen for its interoperability

with Bitcoin its efficiency and security

and as with all elliptic curves it is

symmetrical about its x- axis therefore

for every coordinate on the curve there

exists another coordinate at the same X

point and each point on the curve is

your v r and s they are the coordinates

of the points on the curve each point is

a unique signature now for every x

coordinate on the curve there exists two

valid signatures which means that if a

malicious actor has access to one of

those signatures even without the

private key they can compute the second

one this is known as signature

malleability which is a form of Replay

attack resources will be left down below

if you're watching this on YouTube or in

the GitHub repo if you're on updraft if

you would like to learn more about

replay attacks now there's a couple of

constants that we need to quickly Define

associated with the secp 256 K1 curve

the first is the generator Point G and

is just we can assume random point on

the elliptic curve it's purely a

constant the second one is n which is


the order of the subgroup of the

elliptic curve points and it's

generating by G and all you really need

to know about n is that it defines the

length of the private key and it's a

prime number now it's not crucial to

understand what these constants mean we

purely just need to remember that they

are constants they are just constants

that are going to be used in subsequent

calculations ecdsa signatures contain

three integers and they might be

familiar to you v r and s therefore

signatures can be denoted as VR and S R

represents the X point on the elliptic

curve based on some random Point capital

r on the curve but it's just the x

coordinate s serves as proof of the

signer's knowledge of the private key

and is calculated using a random

constant K which ensures that the

signature is unique every time V is used

to recover the public key from R and

represents the index of the point on the

elliptic curve whether the point is in

positive y or negative y this is known

as the polarity let's now go through how

public and private private keys are

generated private key is generated as a


random integer within the range 0 to

nus1 where n is again the order the

public key is an elliptic curve Point

calculated by timesing the private key

with the generator point but how do we

know the ecdsa private keys are secure

this is because of the complexity of the

lipic curve discrete logarithm problem

which basically says that if we times

two big integers together the output

being a giant integer using just the

output we cannot feasibly calculate the

inputs since Point arithmetic in a

finite field does not support division a

computer would instead have to use brute

force to determine P even though G is

known and this involves trying every

possible value of P to find the correct

value which is not feasibly possible

imagine I have two large prime numbers

and I times them together and I give you

this output do you think you could

calculate the inputs unless you're a

quantum computer I don't think so so we

can assume this is impossible even for

computers now how are signatures created

signatures are created by combining a

hash of a message with the private key

this combination is done using the ecdsa

algorithm firstly using the sh 256


hashing algorithm we hash the message

then secondly we generate a securely

random number K the nons we then

calculate a random number capital r

which is the nons times the generator

point and take its x coordinate this

this is R lowercase R

VSR this is the r part of our signature

using the following formula we then

calculate s using the nons the hash of

the message the private key the r part

of the signature and the order n v then

defines whether we are using the

positive part of the y- AIS or the

negative part of the y- axis finally how

are ecdsa signatures verified the ecdsa

verification algorithm takes the sign

message the signature from the signing

algorithm and the public key and outputs

a Boolean representing whether the

signature was valid or not whether the

recovered signer matches the provided

public key this works in Reverse of the

signing algorithm we convert the S

coordinate back to an R coordinate and

verify that the provided R coordinate

matches the calculated R coordinate this

is done using the following formula

which is essentially just a reverse of


what we did when we were signing the evm

precompile EC recover does this for you

in smart contract s it enables us to

retrieve the signer's address of a

message that has been signed using their

private key using ecdsa and this is what

allows smart contracts to verify the

Integrity of a signature and retrieve

the signer using EC recovered directly

can lead to some security issues so the

first as we discussed is signature

malleability where because the curve is

symmetric about the x-axis there are two

valid signatures for each value of R so

if an attacker knows one signature they

can calculate the other one one this can

be mitigated by restricting the value of

s to 1 half of the curve if s is not

restricted the two valid signatures

exist and therefore the smart contract

can be vulnerable to Signature

malleability attacks however if you're

using open Zeppelins libraries such as

the ecdsa library to verify signatures

then you are protected against signature

malleability attacks as long as you're

using versions greater than

4.7.3 for example as you can see in the

code from this lava Labs code for arena

udit you can see the EC recover is being


used directly without any checks on S so

there is no restriction and both

signatures would be valid you shouldn't

Implement EC recover directly therefore

open Zeppelin's ecdsa Library should be

used to validate signatures aside from

signature malleability the other issue

with using EC recover directly is that

if the signature is invalid EC recover

will return the zero address now if this

is not handled correctly in the

implementation in the smart contract

then this can lead to issues so there

should be a check check in the smart

contract if EC recover is returning the

zero address and then the smart contract

should revert if you're using open

Zeppelin's ecdsa library then this check

already exists and you're protected

against this vulnerability now this was

a lot of information and this may be

overwhelming so well done give

yourselves a pass on the back for

getting through this if this was

confusing to you or you need to rewatch

this video go read some other articles

immerse yourself in some Math's magic

then go ahead because this is extremely

complex stuff and you're probably not


going to get your head round it the

first time but well done cuz now you

understand ecdsa signatures we know that

ecdsa is used to generate public and

private Keys generate signatures and

verify those signatures and we have

walked through step by step how this is

done so thank you for

watching now we're going to take a

little bit of a tangent here and talk to

you about transaction types if this

doesn't sit with you the first time

that's okay because again we're going to

be working with Kira she's going to be

showing us a couple of different

examples that are once again in solidity

we haven't worked with solidity but it's

really just important that you keep in

mind that there are different types of

transactions different transaction types

she is going to show us some examples in

solidity of what those look

like when sending transactions

throughout this course you may have

noticed something called transaction

types for instance when we deployed a

smart contract on ZK sync using remix we

signed find a message which contained

the transaction type 113 in the message

additionally we added the-- Legacy flag


when we deployed our smart contracts

with Foundry ZK sync you may also notice

on ether scan or ZK sync block scanners

the attribute transaction type on all of

your transactions and in this example it

says transaction type two let's go

through and break down all of the

different transaction types and what

this means ethereum and ZK sync share

four transaction types first transaction

type Z Legacy transactions when we added

that-- Legacy flag we were specifying

transaction type Z this was the ethereum

transaction type before ethereum

transaction types were even introduced

and it was the very very first

transaction type secondly we have

transaction type 1

0x01 there were some contract breakage

risks associated with EIP 2929 and EIP

2930 optional access lists solved this

in introduced transaction type one and

this contains the same Fields as Legacy

transactions with an additional access

list parameter which contains an array

of addresses and storage keys and this

enables gas savings on Cross contract

calls by pred declaring the allowed

contracts and storage slots the next


transaction type was introduced by EIP

1559 and this is transaction type 2 or

0x02 and it was introduced in ethereum

London fork and this transaction type

aimed to tackle High Network fees and

congestion and it was all around gas

fees Legacy transactions had the gas

price parameter and this was instead

replaced with a base fee which was

modified each block it also added the

following parameters Max priority fee

per gas which is the maximum fee the

sender is willing to pay the max fee per

gas which is the maximum total fee that

the sender is willing to pay so like how

much extra are they willing to pay to

have priority plus that base fee is the

max fee per gas it should be noted here

that Z kync does support type two

transactions but it does nothing with

the max fee parameters because Gas Works

a little differently on ZK sync and

finally we have type 3 or 0x03

transactions and this was introduced in

EIP 4844 Proto Dan sharding or blob

transactions and this was introduced in

ethereum's denen fork and provided an

initial scaling solution for rollups

while their usage was still low or is

still low depending on when you're


watching this and it introduced a couple

of new parameters alongside those

introduced in type zero and type 2

transactions it introduced Max blob fee

per gas which is the maximum fee per gas

the sender is willing to pay for the

blob gas so this was a separate Market

from regular gas it's like the maximum

extra fee for the blobs and then also it

had blob versioned hashes which was a

list of The versioned Blob hashes

associated with the transaction blobs

The Blob fee is actually deducted and

burned from the sender before the

transaction executed which means in the

case of transaction failure it's

actually not refunded and in a second we

will go into EIP 4844 Proto sharding and

blobs in more detail in Patrick's video

so wait a second for that but we have

two more transaction types to go through

and these are ZK sync specific

transaction types so first we have EIP

712 transactions on ZK sync and these

are those type 113 transactions or 0x 71

transactions and if defined typed

structured data hashing and signing as

we know EIP 712 introduced a way to

standardize the version data and also


the data to sign so that it could be

decoded and understood in applications

like metamask type 113 transactions

enable us to access ZK sync specific

features like account abstraction and

pay masters and smart contracts must be

deployed with these type 113

transactions the fields for type 1113

transactions are the same as standard

ethereum transactions plus a couple of

additional fields gas per Pub data which

is a field denoting the maximum gas the

sender is willing to pay for a single

bite of Pub data Pub data is simply the

L2 State data that is submitted to the

L1 the data that they are sending custom

signature which is a field for the

custom signature for when the signer's

account is not an EA pay Master params

these are parameters for configuring a

custom pay master so a smart contract

that is going to pay for the transaction

for us and also Factory depths so this

should contain the bu code of the smart

contract that is being deployed now

finally we have type five transactions

or 0x FF and these are priority

transactions and they enable us to send

transactions from the L1 to the L2

directly in ZK sync and so now we know


all of the different transaction types

before we head back to remix here's

Patrick who's going to explain to us all

about blobs Proto Dan sharding and EIP

4844 type three

transactions so we're not going to do a

lot of work with these transaction types

in this project here however it does

finally explain what's going on with

these warnings that we always see

whenever we work with zync so I'm on the

completed mock signatures code base here

again you won't have the completed code

here but when I run MOX run deploy or

MOX run deploy mercal airdrop Network

aav VM right so deploying to the ZK sync

Network we always will get these weird

warnings hey uh user warning no EIP

1559 transaction available falling back

to Legacy it's because most current

tooling automatically defaults to these

type two transactions AKA these EAP 1559

transactions ZK sync doesn't have those

ZK sync doesn't need those because of

the way ZK sync is built so ZK sync just

goes hey let's just use type zero those

work perfectly well here and whenever we

run with titanoboa it will always try

the type Tye two transactions first see


that those don't exist on zync and then

fall back to type one so that's why you

always see these warnings and that's

because of these different types of

transactions all right and finally we're

going to talk a little bit more about

two more types of transactions blob

transactions and type 113 transactions

we're not really going to be using them

too much for this section here but it's

incredibly helpful to know and will give

you more s it as to why you might be

running to errors and how different

things work so let's go ahead we'll

watch these two videos on blob

transactions and type 113 transactions

as

well in a normal transaction all your

transaction data is stored onchain

forever that shitcoin that you bought

you thought would Moon and went to zero

yeah everyone can see you did that

forever blob transactions a new

transaction type AKA type 03 however

give you a box to cram in data that will

eventually be deleted once the

transaction is included in the block it

stores everything per usual but after a

short delay maybe 20 to 90 days we

delete whatever you put in this box this


is known as The Blob which is sort of an

acronym for binary large objects a lot

of people have been using the sidecar

analogy with a blob being the side car

of a motorcycle the motorcycle being the

transaction and we eventually light the

side car on fire and throw it away blob

transactions were included in the

ethereum denune upgrade on March 13th of

2024 and rollups have been absolutely

Lov loving it these blob transactions

came from EIP 4844 AKA Proto dank

sharding which is a really cool name but

it was actually just named after the

researchers who came up with this so why

do we give transactions this optional

box for them to dump this temporary data

well it goes back to ethereum's biggest

issue today that sending $1 cost me

twoing dollars ethereum right now is

crazy expensive this is due to the

blockchain trima problem and some other

stuff Link in the description rollups

are the solution that we've come to know

to help scale a

so that our transactions aren't this

expensive you can go to ZK sync arbitr

or optimism and you can send that $1 for

substantially cheaper than you could on


the ethereum main chain and we as a

community have essentially settled on

rollups being the way we're going to

scale ethereum for the next few to

several years the way they work is they

essentially execute a bunch of

transactions on their own chain bundle

up and compress the transactions into a

batch and submit that batch back to

ethereum with many l2s processing

transactions you can get a lot more

transactions for a lot cheaper because

you're compressing all these

transactions on all these rollups or all

these l2s now when these l2s submit

these batches back to ethereum ethereum

has to do a little work to verify that

the batch of transactions is actually

good and that right there is where the

issue is when the L1 when ethereum

verifies that a transaction is actually

good it only needs the compressed batch

of transactions once to verify that it's

good and then it doesn't care about the

data anymore but before this upgrade

when you submitted this batch of

compressed transactions you had to

submit the whole chunk of transactions

and permanently stored on every single

ethereum node on the planet you see the


issue there we needed this data for like

a second and then every single node

would have to hold on to it even though

nobody ever cared about that data ever

again it would be like if every single

time you passed an exam in school you

had to carry that exam around with you

at all times what's more important than

this state blow is actually the gas

costs if you store a ton of data on

ethereum or N1 that means every single

node has to store that data as well

which requires them to go out and buy

more Hardware or do more computation and

so if you want to store more data on

ethereum you have to pay more gas and

since this compressed batch of

transactions is still a ton of data that

before this upgrade we were permanently

storing on ethereum rollups had to pay a

ton of gas so uh the rollups were kind

of pissed they didn't love this and

neither did the ethereum community so

these rups essentially said hey so like

we're the future of ethereum scaling but

this call data is super expensive what

if we just like deleted it after we

validated our transactions were good

we'll post our compressed batch we'll


check that it's good and then we'll dump

it that way we don't have to pay the

cost of storing that data forever and

then we as the ethereum community went

that sounds like a pretty good idea and

so the blob transactions were born so

how are blobs used in practice embrace

yourself we're going to get a little

technical here for a second this is an

example example of a transaction on the

ethereum main chain where ZK sync

actually sent its batch of compressed

transactions to the ethereum L1 if you

scroll down in here on ether scan you

can actually see this new section here

called total blobs and if we click into

this which if we scroll down in here and

we click one of these blobs here we can

see this massive chunk of data like

literally absolutely massive that is not

being stored on ethereum because it was

instead sent as a blob and will

eventually be deleted what's cool too is

ether scan gives us this little blob gas

used and blob as call data gas here

where it shows you how much more

expensive this data would have been if

it was submitted as call data as opposed

to blob data here obviously it's way way

cheaper for rups to submit this data as


a blob than as call data which is what

they previously would have had to have

done getting more technical here what's

interesting is that the L1 ethereum

smart contracts have to validate that

this batch of transactions is actually

good they have to validate essentially

that this blob is good however if they

get access to the blob and they do

computation with The Blob they would

have to have access to the blob which

means they would need to store it on

chain which we can't do so what the hell

and this is where the Proto dank

Charters were actually smart enough to

see this coming and actually created a

new OP code and a new pre-compile to do

some math magic to verify these blobs

they created a new blob hash op code and

a new point evaluation pre-compile and

with these two new tools that was all we

really needed to do math cryptography

magic which there's a lot of that in web

3 The Blob hash will instead essentially

grab that whole blob and hash it using

some math magic and we can use this hash

actually combined with some proofs that

we submit in a function to actually

verify that these blobs are good for


example if we actually open this up in

tenderly and we scroll down we can see

there's this function here called verify

blob information that gets called which

does exactly what it says it's going to

verify the blob information looking at

this function we can see it takes some

bytes call data called Pub data

commitments this is essentially going to

be some cryptographic proofs that we

generate offchain and some other data

and then the list of blob hashes which

we access with that blob hash op code

and in this function we eventually call

this internal function called point

pre-compile which is where we send all

that data to that pre-compile to help

make sure that this data is actually

solid the exact function that's actually

called with this ZK sync transaction in

specific is this commit batches where it

sends a ton of data including these

cryptographic proofs that's going to

combine with these blob hatches to make

sure that the blob is actually solid and

boom with this information here we can

now verify this blob this batch of

transactions is actually solid without

having to store that massive chunk of

data on chain and bankrupting these l2s


which are definitely not making a

ton of money right now and we're able to

do a lot of this due to the beauties of

cryptography and that's how blobs work

so a quick recap of what blobs are blobs

are a new transaction type that allows

us to store data on chain for a short

period of time we can't access the data

itself but we can access a hash of the

data with the new blob hash op code and

blobs were added because rollups wanted

a cheaper way to validate transactions

now we showed you a quick example of ZK

sync but in essence this is how a lot of

these rollups actually work quick

summary of how the rollups actually

validate these transactions you submit

your transaction with a blob along with

some type of proof data the contract on

chain accesses the hash again of The

Blob with The Blob hash op code it will

then pass your blob hashes combined with

your proof data to that new Point

evaluation op code to verify the

transaction batch using some math magic

and boom to demonstrate how to send your

own transaction using a blob I've

actually created a little GitHub repo

Link in the description showing us how


to send one of these transactions first

thing you're going to want do is set up

a connection to the blockchain per

normal and then just create some encoded

text for example we're using this as our

blob data now the thing is blobs have to

be at least

4,096 words of 32 by words combined so

we actually have to take this encoded

text and combine it with a ton of

basically zeros so that we can create

this this blob you cannot have a small

blob they're all big then what we do is

we actually create our transaction

object as you you normally would one of

the big differences is we're going to

change the type of transaction to a type

three transaction normally you'll see

normal type two transactions which is

that EIP 1559 transaction and it's the

default transaction now additionally we

want to add some blob gas feed

parameters to our transactions as well

one of the other really interesting

implications of adding blobs is that

we've essentially created a new type of

gas market a gas market for blobs which

has a whole bunch of interesting

Downstream effects video for another

time and then finally we set up a gas


estimate we sign our transaction and all

we do is we add our blob data to a

little blob compartment of our

transaction we sign it and then we send

it if I wanted to run this on a local

blockchain we go just set up Anvil set

up my Anvil chain to run for this I'm

using Ry which is like a python thing I

would do Ry run send blob actually run

this and we can see two responses here

we can see a transaction receipt right

here and then if we scroll up we can see

see the actual blob that we're sending

and yes I'm scrolling up this whole time

it's this massive object that we send

EAP 4844 AKA Proto D sharting is this

intermediate step in the ethereum's

longtail scaling road map and is a

prerequisite to dank sharding which

includes a lot more cool features cooler

than the name dank sharding too but

rollups are happening now and we said

hey rollups are happening now we need

them cheaper now so the ethereum

community implemented dank sharding the

ethereum docs actually do a phenomenal

job of explaining dank sharding where

it's going what it's going to look like

in the future so now you understand


blobs Proto Dan sharding if you want to

try out sending your own blob

transaction check the link in the

description thanks for getting froggy

with us and we'll see you next

time let's go back to remix and have a

look and see if we can understand what

was going on there okay so now that we

understand both about EIP 712 signatures

and transaction types what actually is

the mechanism or format that allowed

remix to be able to send a transaction

for us in Remix by signing a message now

what happened here was it used something

called account abstraction and ZK Sync

has native account abstraction which

means it's built into the blockchain

account abstraction enables users assets

to be stored in smart contracts rather

than externally owned accounts this

means that users can use Smart contracts

as their accounts rather than something

like metamask on ethereum there are two

types of accounts externally owned

accounts where you have a public and a

private key and a user has to initiate

and sign transactions and then also

contract accounts where the smart

contract itself is the account and any

arbitary logic can be implemented so you


can have things like multiple signers or

the ability to have other people pay for

your gas and send transactions for you

accounts in ZK sync era can initiate

transactions just like an EA but can

also have arbitrary logic implemented in

them and so they have account

abstraction natively and since smart

contract accounts are fully programmable

this allows various customizations such

as signature schemes having multi-sig

capabilities you can set spending limits

Etc and this is the mechanism that

allowed remix to be able to send our

transaction for us by our sign ing an

EIP 712 message and since ZK Sync has

account abstraction natively my ethereum

address on ZK sync is automatically a

smart contract account and so remix was

able to send the transaction for

us welcome back I hope you're all Theory

crafted up because we just went through

a lot of different types of signatures

and now we're going to finally apply

that signature knowledge to our contract

here we're not really going to do

anything with the transaction type

knowledge but that's just some good

knowledge to have so let's go ahead


let's add this in here so we're going to

allow people to call this claim function

by passing in a signature here so what

we want to do is we want to First

convert this account and amount into a

hash because when the user signs this

what they're essentially going to be

signing is the account and the amount so

we're going to first do let's get rid of

this little signatures bit here and

we're going to say the message hash it's

going to be bytes 32 equals

self.org

message hash and we're going to pass the

account and the amount so when a user

signs something they sign a very

specific something and we're going to

set up our contract such that they need

to sign the account and the amount

combined and that's where this VR and S

is going to be generated from the

combination of the account and the

amount so I'm going to create a new

function down here called def get

message hash it's going to take an

account address and an amount uint 256 U

256 and this is going to return a bytes

32 like so in here we're going to say

return and this is where once again

snackmate is going to come to our rescue


we could kind of do all the hashing

ourself however

snackmate has a lot of this hashing

stuff

formatted correctly for us has this

function called hash typed data V4 where

it runs this function here which

essentially hashes the data but puts it

in this correct format this EIP 712

format that you know pretty much every

smart contract in the world follows

these days so what we're going to do is

we're going to first do up at the top

we're going to say from snack mate.

utils import 7712

domain

separator as EIP 712 and I should spell

that

right

EIP 712 domain

separator there we go and at the bottom

we're going to say return e712

doore typed data

V4 with kak

256 ABI and code

and we need to pass in the message type

hash and we need to pass in this struct

airdrop claim with account equals

account and amount equals amount we


haven't created these yet but it's these

it's this format that will allow our

signatures to have this e 712 format so

that once again what's the purpose of

VIP 712 it's so that we can have a nice

readable

output in like a mamass when we sign

something that looks like this instead

of just a blarel of X data so we need to

create this message type has we can kind

of make this whatever we want but we

typically want it to contain some

information about what we're doing so

we're going to say it's going to be a

constant constant bytes

32 equals kachak

256 of airdrop claim

address account oops address account un

256 amount like this oh what's the

matter of me for Kit check like that and

then we also above these need to create

a new struct called

airdrop

claim with account address and amount un

256 again this is just so that this

these sing atures will be formatted

nicely we're not really going to play

with it too much here but we do want to

follow convention so we have message typ

has here that looks good and then we


have airdrop claim as well that looks

good and what's a matter about airdrop

claim has not been

created that's fine airdrop claim

airdrop airdrop claim that looks better

and then we're getting cannot access EIP

712 State this EIP 712 contract has

state so you know what that means we

need to actually initialize it so right

at the top we can do in she alizes EIP

712 which means that if it has an init

function we need to call it so write in

our init here e712 doore

anitore and this takes an EAP 712 name

and a version just like we've been

seeing 100 times so AP

712 name and this can be pretty much

whatever we want here we'll say

constant string 50 equals Merkel airdrop

and then we need an es 712

version which will be a constant let's

do string 20 this will be version number

one so name and then version like this

great and now we finally have this

message hash that we can use and what we

can do is we can create a function

called is valid signature to make sure

that the message hash here is going to

match the message is going to so what


we're going to do now is we're going to

make sure that this message hash right

the combination of these two did the

signing of them is correct so we're

going to make sure that these VR and S

are accurate based off of the account

and the amount so we're going to do

assert self. is valid signature this is

a function that we're going to create

and we need to pass the account the

message hash and the VR and

s s and otherwise we're going to say

invalid

signature like this so down here let's

do oh and this needs to be at internal

sorry down here we're going to make an

internal function def is valid signature

we're going to take an account address a

message Hash A byes 32 V is going to be

a uent 8 R is going to be a bytes 32 s

is going to be a bytes 32 and this is

going to return a bull it's going to

return true or false that's it so first

thing we need to do is we need to

convert all of these to uent

256s so we're going to say v as a u 256

U 256 equals convert V to a u 256 we're

going to copy paste this line to do the

same thing with

r r copy paste this line do the same


thing for S so we first need to make

them all you 256 is because we are going

to call another function from snck mate

so as Kira showed we could just call E

uh ECR or what is it called let's go to

the Viper Dot

we could just call the builtin to Viper

EC recover which will recover the

address associated with the public key

from a given elliptical curve signature

remember we learned this way way back in

blockchain Basics anytime somebody signs

something anybody can verify who was the

signer and it's this function that

allows us to do exactly that we could

directly call that but typically we want

to use a library which has some helpful

benefits like trying it again if it

fails or tweaking the parameters if

they're a little bit wrong so mate has

this thing called ecdsa Dov which we're

going to actually import so we're going

to say from SN mate. utils import

ecdsa and instead of raw calling ECR

recover we're going to do ecdsa doore TR

recover V uh VR and S and we're going to

pass in here here the message hash which

is often known as the digest and then

we're going to pass in the v r and the S


like so and this is going to return the

actual actual signer so we're going to

take the vrns we're going to combine it

with the message hash and we're going to

see who actually signed this based off

the vrns that were given this is going

to be an address

VR not vrf and then all we have to do is

return the actual signer equals the

account so if the actual signer is the

account this will return true otherwise

this will return false and this is how

we can verify that these signature

pieces are correct so back up here we'll

just say assert self that is valid

signature we pass in all the details and

if it's valid we get we pass if it's not

valid we get invalid signature hooray

and with that this is our completed

airdrop

code now a lot of you might not believe

me and that's okay because we are going

to write some tests to make sure that

this works huh what do you think about

that so let's go ahead let's actually

write some deploy scripts so we can

write some tests here so new file deploy

merp and let's go ahead and let's deploy

this so let's do a little def moas main

call deploy deploy Merkel like this


we'll do def deploy Merkel and in here

we're first going to deploy that token

so we'll say from SRC import snck token

and we can do token equals SN token.

deploy let's create an initial Supply so

we'll do in sh Supply equals to way 100

ether and that is from eth utils import

to way and it's mad at me because UV add

moccasin yes I would like to change okay

great that looks good now then we need

to generate the Merkel tree so in that

script that I had you copy paste we're

going to call this where is this

function not get Merkel roof not get

generate Merkel tree and this is going

to return two objects it's going to

return the output and the root we only

care about the root here so we're going

to call we're going to say from

scripts dot make or from script make

Merkel import generate Merkel tree and

we're going to say underscore comma root

equals generate Merkel tree here now

that we have the token and the root we

can actually

deploy the

Merkle airdrop contract so we'll say

airdrop contract equals Merkel air drop.

deploy we pass in the root think the


root comes first right the root yep we

passed in the root and the token do

address like this then we need to give

the airdrop contract all of our tokens

so we'll say token.

transfer the airdrop contract. address

the initial Supply here oh and then we

need to do initial Supply in here as

well and then we can just return the

airdrop contract and we can do a little

test here with MOX run deploy Merle

oh and it looks like it worked let me

just do a little print F deployed to run

this again and voila lovely and let's

have this return turn the deploy Miracle

as well great so we have a way to deploy

this let's write a test because some of

you might not believe me here and that's

okay and this test is where we're going

to see the magic happen because we're

going to be doing all the signing that

we need to do for this contract to

work all right let's start to write some

tests so you can finally see all the

pieces of this signature thing come

together let's first create a com

test.py or we will add our fixtures do

import boa from script. deploy Merkel

import deploy Merkel we're probably

going to need oh we're going to need to


do import pest we're probably going to

need to do add pest.

fixture def

Merkel return deploy Merkel like this

let's also get the token let's do at py

test.

fixture def token and let's time instead

of doing the Manifest named let's just

do have this input the Merkel and we'll

say from SRC import snck what's it snck

token is that what we call that yep snck

token snck token and we'll say return

snck

token. Merkel

do what do we call

it airdrop

token mer. airdrop

token and let's also create a user at

pest. fixture def user and for these

signatures we are going to have to work

with real keys so we can't do you know

boa EMV do generate

generate address or whatever that is

because that just generates an address

we actually need to have an account with

a real key so what we're going to do is

we're going to run Anvil real quick

we're going to grab where is it the top

private key we're going to put this into


our test we're going to say Anvil key

equals

paste it in and we're going to say from

eth account import account and we're

going to say account equals account.

from Key Anvil key and the Anvil key

also if we look at our Merkel output is

associated with one of these addresses

in here so if I look up

Anvil we scroll up we grab this address

here aha it's going to be this address

here so it's going to be this leaf that

we're going to generate that we're going

to verify with the Anvil key so and then

we can do with bo. env. prank our

account. address we're going to write

yield account so this is another way to

do a return statement but what's cool

about this this yield account means that

whatever happens next will still be

inside of this width statement uh

hopefully that makes sense I'll explain

it to you more when we actually use this

user fixture so cool so now we have some

fixtures here uh you know let's also add

the Anvil address in here because we're

probably going to need that boom place

it in okay great so now let's do test

Merkel dop and we will write our tests

and we'll see everything come together


so let's create def test Merkel and this

will take the Merkel fixture token and

user so here's where uh this user yield

keyword comes into play so we're going

to do with bo. prank accounted address

yield account so what's going to happen

is you can almost think of this entire

def test Merkel happening inside of this

wi statement here which means that we

will still be which means that we will

still be pranked which is what we want

so that's what that yield piece is for

so we have the Merkel the token the user

and what we want to do is we want to

test to make sure user can claim so

we'll do test merel actually better get

test user can claim like this so let's

get the

starting uh starting token balance of

our user because we want to check we

want to compare the balance before and

the balance after so this will be token.

balance of user. address and if we

wanted to go the extra mile we could

even assert that it starts at zero but

that's fine we don't have to do that now

what we want to do is in our mer this

message hash that gets generated right

it's the it's basically the hash of the


account and the amount which we did down

here we want to get this exact same

value we could 100% do it off chain but

it's going to be a little bit easier for

us to just do at external at view def

get message hash with no

underscore count

address amount un

256 returns a bytes 32 and we'll return

self.org

message hash account and amount like

this uh what did I do wrong count amount

cannot call it a payable function from A

View ah it's because this is a view

function as well okay nice so now we

have this get message hash what I can do

is I can say message hash equals Merkle

doget message has and we're going to

pass in the what the user address and

the amount so we'll say user.

address and we at the top here we can

say from script. make Merkel import

default amount so this default amount is

the amount that everybody is going to be

getting so we'll do we'll hash the user

address with the default amount to get

this message hash now this is what we're

going to be signing we're going to go

ahead we're going to sign this and the

eth utils actually has a nice little


helpful feature helpful helpful command

that allows us to sign this very easily

so we're going to say from eth

account doore utils do signing import

sign message hash isn't that nice and

we're going to do sign message hash we

have to pass in uh if we command click

on this we have to pass in a private key

and a message hash so this weird private

key type we actually have to import so

we'll do from eth keys. datat types

import ort private key and we'll say

sign message hash private key user. key

because this user type comes with a its

private key which we set up in our conf

test like this and we have to do the

private key and then obviously the the

message hash here and this will return

the V uh excuse me the v r and s and

this e signature bytes which we're going

to is basically just the combination of

all of them which we're going to ignore

so we're going to say V comma R comma s

comma uncore equals sign message hash so

now this is how anybody can sign

something off chain right you just get

the message hash that you want to sign

get the vrn S just make sure the way

that you're signing it offchain is the


same way that's being verified onchain

and ideally your signature your hash is

in this EIP 712 format so now that we

have that it's pretty straightforward

now we can do mer. claim B comma R comma

s user. address nope sorry what is it uh

account amount merel proof vrs okay so

let's do uh user. address

default amount next is going to be the

proof which we have in our Merkle output

we have this proof here and remember

this first hash is just the leaf of

another one and this second hash is

going to be the combination of these two

hashes put together right so to make

this easy for us we could just uh grab

this proof here I'll grab this go back

to the test Merkel paste it in here

we'll say proof proof equals now I will

tell you this now this is a dynamic

array bytes 32 so we want to make sure

that these are actually bytes objects

and not just these strings so we

actually want to convert these from

these strings to bytes so we'll say

bytes. from hex and then we'll remove

the zero X and do this and then the same

thing with this bottom line remove the

zero X put that in boom and now these

are actually bytes right because this is


a bytes 32 array so this will create

them as bytes and then we'll pass the

proof in and then the v r and the S so

account amount proof VR and S and if

this is

successful oh and then actually we have

to um and actually one more thing so V

is a u into 8 no problem but R and S are

bytes 32 so let's do from eth utils

import to bytes

so V so R and S need to be bytes 32 so

we'll do two bytes like this and then

two bytes like this great okay and if

that worked

successfully then the ending balance

equals token balance. balance of user.

address we should be able to assert the

ending balance the ending balance is

equal to the starting balance plus the

default

amount let's try this let's do a little

clear here MOX test- K paste it in and

it's indeed successful now if you don't

believe me we can do a couple of things

here we could have somebody else sign

this right so right here we're saying

user. key is signing this and it's we're

saying user. key is the one signing this

we could do a different key right Let's


do let's spin up Anvil again let's do

private key number two so instead Let's

do let's swap this out we paste this in

here let's remove this let's run this

test again oops let's run this test

again and we'll see it actually will

fail value must be a bite string uh well

okay it failed for a different reason um

so let's do uh you know what let's do

this in the comp test let's do paste it

and let's call this bad user and then

instead of anvil key we'll do Anvil key

2 we'll run Anvil here grab this second

key paste it in here for bad user we'll

use Anvil key 2 now over in our test

here we will instead use bad user and

we'll do bad user for everything in here

bad user bad user but we'll still pass

user into the claim let's see if the bad

user can steal the funds if we try to

run this now it'll fail because we

scroll up in here invalid signature

right it's the wrong person signing the

hash it's the wrong person signing the

data and therefore we get invalid

signature and this does not

work so with that being said this leads

us to our first and only Workshop of

this section here if you go to the get

at repo associated with this here are


your Workshop pieces number one deploy

this to ZK sync either via the air test

node spolia or a tenderly eth virtual

Network and I'll tell you right now it's

pretty easy if you do MOX run deploy

Merkel D- Network era VM you'll see

everything already works perfectly for

ZK sync so that should work no problem

but then the more important piece of the

workshop and this is where I want you to

spend 25 minutes maybe more this might

take you this will probably take you

longer than 25 minutes is try to do this

again by making a Merkel tree with eight

leaves so if we go to our make Merkel

right we have this default input which

has one two three four leaf nodes so try

to do one with eight so add four more

leaves here maybe even change the

default amount and once you do that

you're going to want to run you know box

run make Merkel and this will run the

rest of the Merkel script and print

everything to the Merkel output. Json in

the Merkel output. Json go through here

and you'll figure out okay what's the

proof what's the root what you know what

am I how do I deploy this contract to

get eight to work and then write a test


that passes with eight leavs I'll give

you a hint there's a chance that two

proofs might not be enough here so

that's uh your your hint here and you

should be able to figure out why so

these are your workshops I absolutely

want you to work on them spend so for

this one yeah spend at most 25 minutes

on these prompts without the aid of AI

but then when you get stuck if you get

stuck stop take a break and then work

with AI to get these the rest of the way

this might take you an hour maybe 2

hours to get through and that's okay it

might even take you longer everybody's

different so these are your workshops

that I want you to do deploy this to ZK

sync try to make a bigger Merkel tree

with eight leaves instead of the four

that we did here and those are your

workshops so pause the video pause the

course and do the workshop all right

welcome

back did you do the workshops I sure

hope you did because it's these

workshops that's really going to ingrain

these skills in

you so we've learned a ton in this

section so before we send you off let's

do a little refresher of all the things


we learned here and then you can finally

head on over to moxin upgrades here and

we're just about done with the whole

course this is crazy you've got so many

superpowers so let's do a quick

refresher on all the things we learned

number one we learned about this thing

called Merkel trees what what are they

how they work and how we can use them to

our advantage we learn that each one of

we hash data in each one of these leaves

and then we hash sibling leaves to

create a parent leaf or a parent node if

you will then we hash that with another

parent node and we just keep doing that

until we only have one hash left and

that's known as our Merkel root we can

use this Merkel route to do some very

very clever data compression we don't

need to have a giant list of addresses

on our smart contract to say who can

claim all we need to do is post a

miracle rout and then people can call a

claim function with a proof to prove

that they are part of that merco roup We

additionally finally learned about what

the heck this EIP 712 thing was that we

keep adding to all of our contracts and

in doing so we learned about signatures


different types of signatures how

signatures work and we even created this

claim function so that anybody could

call claim and claim the money for the

owner as long as they had the vrns this

way somebody else could sign it and we

saw this in our test this way anybody

could sign the data this way the owner

could sign the data here and then

anybody could call claim but it would

still go to the owner this way the owner

could essentially get a gasless

transaction right all they have to do is

sign it and somebody else could pay the

gas fees for them we learned about ecdsa

recover we learned about e we learned

about EAP 712 and EAP 191

and we learned a lot of fantastic stuff

about proves and signatures and this is

incredibly important cuz really

understanding signatures is kind of how

this whole blockchain thing works so

there's a lot more to go into about

signatures how they work and I highly

recommend you Tinker around with your

metamask and with a lot of the scripts

that we wrote in here to explore more

maybe you don't believe me that this

sign message hash function Works maybe

you want to go deeper so I highly


recommend you go ahead you go to try go

deeper what is this key. sign message

hash how does this work what does this

ecdsa sign what are these functions how

do they work if you want to go deeper

the rabbit hole of cryptography goes

very very deep but we've gotten this far

huge congratulations and now is a great

time to take a break go for a walk get

some ice cream or go to the gym this is

difficult stuff and you should be very

proud of yourself because we are almost

finished with advanced

Advanced Python and Viper take a break

and I'll see you very

soon all right welcome back to the final

section of your Python and Viper Smart

contract curriculum training if you're

following along with the gab repo

associated with this course come on down

to Advanced moccasin section five

moccasin upgrades and you can find the

full code with what we're going to be

working with right here and we're going

to be going over one of the final but

most important Concepts in smart

contract development and that is going

to be proxies now a couple of times

we've gone on to Ether scan and we've


seen this thing or we've gone on to some

block Explorer maybe block Scout Etc

we've gone to contract and we've seen

this read as proxy and write as proxy

proxy contracts are pretty prevalent in

the web through space and understanding

how delegate call works is incredibly

important to you becoming a successful

smart contract developer so in this

section we're going to understand what

these proxies are how they work why

they're important and how they're

actually a little bit controversial as

well in the final codebase that we're

going to be working with is a real

minimal script we're going to try to

make make this a kind of a quick one

even though this is going to be dense

essentially at the end of this we're

going to have two contracts counter one

and counter two they look nearly

identical with a couple of changes in

here and what's going to happen though

is we're going to deploy this erc1 196

contract in Viper which technically

isn't 100% compliant but that's another

conversation we're going to deploy this

contract and we're only going to make

calls to this cont contract we're not

going to make calls to these counter


contracts but yet this proxy contract

will be able to set a number increment a

number get a version and decrement even

though it has none of those functions

and isn't inheriting those contracts

either so let's go ahead let's get

started learning about proxies learning

about upgradeable contracts and let's go

ahead let's watch this video now a quick

note about this video uh I made this a

few years ago and I thought a couple of

jokes were a lot funnier back then they

are than they are now so um uh bear with

the bad jokes thank

you all right and welcome to lesson 13

boundary upgrades where we're going to

learn about upgradeable smart contracts

the pros and the cons now I've done a

couple different versions of this type

of video in the past so we're going to

go through an old video explaining the

concepts of this then we're going to

move over to remix and we're going to

explain an important subl lesson and

then we're going to go to our vs code

and we're actually going to do all of

this in Foundry upgradeable smart

contracts are something that I'm going

to go ahead and just say right out loud


we should deploy as little as possible

we should not be defaulting to

upgradable Smart contracts it sounds

like a good idea in theory but we've

seen time and time again whenever a

protocol has a centralized control over

contracts issues Happen full stop so

when going through this course and when

learning about this keep this in mind

what are the downsides of upgradable

smart contracts and then you can begin

to ask questions have we seen examples

in real life where these downsides have

come to a fruition and I'll say right

now 100% the answer is yes so keep that

in mind when watching this and use this

knowledge to make yourself be an even

better smart contract Dev so let's learn

now I'm editing this video much later

after I filmed it hence why I have a

beard so I'll be jumping in from time to

time updating some of the sections when

deploying your smart contracts on chain

we all know that those smart contracts

are immutable or unchangeable but what

if I told you that they were

mutable well technically I wouldn't be

correct however smart contracts actually

can change all the time when people

transfer tokens when people stake in a


contract or really do any type of

functionality those contracts have to

update their balances and update their

mappings and update their variables to

reflect this the reason that they're

immutable is that the logic itself never

changes and will be on chain like that

forever so technically yes once they are

deployed they are immutable and this is

actually one of the major benefits of

smart contracts in the first place that

nobody can tamper with or screw with our

smart contracts once we deploy them

however this can be an issue if for

example we want to upgrade our smart

contract or protocol to do more things

or we want to fix some glaring bug or

issue that we have now even though we

can't change the specific code that's

been deployed to an address we can

actually do a lot more than you think

and in this video we're going to explain

the different methodologies behind

upgrading your smart contracts and then

we're going to show you how to do it

with hard hat and open Zeppelin huge

shout out to a lot of open Zeppelin and

trailer bits articles that helped me put

this video together uh and a number of


other sources as well links in the

description so let's get to it now at

first glance you might be thinking if

you can upgrade your smart contracts

then they're not really immutable then

and way you'd be right so when

explaining kind of the different

philosophies and patterns that we can

use here we do need to keep in mind the

philosophies and decentralization

implications that each one of these

patterns have as they do all have

different advantages and disadvantages

and yes some of the disadvantages here

are going to affect DEC centrality so we

need to keep that in mind and this is

why it's so important that before you go

ahead and jump in and start deploying

upgradeable smart contracts you

understand the trade-offs so we're going

to talk about three different ways to

upgrade your smart contracts the first

one being the really SLP parameter ties

way to upgrade your smart contracts the

social migration method and then the

method that you probably have heard

about which is proxies which have a ton

of subcategory like metamorphic

contracts transparent upgradeable

proxies and Universal upgradeable


proxies so let's talk about the not

really upgrading method or the

parameterization method or whatever you

want to call it this is the simplest way

to think about upgrading your smart

contracts and it really isn't upgrading

our smart contracts because we can't

really change the logic of the smart

contract whatever logic that we've

written is there we also can't add new

storage or state variables so this is

really not really upgrading but it is

something to think about upgrades is

just parameterizing everything whatever

logic that we've deployed is there and

that's what we're interacting with this

function means we just have a whole

bunch of Setter functions and we can

update certain parameters like maybe we

have a reward parameter that gives out a

token at 1% every year or something like

that maybe we have a seter function that

says hey update that to 2% or update

that to 4% it's just a seter function

that changes some variable now the

advantages here are obviously this is

really simple to implement the

disadvantage is that if you didn't think

of some logic or some functionality the


first time you deployed their smart

contract that's too bad you're stuck

with it you can't update the logic or

really update anything uh with the

parameterization AKA not really method

and the other thing you have to think

about is who the admins are who has

access to these Setter functions to

these updating functions if it's a

single person guess what you have de

centralized smart contract now of course

you can add a governance contract to be

the admin contract of your protocol and

that would be a decentralized way of

doing this so just keep that in mind you

can do this method just need a

governance protocol to do so another

example of this might be a contract

registry and this is something actually

that early versions of a they used

before you call a function you actually

check some contract registry that is

updated as a parameter by somebody and

you get routed to that contract and you

do your call there again this really

doesn't allow us to have the full

functionality of upgrades here you can

argue that this industry is a mix of one

of the later versions but for all

intents and purposes this doesn't really


give us that flexibility that we want

for our upgrades but some people might

even think that upgrading your smart

contract is ruining the decentral and

one of the things that makes Smart

contracts so potent is that they are

immutable and that this is one of the

benefits that they have so there are

some people who think that you shouldn't

add any customization or any

upgradeability you should deploy your

contract and then that's it Trill bits

has actually argued that if you deploy

your contract knowing that it can't be

changed later you take a little bit

extra time making sure you get

everything right and there are often

less security vulnerabilities because

you're just setting it forgetting it and

not looking at it again now if I wanted

to upgrade a smart contract with this

philosophy in mind the philosophy that I

do want to keep my smart contracts

immutable we can instead use the social

migration method which I previously

called the Yeet method and now I think

it's less funny so we're just going to

stick with social migration the social

Yeet method or the migration method is


just when you deploy your new contract

not connected to the old contract in any

way and by social convention you tell

everybody hey hey this new contract this

new one that we just deployed yeah this

is the real one now and it's just by

Convention of people migrating and over

into using this new one that the upgrade

is done hence my slang name of social

Yeet because you Yeet the first one out

of the way and you move to the second

one I think I'm funny this has the

advantage of truly always saying hey

this is our immutable smart contract and

this is our new one this is really the

truest definition of a mutable because

since you give it no way of being

upgraded in place then if somebody calls

that contract in 50,000 years in the

future it'll respond exactly the same

another huge disadvantage here is that

you have to have a totally new contract

address so if you're an erc20 token for

example you have to go convince all the

exchanges to list your new contract

address as the actual address keep in

mind that when we do this we do have to

move the state of the first one over to

the second one so for example if you're

an ERC token moving to a new version of


that ERC token you do have to have a way

to take all those mappings from the

first contract and move it to the second

one obviously there are ways to do this

since everything is on chain but if you

have a million transfer calls I don't

want to have to write the script that

updates everyone's balance and figures

out what everyone's balance is just so I

can migrate to my new version of the

contract so there is a ton of social

convention work here to do trailer bits

has actually written a fantastic blog on

upgrading from a V1 to a V2 or Etc with

this Yeet methodology and they give a

lot of steps for moving your storage and

your state variables over to the new

contract so Link in the description if

you want to read that now let's get to

our big ticket item so in order to have

a really robust upgrading mentality or

philosophy we need to have some type of

methodology or framework that can update

our state keep our contract address and

allow us to update any type of logic in

our smart contracts in an easy way which

leads us to our big ticket item the

proxies what's our big ticket item

proxies people proxies proxies are the


truest form of upgrades since a user can

keep interacting with the protocols

through these proxies and not even

notice that anything changed or even got

updated now these are also the places

where you can screw up the easiest

proxies use a lot of low-level

functionality and the main one being the

delegate call functionality delegate

call is a low-level function where the

code in the Target contract is executed

in the context of the calling contract

and message. sender and message. value

also don't change so you understand what

delegate call means now right great and

in English this means if I delegate call

a function in contract B from contract a

I will do contracts B's logic in

contract a so if contract B has a

function that says hey store this value

in a variable up top I'm going to store

that variable in contract a this is the

PowerHouse and this combined with the

fall bang function allows us to delegate

all all calls through a proxy contract

address to some other contract this

means that I can have one proxy contract

that will have the same address forever

and I can just point and Route people to

the correct implementation contract that


has the logic whenever I want to upgrade

I just deploy a new implementation

contract and point my proxy to that new

implementation now whenever a user calls

a function on the proxy contract I'm

going to delegate call it to the new

contract I can just call and admin only

function on my proxy contract let's call

it upgrade or something and I make all

the contract calls go to this new

contract when we're talking about

proxies there are four pieces of

terminology that we want to keep in mind

first is the implementation contract the

implementation contract has all of our

logic and all the pieces of our protocol

whenever we upgrade we actually launch a

brand new implementation contract the

proxy contract proxy points to which

implementation is the correct one and

routes everyone's calls to the correct

implementation contract you can think

the proxy contract sits on top of the

implementations the user the user is

going to be making contract and function

calls through the proxy contract and

then some type of admin the admin is the

one who's going to decide when to

upgrade and which contract to point to


in this scenario the other cool thing

about the proxy and delegate call is

that all my storage variables are going

to be stored in the proxy contract and

not in the implementation contract this

way when I upgrade to a New Logic

contract all of my data will stay on the

proxy contract so whenever I want to

update my logic just point to a new

implementation contract if I want to add

a new storage variable or a new type of

storage I just add it in my logic

contract and the proxy contract will

pick it up now using proxies has a

couple of gotas and we're going to talk

about the gachas and then we're going to

talk about the different proxy contract

methodologies because yes there are many

proxy contract methodologies as well and

this is why TR bits doesn't really

recommend using upgradable proxies for

your smart contracts because they're

fraught with a lot of these potential

issues

not to mention again you do still have

some type of admin who's going to be

upgrading your smart contracts now if

this is a governance protocol then great

you're decentralized but if this is a

single group or
entity then we have a problem the two

biggest gotas are storage clashes and

function selector clashes now what does

this mean when we use delegate call

remember we do the logic of contract B

inside contract a so if contract B says

we need to set value to two we go ahead

and set value to two but these smart

contracts are actually kind of dumb we

actually set the value of whatever is in

the same stor location on contract a as

contract B so if our contract looks like

this and we have two variables in

contract a we're still going to set the

first storage spot on a contract a to

the new value this is really important

to know because this means we can only

append new storage variables in new

implementation contracts and we can't

reorder or change old ones this is

called storage clashing and in the

implementations we're going to talk

about they all address this issue the

next one is called function selector

clashes when we tell our proxies to

delegate call to one of these

implementations it uses what's called a

function selector to find a function the

function selector is a 4 byte hash of


the function name and the function

signature don't worry about the function

signature for now now it's possible that

a function in the implementation

contract has the same function selector

as an admin function in the proxy

contract which may cause you to do

accidentally a whole bunch of weird

stuff for example in this sample code in

front of you even though these functions

are totally different they actually have

the same function selector so yes we can

run into an issue where some harmless

function like get price has the same

function selector as upgrade proxy or

destroy proxy or something like that

this leads to our first out of the three

implementations of the proxy contracts

this is called the transparent proxy

pattern in this methodology admins are

only allowed to call called admin

functions and they can't call any

functions in the implementation contract

and users can only call functions in the

implementation contract and not any

admin contracts this way you can't ever

accidentally have one of the two

swapping and having a function selector

clash and you running into a big issue

where you call a function you probably


shouldn't have if you're an admin you're

calling admin functions if you're a user

you're calling implementation functions

so if you're an admin and you build some

crazy awesome D5 protocol you better

come up with a new wallet address

because you can't participate the second

type of pro we're going to talk about is

the universal upgradeable proxy or the

UPS this version of upgradeable

contracts actually puts all the logic of

upgrading in the implementation itself

this way the solidity compiler will

actually kick out and say hey we got two

functions in here that have the same

function selector this is also

advantageous because we have one less

read that we have to do we no longer

have to check in the proxy contract if

someone is an admin or not this saves on

gas of course and the proxy is also a

little bit smaller because of this the

issue is that if you deploy an

implementation contract without any

upgradable functionality you're stuck

and it's back to the Yeet method with

you and the last pattern or methodology

that we're going to talk about is the

diamond pattern which does a number of


things but one of the biggest things

that it does it actually allows for

multiple implementation contracts this

addresses a couple different issues for

example if your contract is so big and

it doesn't fit into the one contract

maximum size you can just have multiple

contracts through this multi-

implementation method it also allows you

to make more granular upgrades like you

don't have to always deploy and upgrade

your entire smart contract you can just

upgrade little pieces of it if you've

chunked them out all the proxies

mentioned here have some type of

ethereum improvement proposal and most

of them are in the draft phase and at

the end of this explainer we will do a

demo of showing you how the delegate

call function

Works welcome back hope you enjoyed that

cuz now we're going to create our own

proxy contract ourselves and we're going

to see firsthand how this kind how this

works and I'm going to be showing you a

little bit more granular low level about

what's going on here so if you're in

your MOX CU let's go ahead make Dr MOX

upgrades cphon updraft and let's code

MOX upgrades cphon updraft or file open


folder as we've been doing this whole

time here let's do a little

MOX in it --vs code and we don't have to

do the --p project for this one let's

just do DVS code and in here as per

usual let's go ahead let's just delete

everything so that we start with a blank

contract now what I want you to do as

we've done a couple of times is come to

the MOX upgrades cyphon updraft go into

SRC and grab this erc1

1967. and let's let's copy paste this

into our project we're going to create a

new file ERC

1967. and paste it in this is almost an

ERC 1967 proxy contract let's look at

this in the ethereum eips is the proxy

storage slot a consistent location where

proxies store the addresses of the logic

contract they delegate to as well as

other proxy specific information this is

a standard of working with proxy

contracts that we don't 100% follow in

Viper due to some Viper limitations but

we can basically get everything that we

need what this contract is going to do

is it's going to do some very weird

looking things if you look up at the top

of the contract we have this giant fixed


sized array of un 256 with this massive

massive massive number in here the

reason we have this massive number is

because we want this implementation slot

we want this implementation variable to

be at this very specific slot in storage

and remember since we learned a lot

about storage we learned that since this

is a u 256 array it's going to be it's

going to initialize all these storage

slots to zero and this implementation

address will be set to the storage slot

after all of this and if you go to the

documentation here for the ERC

1976 the storage slot for the

implementation or the logic contract

address is this address here which is

what we're going to be using so the

implementation still might be a little

bit hazy to you right now that's okay no

worries we'll explain it as we go along

as we go along here so essentially we're

doing some weird storage stuff so we're

creating kind of this Gap in storage so

the storage has a ton of empty slots

then it has this implementation then it

has a ton more empty slots and then it

has some admin address the reason for

this is if we scroll down and we look at

this default function remember how the


default function works it's the fallback

function if somebody calls you know a

function that doesn't exist like they

call like hello world there's no hello

world on here it'll automatically kick

all the data to this default function in

our default function here we have it set

up where we're going to assert the

implementation isn't empty and then

we're going to send everything to that

implementation slot so we're however

it's going to do this thing is at call

is going to be set to true so let me

show you a little bit diagram of kind of

what this looks like in a normal raw

call it would kind of look like this

right somebody would call the ERC 720 e

the erc1

1967. it would hit the default function

the default function would look in its

storage it would see the implementation

and then it would kick all the data over

to some contract like counter one and

counter one would do it but with

delegate call what it's going to do

instead you can almost think of it as it

kind of going over to counter one saying

hey do you have this function that

they're asking for and then take it for


itself I know that that sounds kind of

bizarre but you can almost think of this

delegate call as a borrowing feature so

let's say counter has a function that

looks like this def set number new

number number equals new number if we

were to just do a regular call well this

would get called on our counter one

contract and counter one storage would

get changed but instead with delegate

call we're actually going to borrow this

function whoop and bring it over here

bring it to our self and now we're going

to almost run this function on our

contract itself but instead of saying

def set number new number well actually

excuse me it would be self. number

equals new number what our contract is

going to say okay what storage slot was

your self. number in okay that was

storage slot 0 so I'm just going to say

my storage slot Z is going to be the new

number and on the ERC 1967 contract the

number the storage slot zero would get

populated and nothing would happen to

counter one so I like to think of the

delegate call functionality as like a

function borrower like hey I'm going to

send all this data to you I'm going to

send all this data to this counter one


but all the results and everything that

happens I'm going to keep it you're not

going to keep any of it which is pretty

cool and we also have an upgrade to

function which allows us to upgrade and

we have a change admin function as well

this means though what's kind of scary

is if our counter one had like a defa

change admin we would never be able to

call it because it would trigger our

change admin function being called and

this is actually an issue when it comes

to using these type of proxy contracts

is you want to look out for function

selector collisions where the function

selectors are the same which we learned

a little bit about function selectors

before this setup that we're using here

that we're going to be teaching is some

type of it's kind of a version of what's

known as the transparent proxy pattern a

lot of the modern solidity contracts use

this thing called a u UPS proxy pattern

but we're going to be teaching the

transparent proxy pattern and as you get

more advanced in here you can decide

what type of proxies that you want to

use if you want to use any at all now I

will put a giant Aster here this code is


for education purposes only I do not

endorse this as like production grade

proxy I have not audited this I'm not

you know so just a a rule of thumb here

if you are going to use proxies and

Viper be sure to get them audited be

sure to get them security reviewed

because this is just my implementation

here anyways so the reason that we have

these gaps here is so that this

implementation could be at this one

specific location and so that we don't

do any storage collisions either because

if we set you know our implementation

address here and then we borrowed you

know set number change admin well we

would overwrite our storage slot zero

and that wouldn't be any good so I'm

going to walk you through exactly what

this looks like in just a

second and it's these proxies that allow

us to upgrade our contracts pretty

easily let's say we wanted to add some

brand new functionality but we didn't

want to change the contract address well

on our proxy contract we could just say

hey the new implementation is over here

now so all the delegate calls would go

to counter two the storage is contained

in our proxy contract so we're really


just upgrading the logic we're not

upgrading the storage slots at all just

the logic now this has a number of

drawbacks obviously when you implement

something like this you're adding a

centralization vector that kind of

defeats the purpose of what we're going

for in blockchain so

these different technology choices

obviously have tradeoffs now

additionally we're going to do another

thing here I want you to copy paste I

should have just had you get clone this

huh um I'm going to have you copy paste

counter one and counter two so in here

we're going to do new file counter

1V paste this in and SRC counter 2v

let's grab this come back over here

paste this in counter 2. VI

PES in as well so we have these two

contracts counter one and counter two

counter one has a version function which

returns one counter two has a version

function which returns two they both

have a storage variable called number

which is just a un 256 and they do some

slightly different things we're going to

make it so that we change the logic from

counter 1 to counter 2 without changing


the address without changing anything in

storage are you ready to see the power

you should be and I'm going to draw a

little bit a little diagram here to show

you what's going on on each step of our

script here so let's go ahead let's get

started let's do a deploy piy let's do a

def marason main marason main here and

we'll do a deploy and we'll just do a

defa deploy pass for now we want to

import those contracts so from SRC

import ERC

1967 we want to import counter 1 and

counter two like this so the first thing

we need to do to work with these proxies

is implement the What's called the

implementation or the logic contract

boom so that's what this is going to

look like we're going to deploy this

contract on chain this will exist on

chain that's it pretty much very similar

to what we have done 100 times

so we're going to say counter one deploy

we'll say impation equals counter 1.

deoy boom that's it this line we deploy

counter one that's it okay next we're

going to deploy this proxy contract okay

so we'll say proxy equals ec1 1967.

deploy and we'll say the

implementation. address is the starting


implementation and

boa.com mation slot is here it's

pointing to counter one and this has

this default function which whenever

default is called it's going to say hey

grab the logic from counter one and use

that instead so what I can do is I can

say I'll say proxy with ABI equals

counter 1. at proxy do address and what

this is going to do it's going to assign

counter one's ABI to the proxy and now I

can call proxy with ai. set number 77

now watch this if I do print proxy with

ai. number and I print

implementation. number what do you think

we're going to get proxy with ABI we

called set number on the proxy with ABI

which is at the proxy address

implementation we haven't called

anything on let's run MOX run deploy we

had a little warning here which um we

can do some clever stuff to ignore by

the way I'm going to do import

warnings I'm going to say

warnings um I'm do this warnings excuse

me with warnings. catch

warnings uh warnings. simple filter

ignore we're just going to ignore all

the warnings because we're getting a


warning it's saying hey this is not the

same address or the not the same um oops

simple

filter great so the proxy with ABI

printed 77 and the implementation

printed nothing it's because when we

called set number what our proxy

contract did it said hey uh logic

contract you got that set number number

function let me borrow that cool and it

ran that number over here on itself and

it put 77 in its own storage slot

nothing happened to the implementation

77 was set in the proxy contracts

because it said hey give me that set

number give me that set number function

okay you're assigning the new number to

whatever is in the zeroth storage slot

I'm going to do the same thing I'm going

to assign the number to the zero withth

storage slot as well

so now that we've seen the proxy in

action here we can do an upgrade let's

upgrade upgrade and to be even more

precise let's even do print proxy with

ai. verion and we'll also see if we run

this we'll get version one because

counter one version returns one counter

two version returns two and we'll see

that happen when we do this upgrade


so to do the upgrade all we're going to

do is we're going to have our

implementation point to a different

contract that's it so to do that so

we'll say

implementation 2 equals counter 2.

deploy like this and now we're going to

do the exact same thing and now we're

going to call proxy do upgrade to

implementation 2. address and remember

our proxy and our proxy with ABI are the

same contract right they're both the

same address the proxy with ABI just has

the counter ABI this one has the well

the erc1 1967 Avi which has this upgrade

2 function on it right so we're going to

call it upgrade 2 which is going to

change the implementation address to the

new implementation address so when we do

that we're essentially upgrading to

counter 2 right we're no longer pointing

to counter one one we've essentially

said goodbye counter one you you were

good to us but now you're worthless our

logic contract is Now counter to so now

that we've upgraded we can do the same

thing let's do this little with warnings

thing so we don't get those giant

warnings say with warnings. catch


warnings warnings. simple filter ignore

proxy with ABI let's do counter

2 proxy do address and now we can first

do let's first print this number again

print proxy with ai. number which will

still return 77 because our proxy

storage hasn't changed and when we call

number what we're saying to our smart

contract is what it's doing is it's

going to counter two it's saying ah what

what is number ah number is the zeroth

slot so I'm going to give you whatever

is in my zeroth slot which we have 77 in

it currently and then what I can do is

is I can do proxy with ai. decrement

decrement a function that previously

didn't exist we can print the number and

see the number decremented and then we

can also print proxy with ABI do version

so now let's run the whole thing MOX run

deploy and this was from counter one

then right here this is this print line

proxim with ai. number after we did the

upgrade it's still showing 77 cuz in our

storage slot we still have 77 We call

decrement we print the number we

decremented it to

76 because again counter two the

decrement function is just saying hey

whatever is in the zerith slot subtract


one from it and then proxy with ABI

diversion now that we've upgraded the

logic it is now

two so I know this was kind of a quick

session but that's it you now understand

proxies and how they work but before we

go we should of course have you do a

little workshop for our Workshop here we

have two workshops per normal spend at

most 25 minutes on all these prompts

without the Ada of AI if you're unable

to solve them in under 25 after 25

minutes stop take a break and then work

with AI order the discussions to help

you solve them and your workshops are

going to be TR to first off try to write

a contract that has a function selector

collision with the proxy H when what

does that mean well remember we learned

about function selectors right so in my

counter one the function selector for

set number I can figure it out by

running cast Sig set number U into

256 and this is the function selector so

when we call our proxy when we call set

number on our proxy the codebase goes

okay I'm looking for this function

selector no that's not right no that's

not right no that's not right right no


that's not right okay I'm going to go

with the default then cuz I can't find

the function selector what this means

though is you can have a function with

the same selector even though it's a

different function so for example if I

do cast Sig upgrade what is it upgrade

two upgrade two and I pass it an address

this is the function selector here and

when we call upgrade 2 we would call it

on the proxy here but but what could

happen is let me let's take this

function selector and I'll go look up a

function selector

database we can use this one punch this

in okay it looks like nobody else has

used this function selector but what

could happen is we could have a similar

function selector on our implementation

and this would be a collision so we

could do cast Sig

transfer uh address un

256 I'm pretty sure there's a well-known

known function collision with this

actually there's a ton of them so so all

of these all of these functions have the

same function signature work my dareful

owner un 256256 this weird thing here

this weird thing here this very bizarre

transfer many message bavage btes one


these all have the exact same function

selector so your first Workshop is kind

of hard well I guess I kind of gave you

a bit of the answer here um your first

Workshop is to try to write a contract

that has a function selector collision

with the proxy and then number two write

a contract where the storage variables

change order and look at how that

affects it so for example in our counter

one maybe we'll have a number public un6

and we'll have a my bull public Boolean

or bull excuse me and then in counter

two in counter two switch the order and

see what happens then do you get what

you expect why do you see the results

that you see so these are your two

workshops take some time Tinker around

play with this and I'll see you very

soon all right welcome back we've

learned a ton in this section and this

is the last section of the whole course

you should be incredibly proud of

yourself you're getting this far

let's do a final quick recap of all the

things we've learned in this section so

we learned about proxies and the

delegate call functionality of evm smart

contracts we learned that you can have a


contract whose fallback function will

always raw call or reach out to another

contract but kind of borrow its

functionality for itself you see kind of

a minimal diagram of what that looks

like here we reach out to a contract we

say hey um give me your logic I'm going

to use it on myself and in order for us

to upgrade if we ever want to upgrade

our contract then we could just point it

to a different logic contract or a

different implementation and that's how

we can have a single contract address a

single address always stay the same but

have its logic underneath change as we

said this obviously has some different

security principles if you have a

centralized owner who can just update

the logic willy-nilly well you

essentially have a centralized smart

contract we learned that there's a very

specific implementation slot that we

need to use if we want to follow the e19

67 guidelines we learned we made some

gaps in our smart contract in order to

reach that specific slot we learned how

to upgrade to a new implementation slot

we didn't work with change admin but

this one is is pretty self-explanatory

we were able to see with our little


deploy script here what deploying and

upgrading a contract with a proxy looks

like and with that being said you've

completed the advanced moccasin

curriculum here you should be so proud

of yourself now I'm going to scroll all

the way down to the bottom of this

because there's even more stuff after

this the most common question I get

asked after these courses is what do I

do now well there's always more to learn

so I have some resources on where to

learn more you but this is where in my

opinion you need to go and you need to

apply your knowledge so we had that

section how do I get hired well you just

finished the end of a curriculum now

it's time to go apply your knowledge you

definitely want to join the community

and if you haven't said hi to me on

Twitter you should 100% say hi to me on

Twitter I have been reached out to by

thousands of Developers ERS who now have

a full-time job working in web 3 who

have won competitive audits who have won

bug bounties who have been awarded

grants whove won hackathons and I know

you can do it as well but you got to

join the community but I highly


recommend you join the community because

it's one of the best places to network

meet like meet likeminded people and

just have a ton of fun with what you're

doing hackathons like I said are one of

the best places to get started there are

projects who will literally pay you

Awards to just build random stuff for

them so they're like paying you to learn

it's the biggest win-win for you on the

planet eth Global is one of my absolute

favorite on Earth additionally

competitive audits are one of the best

ways to a become a powerful

security-minded researcher and also if

you want to go down the security

research and also a better developer so

I highly recommend you check out code

Hawks you start jumping in and doing

competitive audits because these are one

of the best ways to really hone in your

skills additionally on codaw we have

this thing called first flights which

are these more beginner friendly audit

competitions where we've specifically

placed some bugs in here that you should

be able to find obviously if you're

looking at Cypher updraft we've got a

whole lot of curriculum on here and you

have finished in my opinion one of the


my favorite curriculums the python and

Viper but there are some more advanced

courses as well assembly in form of

verification smart contract devops smart

contract security and if you want to go

into like the defi path you could like

do a deep dive into maybe curves stable

swap which by the way is all in Viper

which you've just learned curve is a

multi-billion dollar protocol and the

codebase is used and forked by tons of

other projects so learning curve will

teach you more about other protocols

that have built their protocols based

off of curve and just in general

definitely be sure to subscribe to

anything cyphon and our team puts out we

go absolutely insane building everything

we could possibly imagine to try to make

the lives of developers and security

researchers better so be sure to follow

us on Twitter on LinkedIn wherever so

you can stay up to date with the latest

and

greatest

congratulations at this point you have

learned a ton about smart contract

development and you're ready to take the

next steps to go out into the web3


community and start building real

projects working with real protocols

that deliver real impact I'm so proud of

you for getting this far I'm so proud of

you for doing all the workshops for

listening to all the concepts for coding

all the projects all of that knowledge

is what's going to iron you out and what

has ironed you out to be the developer

you are today so the good news is you

have the fundamentals the skills to go

out out and be successful but in my mind

here's where the fun for you just starts

there's so much out there that hasn't

been done before and every problem and

everything that hasn't been done every

protocol that hasn't been built is an

opportunity for you to step into that

void and make something outstanding

there are so many more directions that

you can go you can go down into security

infrastructure building protocols

working with zero knowledge technology

fully homomorphic encryption and so many

more technologies that are going to make

this industry and this world a better

place I'm so glad I'm so glad that you

stepped with us the whole way you went

through this Viper and python course

with us so a huge thank you to you for


taking the steps to be a better person

and to gain this knowledge and now per

normal is a great time to take a break

go for a walk go to the gym or get some

ice cream cuz you absolutely deserve it

celebrate this online post this on

Twitter on Reddit text your mom text

your friends text whomever celebrate the

wins celebrate getting past here and I

wish you the best of luck because your

journey is really just starting thank

you so much for taking the steps to be

in web 3 and I'm so excited to see you

on your journey and to see you evolve

into the smart contract security

researcher or developer or whatever you

want to be evolve into that Beast that

we have hopefully helped and played a

small part in Awakening thank you for

getting froggy and we'll see you next

time

You might also like