Building Full Stack dapps with React, Solana, Anchor, and Phantom wallet.
In The Complete Guide to Full Stack Ethereum Development I did...
For further actions, you may consider blocking this person and/or reporting abuse
Really nice read,
Just one tiny thing, when using Anchor it's recommended to use useAnchorWallet hook instead of useWallet. Some wallets don't support signing txs, if you provide such a wallet to the Provider constructor you'll get runtime errors.
I guess you're aware of that, just in case somebody has issues.
Hi, Daniel.
If I use useAnchorWallet instead of useWallet, can I get AnchorError via any solana wallets?
When I have called rpc api from solana program on Frontend, I need to get AnchorError in try-catch cause.
But I can see AnchorError on browser console(via solfare wallet) but I cannot catch the error. Any thoughts?
Thanks! Have a nice day~
Great post!
One thing though in the 1st test, you will need to declare the variable "_baseAccount" before you can assign it.
just add "let _baseAccount" in the describe test block.
Also I had to turn off the solana-test-validator for the tests to pass for some reason. Just thought I'd post just incase anyone ran into a similar issue!
I believe this happens because Anchor tests spin up a test validator instance. I know somewhere in the Anchor tutorial docs it's explained. Just make sure to turn off the test validator when running the test suite and you should be ready to go.
man, saved my life!
You man made my day! Thanks a lot, I was trying to figure out why the tests are getting errors and errors... Adding this line of code and also stopping the solana-test-validator made my test work! Thanks!
You could also go for
anchor test --skip-local-validator
Thankyou, this had me fcked for ages
thx for posting appreciate it ran into the same issues XD
If you end up with
Error, its probably because of create-react-app using "react-scripts": "5.0.0", in order to fix - downgrade to "react-scripts": "^4.0.3" or do manual webpack hacking
source: giters.com/solana-labs/wallet-adap...
and github.com/reduxjs/redux/issues/4174
This Alchemy tutorial is a really good guide to the manual webpack hacking: alchemy.com/blog/how-to-polyfill-n...
You only need these overrides:
Saved
I changed "react-scripts": "5.0.0" into "react-scripts": "4.0.3" and I got the following error at Building the React app when I run npm start.
Anyone could help me?
I followed the dowgrade instruction for all dependencies, but still got the following error:
Failed to compile.
./src/App.js
Attempted import error: 'PhantomWalletAdapter' is not exported from '@solana/wallet-adapter-wallets'.
Could someone help with this? Thanks!
@walkre I am having the same error, did you solve this?
Sadly, no.
with these dependencies it worked for me
...
"@solana/wallet-adapter-base": "^0.7.1",
"@solana/wallet-adapter-react": "^0.13.1",
"@solana/wallet-adapter-react-ui": "^0.6.1",
"@solana/wallet-adapter-wallets": "^0.11.3",
"@solana/web3.js": "^1.31.0",
...
"react-scripts": "4.0.3",
That worked for me too.
Thank you very much!!!
Cheers mate! Made my day.
This is really nice for developers like me who are new to blockchain apps development.
It's a very informative tutorial!
But I'm currently having trouble at the first Hello World build.
When everything is set and I run npm start inside the mysolanaapp/app folder, I started getting lots of error in regards to the @solana/wallet-adapter-react @solana/wallet-adapter-react-ui @solana/wallet-adapter-wallets @solana/wallet-adapter-base
Example of one error is:
ERROR in ./src/App.js 20:0-16
export 'getPhantomWallet' (imported as 'getPhantomWallet') was not found in '@solana/wallet-adapter-wallets' (module has no exports)
I solved this by running npm install inside the mysolanaapp\app before running npm start. Thank you so much!!
Awesome tutorial!
Still having the same issue though as described by @khrysaoar.
The npm install did not get the job done for me.
Hints anyone?
Thank you very much!
Resolved as mentioned by @hypeman.
Changed "react-scripts": "5.0.0" to "react-scripts": "4.0.3"
thank you it helped! And then I faced the next error with
BitKeepWalletAdapter
which could not be imported. The solution was to downgrade the following dependencies:it feels like Solana tooling is breaking dependencies on a weekly basis :-(
@dabit3 Hi, I hope you can help me or someone. Thank you so much!
One of the most useful Solana related tutorials. Thank you!
I have couple of questions though:
Have you managed to solve the AccountNotProgramOwned error? I seem to stuck on that error as well.
local storage.
sounds like a terrible idea for anything beyond a demo. What if the user clears his cookies or use another browser, then he loses his account data and starts from new? I could imagine that a base account could be generated from the public key of the provider/user to have something deterministic which can be safely retrieved and reused
EDIT: the method
PublicKey.createWithSeed
based on the user address, the program ID and a deterministic storage key that can be hardcoded in the front end app, is actually the solution to thisI agree, just for demo purpose. Thanks for sharing the right way.
Very clear tutorial, thanks!
Need some help.
I've follow 'Building Hello World' part and deployed program to localhost cluster.
After frontend calling program.rpc.create method and Phantom wallet approving I recieve
Transaction simulation failed: Error processing Instruction 0: custom program error: 0xa7
Account have enought balance, any suggestions?
I am also getting this issue. I updated the
lib.rs
andAnchor.toml
files withprogramID
.Here are the steps I've done.
And this returned the
programID
in the form of public key.Replaced the program id in
lib.rs
andAnchor.toml
I already checked the programID I am using in the app, and it matches to above one.
But I am still getting this issue when I am trying to call the
initialize()
function.I am really not sure why this happens and it's bothering me for days. Please help me if you have any idea.
Did you fund the wallet?
Hey, same problem here. did you solve this?
I've carefully checked everything step-by-step and it works. I think my mistake was in
cause of different app name
Great Tutorial, thanks for posting ... Having a little trouble in a particular spot though.
Not sure why but I'm getting this error whenever I type 'anchor test' or 'anchor deploy' . 👇
'Error: Not a directory (os error 20)'
Does anyone know what this means ?
I think that you need to install rust. I did that and then it works!. Use the next command in the terminal to do it:
curl --proto '=https' --tlsv1.2 -sSf sh.rustup.rs | sh
source $HOME/.cargo/env
rustup component add rustfmt
Hey, did you solve it I'm encountering the same problem
I keep on getting this for the hello world app. I'm a bit stuck tbh.
1) mysolanaapp
Creates a counter):
Error: 101: Fallback functions are not supported
at Function.parse (node_modules/@project-serum/anchor/dist/cjs/error.js:40:20)
at Object.rpc as create
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Context. (tests/mysolanaapp.js:13:5)
hi, CAPITAL letters are not supported for function name in your rust on-chain program.
I get the same error when I use some.
For me it was a combination of underscore and number, function name
exchange1
is valid butexchange_1
is givingFallback functions are not supported
errornvm! i tried turning off the test validator and it succeeded :)
This is because anchor test runs the local ledger as well right? Just ran into this issue lol.
Just the guide I was looking for!
For anyone coming to this in 2022 with
anchor-cli 0.22.1
, you want to replaceProgramResult
with updatedResult<()>
docs.rs/anchor-lang/latest/anchor_...
rather than
docs.rs/anchor-lang/0.18.0/anchor_...
Also, for others who might have a run in with this error message
Error: failed to send transaction: Transaction simulation failed: Attempt to load a program that does not exist
while running the tests. Check out this github.com/project-serum/anchor/is...You might want to turn off your
solana-test-validator
process, delete yournode_modules
and do a freshyarn install
, and finally try theanchor test
. The issue seems to be when the name of a mod is changed the tests fails, which made sense in my case because I was going with a different name for my project (anchor_crud instead of mysolanaapp).In case anyone else was having a problem getting all the base tools set up on Ubuntu, I threw together a shell script to install everything so you can jump straight to writing code!
gist.github.com/Quinncuatro/2ef56e...
why I cant see anchor installation guide?
anchor-lang.com/docs/installation
I followed this guide but I got error.
error: failed to run custom build command for
ring v0.16.20
Caused by:
process didn't exit successfully:
C:\Users\Baymax\AppData\Local\Temp\cargo-installgjndxS\release\build\ring-bfe791dd4e257bbd\build-script-build
(exit code: 101)--- stdout
OPT_LEVEL = Some("3")
TARGET = Some("x86_64-pc-windows-msvc")
HOST = Some("x86_64-pc-windows-msvc")
CC_x86_64-pc-windows-msvc = None
CC_x86_64_pc_windows_msvc = None
HOST_CC = None
CC = None
CFLAGS_x86_64-pc-windows-msvc = None
CFLAGS_x86_64_pc_windows_msvc = None
HOST_CFLAGS = None
CFLAGS = None
CRATE_CC_NO_DEFAULTS = None
CARGO_CFG_TARGET_FEATURE = Some("fxsr,sse,sse2")
DEBUG = Some("false")
aes_nohw.c
thank you for the guide! just what I'm looking for.
additional info, if anyone is using WSL, to run the test-ledger command succesfully, make sure you're in ~ directory instead of the default mount directory, e.g /mnt/c/Users...
Hello all,
I go to the point of running the anchor test and encountered errors, can someone help me out. Thanks
Replace it with "Result<()>"
Thanks Kimchi-shi, now am encountering the following errors.
Great tutorial. Got me started from scratch.
On the first test however I am receiving the following error. Any thoughts?
Failed to run test: mocha -t 1000000 tests/: No such file or directory (os error 2)
I ran into this as well, and in my case the problem was that
anchor test
expects mocha to be installed globally (npm i -g mocha
or equivalent), which I forgot to do.Never mind. It appears to have been an ID10T issue.
Just for future adventurers,
Was the problem that you hadn't changed directory into example1 or example2?
I just ran into the same problem and found this post while trying to solve it.
My problem was that I had the npm anchor package installed globally (which I did before I realized that it doesn't work on the M1 mac currently). Uninstalling it fixed the issue. (of course you also need to build anchor for it to work properly on the M1)
I have a issue when solana app is created with anchor as following:
anchor --version
Only x86_64 / Linux distributed in NPM package right now.
Trying globally installed anchor.
Failed to get version of global binary: Error: spawnSync anchor ENOENT
Yes, looks like you need to install anchor using Cargo:
Should one take issue to the first two lines in the output from this comment? Does it indicate the NODE_PATH variable is not set properly @dabit3 ?
Fantastic to have a working example Solana program to refer to thank you!
Just one issue I ran into deploying my program- the npm module with clusterApiUrl seems to be named @solana/web3.js and leaving off the .js didn't work for me.
Hey, thanks Eli, just updated to fix this!! Thank you for the heads up.
Hey there, thanks for your guide
I seem to be having an issue running the tests from the hello world project. Whenever I run anchor test I get the following error:
Transaction simulation failed: Attempt to load a program that does not exist
anchor.workspace is an empty object when running the test.
Hoping you can help me solve this as I cannot find anything about this anywhere
This fixed the bug for me
How do you check the programID on the CLI?
Hello.
In my experience, you should deploy program before testing. Please run "anchor deploy" before "anchor test".
When deploying, you should set program id. I hope my experience help you. Happy coding!
Does anybody know if it is possible to sign an Anchor transaction with a Phantom wallet?
the example signs using the baseAccount keypair
but when using Phantom, we don't have the keypair, we sign the transactions...
Any thoughts?
Thank you for great post.
When I set the network to devnet,
const network = clusterApiUrl('devnet');
I got the error;
Transaction simulation failed: This account may not be used to pay transaction fees.
Could anyone help?
Even i was facing the same issue, but I hardcoded the devnet url.
hardcoding the devnet solved the issue?
yes.it got resolved. But this tutorial is very helpful.
Thanks for the Nader
Can i use go instead rust?
I don't think so. Solana programs compile to BPF bytecode which, last I checked, Go doesn't compile to. Other languages you could use are C and C++.
I've really fall in love with rust
haha, in just 4 days :)
At the end of part 1, the app.js generates the following error for me:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
Not sure what is the issue here...
if I do npm ls react:
futureoffrance@ /mnt/c/Users/unkn0wn/solana/futureoffrance
├─┬ @solana/wallet-adapter-react-ui@0.6.1
│ ├─┬ react-dom@17.0.2
│ │ └── react@17.0.2 deduped
│ └── react@17.0.2
└─┬ @solana/wallet-adapter-react@0.13.1
└── react@17.0.2 deduped
So I see I have react 2 times, but isn't that normal? It's from different modules. I couldn't remove just one there I think...
Any help appreciated
Thank you
you're probaby using
useWallet
oruseState
outside of a functional component. Make sure they are insideLearning anchor and getting it going just by following patterns. I don't fully understand what's going on underneath, though. For example, what is 'info when creating structs? In this line:
pub struct Create<'info>
I'm assuming 'info is pointing to some Anchor struct definition - but unsure which because it appears pretty much everywhere regardless of what's being created. Or here:
pub base_account: Account<'info, BaseAccount>
Same question - and are we overloading with the fields from BaseAccount as well? Trying to learn rust & anchor at the same time, so not sure if this is an anchor question or rust question.
To answer my own question, 'info is a rust parameter for managing lifetime of references. The single quote is the operator and "info" is just a variable name (could be anything). All references tagged with 'info must be active until all are complete. More here: blog.logrocket.com/understanding-l...
hi nader, I just wanted to say thank you for your work as it was a great source of inspiration for me.
I ve made my best to test solana :
dev.to/fred227/thewheel-a-first-ex...
Of course your great article is mentioned in my article.
thanks a lot.
frédéric
It's very helpful.
I hope you will write a guide about NFT in the future.
This is exactly what I am looking for right now :D
I'm gonna write one if you guys want
Typo:
it("Creates a counter)", async () => {
should be:
it("Creates a counter", async () => {
I am running into
TypeError: Cannot read property 'env' of undefined
problem, before running command "anchor deploy". Anyone had the same problem?
in
tests/mysolanaapp.js
I changed:// const provider = new anchor.AnchorProvider();
const provider = new anchor.getProvider();
It's working. thanks for help
Helped
Saved me, Thanks!
Hi Everyone,
I have a doubt is there any chance to create a solana api for invoking this api into frontend application which is built on reactjs. Can any one help me, how to make this solana api .
It just popped up inside Chrome's Feed in my phone and I've been enjoying to read this a lot.
Thank you so much for taking the time to write this. Rust is a big challenge to learn, and Solana docs aren't as clear as one may like. There's lot of back and forth reading as the solana 101 article you've linked.
I wanted to ask for anyone who can answer me, from the following paragraph:
"validators use Not Bittorrent to fetch blocks and dont need to wait for all the pieces to presume correctness. they also claim to offload data to Not Filecoin so validators can run light clients but someone in their discord told me they never implemented that so idk"
What does the author mean by "Not BitTorrent" and "Not Filecoin". I know both, but I don't get to which protocol or service he's referring to. Google hasn't helped, either.
Is it possible for base account not to be generated each time? I wanted to use key/pair that I used for deploying the contract but it failed. What is the right way to do it if I want to persist data for the users?
I think there is a link in the article to make it happen but here is a possible solution.
In the src directory just make a file called createKeyPair.js and add this code:
// Shoutout to Nader Dabit for helping w/ this!
// twitter.com/dabit3
const fs = require('fs')
const anchor = require("@project-serum/anchor")
const account = anchor.web3.Keypair.generate()
fs.writeFileSync('./keypair.json', JSON.stringify(account))
Then inside your app run:
node createKeyPair.js
which should create a keypair.json (which is what holds the keypair for persistence)
Then in the App.js import the json file
import kp from './keypair.json'
and then whereever in your App.js you are calling:
let baseAccount = Keypair.generate();
Just replace with the following:
const arr = Object.values(kp._keypair.secretKey)
const secret = new Uint8Array(arr)
const baseAccount = web3.Keypair.fromSecretKey(secret)
That should be it. now it should be persistent on loading for anyone connected to your app.
I am at the react stage. However I have some issues when I click on the create counter function. This is the error I get: index.js:1 Transaction simulation failed: Attempt to load a program that does not exist
Hello.
In my experience, you should deploy program before testing. Please run "anchor deploy" before "anchor test".
When deploying, you should set program id. I hope my experience help you. Happy coding!
Hello!
I'm interested if there is a common approach of combinig Redux (or other state managers) and Solana integration in React applications?
Why most cases of React-Solana integration are using Context API with hooks?
What are the best practices and why?
Encountered this error showing that ProgramResult is not found in the scope.
Please how do I solve it?
'solana-test-validator' was working fine a couple of weeks ago.
I changed nothing.
Now I get 'Aborted (core dump)'
I'm on Ubuntu latest in a Virtual Box VM running on Windows 11 on a very new 8 Core AMD Razer Blade 14.
Why? How to fix?
I followed the dowgrade instruction for all dependencies, but still got the following error. Could someone help with it? Thanks!
Failed to compile.
./src/App.js
Attempted import error: 'PhantomWalletAdapter' is not exported from '@solana/wallet-adapter-wallets'.
Your article is very detailed, and it is of great help to me, thank you very much.
Great article!
Is there any way to reconnect to phantom wallet after page refresh using react.js?
create-react-app
now comes with React 18.x. The versions inpackage.json
have to be downgraded to 17.x, which is required by the wallet node packages.What a great post, thank you for putting it together!
Very Good!
Error: Your configured rpc port: 8899 is already in use
Thank you so much for this. If you don't mind, can you please write a tutorial for full stack avalanche development?
Is there any way to reconnect to wallet after page refresh? I've seen it on Metaplex example, but can't reproduce it on my react app. Help pls!
It does reconnect if you setup the
autoConnect
parameter like so:Thanks for sharing
Appreciate for your guide.
I have learned something many from this guide.
I will follow and subscribe.
Looking forward to your more guides.
Thanks!, Holmes
dev-to-uploads.s3.amazonaws.com/up...
Hi can u help me out? I'm getting this errro
Save my life!, thank yoy for sharing.
Anyone come across this issue when running npm start?
Failed to compile.
./src/App.js
Module not found: Can't resolve '@solana/wallet-adapter/react-ui/styles.css' in '/Users/
Can you help me out?
dev-to-uploads.s3.amazonaws.com/up...
First of all. Thank you for making me interesting about blockchain and web3. Will you have plan to make this tutorial on youtube? I'd love to watch it.
I encountered an error showing that "ProgramResult" is not found in the scope.
Please How do I solve it?
It is very wonderful course.
I am grateful to you.
If someone wants to read the reviews of solana in turkish
tr.binbits.com/sol-coin-yorum-sola...
can you also write an article on how to do custom things like whitelisting, dynamic transfer fee, anti snipe etc
Issue with provider import with last Anchor versions. Here is a fix :
medium.com/illumination/export-pro...
Great post!
But instead of the String, how can i use another struct?
for example a Vec of Foo
run anchor build error message:
help me:
hi, i get an error when i try Hello World, Any idea what i doing wrong ?
"Transaction simulation failed: This account may not be used to pay transaction fees"
Hello.
In my experience, you should deploy program before testing. Please run "anchor deploy" before "anchor test".
When deploying, you should set program id. I hope my experience help you. Happy coding!
Fantastic Tutorial! Shows everything needed to get started, from on-chain programs to browser interface. I got both parts working. Many thanks!!
Relate to phantomwallet, I think problem in lib wallet-adapter-wallets, so I change to use in wallet-adapter-phantom, it's ok, also I don't need to change "react-scripts": "5.0.0" to 4.0.3
//import { PhantomWalletAdapter } from '@solana/wallet-adapter-wallets';
import { PhantomWalletAdapter } from '@solana/wallet-adapter-phantom';
anchor init mysolanaapp --javascript
Error: yarn install failed: program not found
how to resolve this
Anchor installation link is broken. Use this one: gist.github.com/WrRaThY/1df3030ea7...
Just figured out project-serum repo moved/redirects to coral-xyz. So installation guide is here:
coral-xyz.github.io/anchor/
Awesome , You did it well.