Solana Smart Contract Tutorial: Using the Anchor Framework
By Josh's DevBox
Summary
## Key takeaways - **Anchor Handles Serialization/Deserialization**: Anchor handles the serialization and deserialization of instruction and account data so you can focus on writing smart contracts instead of byte packing. [00:21], [00:43] - **Anchor Performs Security Checks**: Anchor handles basic security checks like verifying the user ID is valid and ensuring accounts are owned by the Solana program. [00:54], [07:41] - **Program Module Defines Instructions**: The program attribute defines the Solana smart contract and each function inside the module is an individual instruction. [04:00], [04:23] - **Accounts Structs with #[account(init)]**: Define one struct per instruction deriving Account, use #[account(init)] to create accounts specifying payer, signer, and space like 8+8 for discriminator plus u64 data. [05:42], [07:09] - **IDL Enables Frontend Reuse**: Anchor build creates an IDL JSON file representing accounts and instructions, allowing frontend code to interact without recreating data types. [24:17], [27:43] - **Anchor vs Native: No Byte Parsing**: Native Solana requires manual serialization, instruction parsing, and ownership checks in one massive function; Anchor abstracts this into clean per-instruction functions. [42:39], [43:46]
Topics Covered
- Anchor Automates Serialization
- Define Instructions as Functions
- Init Controls Account Creation
- IDL Eliminates Frontend Duplication
- Anchor Cuts Code 90%
Full Transcript
hi everybody in this video we're going to learn how to use the anchor framework to speed up writing your solana smart contracts my name is josh and this channel's mission is to accelerate the real transition of blockchain technology
cheesy introduction aside let's talk about the anchor framework so what is the anchor framework anchor is a framework for quickly building secure solana programs specifically what it
handles is it handles the serialization and deserialization of instruction and account data if you've seen some of my past videos you'll know what we're talking about but for those first time
viewers solano works by having specific custom data both on the network on the or the on chain code and the client code or the off chain code and for the data to talk to each other
you need to be able to serialize it and deserialize it as you send the data across the network so that's one thing and the second things anchor handles for you is handles basic security checks and we'll go into
more into this later but one thing we should always do when handling smart contract is to make sure that the transaction we're doing actually is a legitimate transaction and
not some malicious party and anchor helps take care of some of that for you and that was always big thanks to our sponsor myself because no one else will sponsor me um on a serious note i try to
make these videos as independent as they can but they do reference some of the videos i made in the past uh check out my playlist in the description below to get the full details of everything
and that aside as always disclaimer is not development advice if you write code that gets you sued it is not my problem it is yours now let's get started
so setting up is pretty straightforward um we're essentially just going to go over the anchor minimal example with some of our own little plot twist to match the implementation of our
previous videos um but i included the link to the setup instructions i'll also add in the description below i assume we're all we can all handle uh installing software at
this point but the four things we need to install is rust solana yarn and anchor yarn if you've been following along my previous videos the only big change you need to install
is you need to install anchor with mpm yarn will be relevant in actually building the project it seems like every project in solana uses yarn and of course we'll be using the anchor example
project that's provided by projects theorem and i also include a description to the github project but we just run the command git clone to get the project
so before we get started there are some anchor commands that i think would be really neat to talk about just as a fyi we're not going to use the first command which is anchor init this would essentially create a new anchor
project we're not going to be doing that we're just going to be using an existing project but this the command would essentially just create a new project for you as you might suspect and which would include everything you need to run
a hello world program essentially including tests which is always nice we have the anchor build command which essentially just builds and compile all of your code that
you've written in then there's angular deploy which according to documentation builds and deploy your code to the salon network which in our instance right now would be localhost since when i could be actually
deploying anything we have anchor test which runs our unit tests that we have written it also builds and deploy and of course there's a lot of other commands so if you want to see them all
just type anchor h or you can also visit the documentation in the link i've added here now so now we know a bit more about how to use the anchor commands let's actually talk about how to write an
anchor code and so this will actually be the code that we'll be going over the basic one example and you see we have this massive amount of code oh it's probably not that big
like 40 lines but it's confusing there's a lot of attributes and things that we don't understand so let's break it down one by one oh so breaking it down so let's first talk about the program module which is the mod basic one that you see right
here so on the very top you see this program annotation this program attribute and essentially it's what anchor uses to define what a solana smart contract or
program is and it just handles some of the background tasks to make these easier for us so now we have the annotation and each of the function inside of the module is essentially a instruction for those new
to this video instructions essentially are just individual transactions that you can make to the contract to do something with your account and for those who don't know what accounts are accounts are essentially
just state data that is stored on the solana network but in previous videos you see that we essentially just had one massive helper function and then we extracted the data that we got from a
network and then handle each instructions independently what's nice about anchor is that we just define each function per instruction that we have so let's talk about what we get actually
in the data the first parameter we get is the contacts and essentially all contacts is is it's a container that holds the account data that we defined um if we go back quickly we'll go over
to this but you see that there's this initialize parameter that we passed in that's defined down here and after the contacts we actually have a unlimited amount of variables that we can take in and these are just custom
instruction data that we send across the network i also include the documentation to the context for those who are curious and that's essentially what we need to know about each function so now that we know more about the
program module let's look a bit more into the account data types that we are passing in so let's let's so let's dive into our accounts we need to find one struct for
each of the instruction that we want to handle for our functions and each strut should derive a count and what this means is that the struct would
inherit the account traits or the counts trait and accounts would just include extra the implementation detail that anchor uses that we don't have to worry about
now diving into what data goes into the structs the intention for each of these struct is that we would include data that we need to use for each of our instruction and if the parameter we
include in our struct includes a account type i know there's a lot of accounts there's the accounts that we derive and then there's an actual account to the instructor but for each of these account
types that we include we need to add this attribute this account attribute which specifies the behavior that we must expect from account and if we actually dig into some of the parameters
that we include we have the init which is the first command and this essentially is to create the count something we have not seen in the previous video is actually the process of creating account when writing native solana code it
usually just creates the account for us and we don't need to do anything in anchor we can actually take control of that and do some customization ourselves we want to so that's what this initialized struct is in the initialize
function that we have implemented that is implemented over here this is essentially just creating our account for the first time so when creating an account that's what the init is for to signify that this is
us creating this specific my account type other data that we need to include is who is the payer because we need to essentially pay rent is what it's called
to store our account on the solana network and we need to specify who the signer is or essentially the wallet and we dictate that the signer is the user which is this parameter down here which
is the the field user that is of type signer and essentially one of the nice things about anchor security is that anchor will automatically check for us that the
user id that we pass in is valid and some other checks and it's moving on from payer we also have space so one thing about working in salon rest is that everything has to be extremely space efficient we have to
allocate a certain number of bytes essentially to our code and in this case uh we allocate eight uh eight plus eight sixteen bytes and the reason we have eight plus eight
is the first eight we always have eight because that includes the hash of the account essentially and then the next aid is the size of the data that we're storing which is from
the my account as you can see right here and my account is defined down here my account includes only one thing which is a data type which is a u64
and a u64 is essentially a number that has 64 bits long and we know eight bits goes into one byte so this my account data struct is a
is of size eight bytes so that's how we define our a plus eight so that's how we define space another account type is mute which you can see us use right here on line 33 and what it
says is that we can modify the data stored on the account so that's what this account attribute is it's just a nice hook essentially you can think of that anchor uses to run code in the background for us that
we don't have to worry about which might add one nice thing is it actually verifies that all the accounts you use is actually owned by the solana program which is important for security purposes
so moving along we see that there's this apostrophe info variable we don't really know what that is but essentially the apostrophe just indicates that the very that the variable we're using is a lifetime variable
you can look more into that if you're curious when i can dig into that and from my understanding don't call me on this one this info actually represents a account info class and i'm just going to open it up
because it'll be real important to see well wrong link but an account info is inner instruct that contains all these types the most important one
is going to be data because this is where we will be storing our custom data but we can see a lot of helpful information like this is our who the the pub key of the owner of this
account the key of the specific account and so on and so forth so that's what it is going back to our presentation all right so now we know what an account info is let's actually talk about the
account that i accidentally opened up earlier so an account is another struct that was created by anchor to help essentially wrap the data that
the user is passing into it but so let's take a quick look into what account is and a account is like i mentioned earlier a wrapper around the account info which includes information about
your account like the owner the rent and so on so forth that verifies the program ownership and deserializing underlying data into the rest type and this is what we were talking about
anchor handles some of the processing work for you so for example if you look at the code so if you read this basic functionality uh i won't read the whole thing for you you can read it yourself i'll probably
actually should have increased this but if you read the code itself some of the things it checks is it checks if the account info owner which
if you look at the account info again it has this owner class or owner field it checks to see if the
the account info the owner is equivalent to the owner of the program and it does some other things like check if there is any rent left in the
account so that the so that everything is valid and if you can dig into it i'll include this in the description below so that's what account info is it's just a wrapper
and you can see that this account takes in two types or it's just it's a generic that takes into tive there's the account info which includes all of the basic information about the
account and it contains a my account struct which is essentially custom data if you look down here my account which also know we annotated with this account attribute
but this my account is a is essentially just custom data that you want to store on the salon network for your users accounts so in the basic example they just call
it a data if you watch the previous video we called it counter and that's essentially what we're going to use this for so and just for completing this we'll go
over some of the rest of our data we have this user field in our strut and that's a signer a signer is essentially just another data type to represent a wallet that is going
to pay for the creation account and then we're going to have the system program which is something else we include to create the program i wouldn't worry about the details too much i just copy and paste this this is
just setup work that we need to have for the initialize instruction that we every user has to start if you look at an actual instruction that we need to find such as update
that's actually much simpler we just include the account data that we want to interact with which is the exact copy of what we have up here notice that we don't need to have the init attribute anymore
because it already exists all we include is this mute attribute because we want to modify the data or update it specifically and to reiterate we don't use this my
account struct directly in our instruction it is just custom data that we're passing into these initialize and update which is the actual instruction that we're passing
into our code if you take a look right here we see we use initialize right here inside our initialize function and we use update insider update function and that's roughly everything you need
to know about creating a smart contract using the anchor framework so now that we have no right one let's actually go through a practical example so we're going to convert our existing basic one
project that we've cloned from the serum anger example and but don't worry i'll go through the whole example so you can follow along but we're going to
we're going to modify that example to match our previous video where we sent a where we wrote a salon smart contract that essentially had four or three instructions well we don't count
initialize but four instructions we're going to have a initialize which we're going to set our count or in this code it's going to be called data we're going to set our data to be zero we're going to send a increment
instruction which will increase our account by one we're going to have a decrement instruction which decrease the count by one and finally we're going to have a set instruction which will set our
account to be whatever value we pass it so let's get started the code so the first thing we need to do is we need to actually clone a project already done in my local library but let's just go through this together
so if we go back to my notes there's this get clone function uh you know don't trust me i'm just a random guy on the internet i recommend you um
going to the github repo itself and then getting the command from there but let's pull up my command prompt now go into our wsl instance and for
those who are first time watchers i have to ask you to go look in the past video to learn how you can set up wsl um wsl is just a windows linux operating syst subsystem that we connect
to you see the squiggly line so we can go to our route as you can see we have a lot of existing code i'm just going to and as you can see i recloned it over
here so let's go back to our cd video we've been using this directory for all of our videos so we're just going to do another git clone here and i'm just going to clone the whole anchor protocol and why did i
get that all right gecko and get cloned all right let's try that again we do get cloned all right so now we've cloned our repo we see that anchor exists
so you can see anchor and you look at the content you see that it's everything in the github repo so now that we have that let's open up our visual studio code
which i will pull up over here and we're going to connect to our project that we just created through vs code and once again uh look through the holo
program i believe i made that talks about how we would set up vs code to be able to connect to your wssl instance but essentially all you think all we need to do is just open folder
okay that's not going to be correct so we're going to so we're going to click on this button on the bottom left corner to open a ws a wsl instant using our remote wsl
extension that we downloaded close this now if you'll click open folder again there we go and we just typed the path to our repo that we created that's video and
anchor and now inside this project there's actually multiple examples that we could have gone through but but i'm just going to open the root directory so i click ok
and now if you see on the left corner in this column we have we are in the correct directory and if we open examples we see our
the example projects the ones we are here but curious about is basic one and we just go open this and we click on lib
and we see the example code let's also open up the test file because we're going to need that later now i'm going to use control b to close
that window for space here's our anchor code that we went over written rest of course so now let's actually dive into the details of the code i only pointed out the the definition of our function we've
never actually talked about what the code itself did um i mean i don't think it's too complex to understand but let's go through it for completeness so in our initialize function um
we're past that initialized struct that we defined down here um and the nice thing about and one thing you'll notice is that we actually never use the user or system program anchor
handles all the verification and everything for us one thing i will actually mention that's very powerful is that this code will only trigger if everything is successful if we have any
problem with serializing deserializing our data that is shown over here we will never actually run initialize or update for that matter if there is a security vulnerability
that we encounter like the account doesn't actually belong to the solana program we would also not execute this code anyways so we have this initialize and
the return type is a result we talked about this in previous videos but a result is a rust type that is essentially a enum that gives you an okay or an error i believe
think of it kind of as a promise if you're familiar with javascript you can either get a success or fail in this video we're not going to worry about any error cases so everything is return of an okay
but if you look in our code we have the contacts that was passed to us and essentially what line 10 does is with the contacts and if you open up the
link to documentation you'll see what fields includes it you can reference the accounts it says accounts but it's actually just that one account that we passed in so inside accounts we can talk to my account
which is another layer of introduction that contains the most important part the metadata that we have
that's stored in the my account strut so this is how we get the my account variable and important to note that we have this ampersand mute
because we want to update the value and in rest if you want to update a data structure we need to include this mute symbol and get a reference to it so
in initialize all we're doing is we're giving custom data and we'll don't worry we'll look at the client side to see how it's passed in but we get this custom data and we just set it to the data type
which as you see we defined right here it's just a integer of u64 and after that we just return a okay result because everything worked out great for those who came from my past videos
you'll kind of notice how simple this is there's no serialization or deserialization that's being done with the data remember how we had to create an array and then pack it with the
bytes to represent the data that was not fun but you see we don't do it here and that's because anchor does it all for us and so we don't have to do anything anyways so let's actually implement the
code that we've been talking about so we're gonna have four things remember it's we're going to have initialize set increment and decrement
so initialize we just want to set the data to be zero so we just set this to zero and we can just remove any of the custom data that we're sending update or we call it set at this actually you know what let's just keep
everything called update we know what it is increment we're not going to use update anymore we're going to call it increment now technically we could use it because we're not really changing anything
but i think it's best to always define a custom struct for each of our function in the case that we ever want to change anything in the future we don't want to break our existing code anyways so we create our increment in our decrement
instruction and we don't need to pass any custom data because we're just going to increment by one or decrement so let's equal one
minus minus equal one uh one interesting thing that we're and we'll point out that we're not going to catch is that this decrement can actually crash the code because if if we
go to a negative number because unsigned 64 is only positive numbers but we're not gonna worry about it all right so we define our increment and decrement function
now we need to actually define the instruction that goes with it and it's nothing complex essentially we just copy paste our update and we
just call it a new struct it's literally the exact same copy and paste and that's all we need to do to create our salon program and if if you watched any of the past video you'll know it was not
straightforward to get to this point so you can see the power of anger right now all right so let's go back to our slide to see what instructions we need to run
okay so how do we deploy our code here is the instructions technically uh so the first thing we need to do is we need to run the salon
keygen that creates a wallet essentially on our if on our local instance i technically don't think we need this because we in at least in our example we
actually never use a wallet we just kind of define custom wallet in our tests but you know if that's not the case if that doesn't work for you you probably have to run this command
anyways so we need to navigate to our basic one on our visual studio code it has a built-in terminal for those unaware we need to yarn install to install within our project
anchor build to build our project and then we need to run this solana address this command essentially to get the address of our smart contract this is very important because that's where our code is located at
and we need to include this address in our declare id macro that we've actually never talked about we kind of just passed over it and then we just build again with this new id
and then finally we run anchor deploy to deploy our sorry contract on our local network so let's do that i'm going to move this to the left so
if you go to view and terminal we'll open this terminal to our code and then we go to cd examples
tutorial basic one we do a yarn install to install our dependencies okay so now that we have that we can do
an anchor build and this builds our solana program it actually does something else that we'll look into later but it creates something called idl which is something that the front end uses to actually
communicate with us without having to define our front end code it's very handy because in our past video we saw that we had to manually recreate all of our data types
on the front end by using this idl file that we created we don't need to do anything at all so we just write one code on our salon program and it can be used everywhere
all right so it's built so now we have this new key pair right here that displays the address to our program if we actually look it up it's this array of numbers and we need to convert that
array into actual valid numbers and that's when we run the command that was mentioned the presentation salon address dot k dash k and you give it the address of the key
pair that was created which is in this instance this specific uh line of address all we need to do now is copy the code
or the address go back into our lib paste the value and do another solata build or anchor build all right now it's done
we have the program now we can do the anchor deploy which then would build and deploy our contract to the solana network and you see right here our program id is
the exact same thing we mentioned so essentially that's all we need to do to deploy our program onto the salon network now the question is how do we actually test it
one of the benefits and power of anchor is that it automatically provides a front-end interface that we can use if you've seen the past videos that we've made we had to recreate our
account basically in a javascript equivalent but now banker what anchor does is it takes this idl that we've created or angular creates we read it and then that will
allow us to interact with the same interface that we created on rest in javascript i'll probably move my head over here there we go take a look at this but if you look at
the code briefly all you do is you read the generated id file that rust provides we need to actually put this somewhere and then we convert that into a
json object and then from the helper libraries that anchor provide we also need to give it the program address and then with these two information we
can create use this anchor program uh helper function we give it the ido and we give it the address to our program and it will create the
a client essentially to talk to our smart contract with the expected variables and so with program we call it we can call something like program.rpc.initialize
program.rpc.initialize
initialize being the function that we implemented in the basic example in this specific example initialize actually didn't take in any specific parameters so nothing was included
for us that's not the case so we'll look into that later but that's roughly what needs to be done to talk to our smart contracts so relatively simple i i skipped some stuff such as obviously
creating the wallet or connecting to the correct network but this is roughly what needs to be done and before i move on let's actually look at the idl files that we created
so back on visual studio if we open the explorer let's see if the target folder shows up okay oh yeah actually here it is so you
see there's a target folder we go to idl we look at basic one json let's remove this and what this is essentially is this json object that represents the
accounts and then the instructions that we send across the network remember we have our initialize and update instruction and that's what we see here so in our instructions we have an array of objects
json objects there's two of them there's initial project four there's initialize there's update there's increment and then there's the decrement
and so if we look at this code initialize if we look at the accounts we see that there are the three types that we specified my account user and system program
if we look at update and this is the interesting part in our update if we call in our libs how we define over here we take in one type which is the my account
which you see right here and in this args we take in this data that's u64 if we look back in
our update function we have our update instruction that we defined and we also have the arguments which is our data u64 now as you imagine if we had more arguments that we took in they
would have appeared over here because this is a array of arguments in our increment and decrement case we don't have any arguments because we didn't use anything over here so that's what this id is and with the
front end anchor library we use does is it converts this idl into hover functions that we can call such as this initialize code right here
and it will make the request to the network and we don't have to do anything now moving on to running this code and testing is actually kind of painful we have to read the file we have to get the smart contract address and so on and so
forth so the smart guys in gaza anchor did a service to us by creating a concept called workspace and that's used to simplify the test one thing to know about workspace is that it only works locally with the anchor text test
command and it can't be used in any real code unfortunately and it's also important to note that there is this file called the anchor.tml
file and in there we need to find the network that our test is deployed to and the address to it we need to update that anchor.tmo tomo file with our program
anchor.tmo tomo file with our program address now actually look at how we use it it's pretty straightforward you really just call anchor workspace dot the name of your file your project and
that gives you the program and you just do program.rpc.initialize
do program.rpc.initialize
so very powerful stuff um if it ever changes you don't need to worry about it the workspace has the latest change so with that understanding out of the way let's actually start writing our test the oh anchor projects automatic come
with a test directory uh tests are written in javascript using the mocha testing framework if you don't know what that is i recommend just looking up it's not too difficult i'd say um it's just a
nice way of writing verbose tests and of course those examples we can follow so that's not hard just a reminder again we need to upgrade our anchored auto file with our new program address otherwise the test isn't
going to work and to run our tests we just run anchor test uh we i did some testing and it's like it seems like we have to manually do an
anchor deploy to build our rest code if we decide to make any changes there otherwise the test would still be stale according to the documentation angular tests should build deploy and run the
test but that wasn't the case for myself when i run it at the making of this video anyway it's not a big deal i will say though that if you were to update the test and you run an anchor test that change would happen automatically so you
don't need to do any building there that's good to know all right so back on to the test um we already have our code it's pretty straightforward we just want to test our for uh
code over here um our test file as you can see is in the same directory of basic one it's in this test directory we just open the basic 1s
and so let's take a quick peek of this code so this is a javascript file there are three libraries that we import acert which is just you know typical
assert library for handling testing we have our typical anchor framework provided by project serum this is what we've been working with
and of the anchor library we are also calling explicitly the system program that's stored in our web 3 module what's neat by the way in visual studio because you get f12 on this code
it will open up the program definitions and so you can actually look into the code and see what it does so so very helpful if you're curious on what things do anyways so to create a mocha test
essentially mocha tests are descr are defined by two things you have describe it's a description of your overall test for each of the described you implement
your it functions and it is actually the test that we run ourselves so each of these its are its uh is its own individual test there's only two in the existing one for a basic one so what we
want to do is we want to modify this to use our new code before i forget let's open up the anchor profile we see that we have the program.local.net so that
means this test is being random local net or localhost what we want to do is we want to change our program address to be the one that we set in our declare id
macro so we go back there copy and paste and save and of course we run in your test this is the command that gets ran this is all defined for us and we don't need to
worry about it okay so back to the test itself so you think of described as like a class and it is the functions
so we can declare some global fields so two global fields that were created is the provider so the provider essentially is the the network that we're connecting to the angular library provides a local host
implementation so we don't need to worry about it we just call it and it'll give us the provider we need and of course we need to set the provider so we use it for our test and that's done with this line of code
and so these are all global fields so it will be reused uh there are a couple bugs already in this existing test so we're gonna have to fix that first report compile before
we actually try running it but back into our code you can see that this is the exact same code that we saw earlier we create a program by using our workspace this
we need to create a fake account that we want to store on the network and that's what and luckily for us anchor has a helper library that does this it creates a key pair and we just call it my account
and now the interesting part so the program that we created from our workspace we can call the rpcs that we define to send our instructions over the first thing we always need to do is
we need to initialize our pc and so we call initialize and this is remember tied to this initialize function that we defined over here
and inside initialize we need to give it our arguments the data that we sent over in the original code we set some data but in this code we actually don't so we just get rid of this and we just
send in the next set of parameters which is the account data for our contacts specifically that's this initialize value and if we look at initialize we
take in three things my account user and system program and so that's what we're passing in over here so my account we just get the public key of our account
that we just made up a user which is the wallet that's going to pay for the creation of the account in this instance we use our provider that we define and it creates a fake wallet for
us to use and then their system program we just call the system program that is provided for us give it program id and you know don't even worry about it honestly
we need to provide a signers for our initial initialization and uh i want to worry about it too much we'll just you know copy and paste and just provide the your your accounts that
you create to be a designer this is the account that's to be created and that's basically all you really need to do to send a transaction across the network to your smart contract pretty straightforward honestly especially if
you come from my past videos where we talked about how we set this up so now that we've made our initialize code and we send the test and essentially if everything was correct we would
execute this code and we would set our data type to be zero and so we need to retrieve that account that we set and the workspace api we use provides that
type of information we just call program accounts my account and we call fetch we give it the key public key of the account that we're fetching and that'll give us the account
information yeah i want to worry too much about memorizing this this is mostly just copy and paste and so now we have the account data all
we need to do is just check if our cert values are correct and so we're calling account that data equals the value that we sent over which is actually not correct it's actually just zero
and just for a quick reference the account.data
account.data is actually referring to this my account type that we define and it's specific data so we're directly
calling this value and you might wonder what is this new anchor that bn and this anchor that be in is essentially just this is anchor's way of serializing and
deserializing data so what this all really does is i believe it creates a um an object of that represents a zero in the previous videos we manually
created a array of bytes that represented the value and this is just a helper function that does that so we could do this comparison i believe it'll work but another thing i'd like to do and because
all assert that okay does is tell you if this function is true or false we don't really know the values so what i like to do is i like to do a cert.equal
and we just compare account that data with the value that we expect which is zero it's very important to note that if we do a data.equal
data.equal if we just put a zero here it would actually fail because that is not the type that we expected we expected this binary format
so the comparison isn't exactly equal okay and so that's all that is and now for the final part this is not a good testing methodology you should not do this in real tests but you know for the
sake of time let's just do it this way but we then store this account that we created in a global field and then we're going to use it for the rest of our tests you can already
see the potential recipe for disaster if tests don't run synchronously in order but potentially we can increment something and decrement and then maybe depending on the test order you might decrement and then increment and then
the expected value is different but anyways so this test itself will not pass because my account is it doesn't exist we didn't define it so to get this
test to even compile we just do let my account equals null and so we'll set it for the first time when we call our initial function and we'll set it at the end and then when we call our next test we will use
it all right great so that is basically how we write a test it's very straightforward and if we look at our update function it's pretty much the same thing you know
we get our accounts that from our goal field we store into a constant we get our workspace and then inside our workspace we call our update rpc which we defined and as
you recall update actually does take in a custom argument which is just a into 64 bytes or bits and we define that over here
it's actually very important that we have to use this anchor that bn file to generate it uh the parameters the update rpc expect is not actually an integer it
expects this uh format expect to anchor that bn object so we have to use it in this format and let's just set it to 100 we do the exact same and then we define
the accounts that we pass in and just like how we define inside our update we only define our my account so we do the exact same thing
to populate the my account field we just get the public key of our accounts and then we fetch it the same way we refreshed it earlier and then we just do a comparison
this uh the code like this would pass but you know if it fails you don't know why that's not very helpful because the test will just tell you that we expected true and we got false
so going back to what we're doing we can just do account.data is it equal to the value 100 and if it is then it passes but if it's not it'll actually at least tell you what
fields appeared and so you don't have to figure out what went wrong so now that we have our update let's implement our increment in our decrement so
first let's call it increment and this can be our decrement so i just copy and paste the update if the code is very straightforward it's pretty much the same thing instead of
calling our program rpc update we call the increment function we don't pass in anything because if you look back at our increment implementation we don't have any custom arguments we
just increase the count by one and so that's exactly what we do it takes in the same my account so we keep everything the same we fetch the data and we expect the value to be 101.
now decrement is the exact same thing we don't pass in anything and we expect that since we are at 101 now if we decrement it it will be back at 100.
so that's it that's how you write your test that's how you talk about the program now let's go back here and run your test on our terminal and you see that it fails wonderful
let's find out why okay okay i forgot to change the rpc we called to decrement okay now try one more time yeah we don't want to do an update we want to
decrement there we go okay so now all of our tests are passing and that's about as far as i want to go in this video but i know you're asking how do we actually use this in real life well unfortunately that's we're nearing
the end of this video in the next video i want to see how we can integrate with phantom wallet so actual real wallets and write code to talk to a network that we deploy locally but before then let's
look at our tldw back to our slide so this is probably the most important uh section of the whole video just to see the difference between solana and anchor and i just did a comparison between the old
code we wrote in our previous videos and compared it with what we just written today in anchor and see the difference and just move right away so on the left you see the solana code
uh solana we have this process instruction function that we created it takes in the program id the accounts and the instruction data and so to on a quick highlight you see
in the red lines we did a lot of serialization of data as you recall we had to take in the instruction the arguments that we get this will be the equivalent
of each of the contacts that we send this update increment and decrement and we had to essentially parse the data with rules that we defined ourselves so we can figure out what instruction we
are trying to implement it was this a increment instruction was it a decrement or was it a set or slash update and of course not even that we also had to parse our greetings account to get the
data that's in our account but so very painful very involved and all everything is in one super function now let's look at our anchor
implementation anchor is straightforward we have four functions each function is essentially the equivalent of us handling our instruction all the serialization and deserialization has
been handled for us that's just serialization and decision let's talk about the next part in this red line you see that we're actually doing a check to make sure that the account isn't even owned by the program
and so these are these simple checks that we have to think about every single time we write but in anchor that's all abstracted away from us the all this code is handled in the back end we don't need to do that
the sheer fact that if our code even gets executed on in anchor that implies that this constraint is true so that's on the unchain code let's look at
just the front end code or just defining our accounts actually and so on as you recall in our videos we had to create our account type we had to find it on rust which is what
you see in this picture and if we want to also use the variable on the front end in our javascript code we need to define the variable again in this java equivalent javascript
equivalent but not anchor in anchor we just define our account strut once and you know use it where applicable in our instructions which is this
initialize update increment decrement and then that and then that would be converted into an idl file that'll be read in our front end library that we saw earlier and we can just read it
directly there we don't need to implement the class a second time so you see that basically eliminates any possibility of errors because you're not writing it the second time
and so that's about it hopefully this video is relatively shorter in comparison to the past videos but i highly doubt it we'll find out but uh so if you found this video helpful i
greatly appreciate if you like and subscribe to my channel otherwise stay tuned the next video will be about using integrating our program to use
phantom phantom wallet to use real or you know fake salon that we give ourselves to interact with our program so until then i'll catch you all later
have a nice day
Loading video analysis...