"Solana Introduction": Official Tutorial Lesson 2#
- Complete the code with the lab.
- Complete all challenges.
- Add instructions to handle invalid wallet addresses.
- Modify the script to connect to mainNet and look up some famous Solana wallets. Try toly.sol, shaq.sol, or mccann.sol.
The second challenge is definitely not a difficult problem. It seems like something that can be found by changing a few parameters.
But I'm not familiar with it. I've spent a lot of time reading the documentation, and GPT's answers are not helpful. I don't know what I missed that prevented me from completing it.
I will update this later, let's continue.
It is easy to complete the code with the lab, there is nothing that can cause confusion. I won't provide detailed records.
Regarding Add instructions to handle invalid wallet addresses:
- The most direct solution, according to ChatGPT, internet searches, etc., is:
try {
const public_key = new PublicKey(address);
} catch (error) {
console.log('address is not valid.');
}
Of course, there are doubts. I just started learning, and I don't know what needs to be checked for an address to be considered valid.
- The second step is to ask ChatGPT how to determine if an address is valid.
I was given two options:
-
Use a library directly. The library will handle this. (web3.js, Solana CLI)
-
Since the address is derived from base58, the algorithm itself has some characteristics. For example, the length and the absence of certain characters.
But the basic conclusion is that the address can be validated based on the characteristics of base58.
- The third step is to perform a simple verification. Read the code of web3.js and Solana CLI to see how they validate addresses.
-
The
PublicKey
constructor in web3.js has a validation based on length. Then it uses the bn library to decode and check for any issues. -
The constructor in Solana CLI also only checks the length. It simply decodes using the base58-related library and if there are no errors, it is considered valid. They are directly sent.
The nesting is too deep (just a comment, it feels like Java haha).
So, the conclusions here are:
-
If you want a simple and quick way to validate if an address is valid, just use the constructor from web3.js, it will handle the validation for you.
-
If you want the code to clearly express the intention, instead of implementing it in a roundabout way, it is recommended to follow the algorithm rules, check the length, and try decoding once. If it passes, the address is considered valid, if it fails, the address is considered invalid and an error should be returned.