DEV Community

Raza
Raza

Posted on • Updated on

Solana for Javascript developers

Javascript. The water of programming languages: shapeless, formless. When you put it on the frontend, it becomes the frontend. When you put it on the backend, it becomes the backend. Take a sip, here's everything you need to know about developing on Solana with Javascript.

I'm going to assume you're a some-stack web developer: front, back, full, that can write Javascript.

🎉 Congratulations, I declare you a Solana developer. 🎉

No other skills necessary. Get to the end of this article and I'll even give you a certificate.

What even is Solana?

To a Javascript dev, Solana is just another backend. It's always on, highly optimized, doesn't go down, and it has virtually infinite reads, all for free. Oh, and you can write data to it at cheapish rates. What more can you ask for?

Proof of History, Tower BFT, Sealevel, yada yada. You don't need to understand how it all works. I don't. All I know is that it's a global computer that synchronizes state at the speed of light.

What stays the same?

A lot more than you think. Everything is still just an app of some sort - web app, mobile app, desktop app, Samsung smart fridge app. You'll build the same UIs with most of the same libraries using your favourite tools - VSCode, Vercel, Dreamweaver, Notepad.txt.

What changes?

The two big changes are authentication and data.

Authentication

Instead of JWTs and session tokens, you'll be interacting with “wallets”: middlemen applications between your code and the user that handle their credentials securely. If your app is a restaurant kitchen and customers are your users, wallet apps are the waiters, confirming orders and delivering food between you two.

Comic that displays cats as a chef, a waiter, and a user

Wallet <> app communication is pretty well documented and there’s tons of templates and examples out there. Just npm i the components and jam them into your app:

A screenshot of React components for connecting wallets

Here's wallet adapters and components for React, Svelte, and Angular:
React, Official - https://github.com/solana-labs/wallet-adapter
Svelte - https://github.com/svelte-on-solana/wallet-adapter
Angular - https://github.com/danmt/wallet-adapter-angular-sample

You can event take wallet connections one step further and implement "Sign in With Solana" - https://siws.web3auth.io/ - a complete alternate solution to traditional profiles.

The only authentication you do "on the backend" is verifying wallet signatures. Since most wallets are browser extensions, it's possible to "impersonate" another wallet by injecting JS. To ensure users are who they say they are, you ask them to sign a unique message, usually a timestamp or ID, and then check that the signature is valid for their address.

Once again - you don't need to fully understand how wallet signatures work when getting started, follow the docs and you'll be good to go.

The last type of authentication is custodial wallets - you make a wallet for the user and control it. This is frowned upon, not only because it's whack, but also because it defeats the whole purpose of being on the blockchain - giving users full control of their identities.

Data

Everything is stored on the big global computer (i.e. blockchain state). The majority of your data reads will be one of:

  1. What assets does this user have in their wallet/account?
  2. What data is stored in their program accounts?

All of this will be read directly from the blockchain, but don’t worry about how you’ll be doing that. There’s some very smart people out there taking all the raw data on the blockchain and putting it into a pretty API for you to consume. The Solana Foundation offers free JSON-RPC endpoints, so you can just slap the URL into your code and get started.

Reading data

The process of reading data is largely the same as a regular backend. You set up a connection to the backend (RPC endpoint), you define what you want to read and you get the data.

The solana-web3.js library handles all the complexity of formatting these requests, and it has a pretty comprehensive API, here's what a simple balance read looks like:

import { Connection, PublicKey, clusterApiUrl } from "@solana/web3.js";

// Connection to the endpoint
const connection = new Connection(clusterApiUrl("devnet"));
// Defining which address we're gonna read
const address = new PublicKey('CenYq6bDRB7p73EjsPEpiYN7uveyPUTdXkDkgUduboaN');
// Making the read call
const balance = await connection.getBalance(address);

console.log(`The balance of the account at ${address} is ${balance} lamports`); 
console.log(`âś… Finished!`)
Enter fullscreen mode Exit fullscreen mode

This is the simplest version of it. When reading from programs (also known as smart contracts), you have to take a few more steps and you need to know how the data you're reading is structured.

In a nutshell, you also have to:

  1. Define the schema of the data you're reading
  2. Deserialize it (think of this like converting formats)

There's a well-documented library called project-serum/borsh that's commonly used for deserialisation.

Rejoice, for you have been given the gift of literacy. Go forth and read.

Create, Update, Delete - All about blockchain interactions

"Writing" data to the network just means interacting with programs deployed on the network that change the state of accounts. You have two options of doing this:

  1. Use the existing libraries and their built in transaction "templates"
  2. Create a transaction from scratch on your own

#1 is easy for common transaction types and when interacting with system programs. You'll need to do #2 when interacting with custom programs.

Let's take a look at #1. The beauty of the solana-web3.js library is that it lets you create, update, and delete from a single Node.js file.

Create a new currency. Send a million people unique images. Gamble your net worth in a game of Plinko. Just hit node index.js and your financial future is in the hands of a computer.

Let's say you've decided to launch your own coin. To do that, you'll interact with the token program and create a "mint" account, that can mint all the tokens you want.

Here's what that looks like:

import { createMint } from '@solana/spl-token';
import { clusterApiUrl, Connection, Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';

// Create new keypairs that you need 

// Address paying the fees for this tx
const payer = Keypair.generate();
// Address allowed to mint tokens
const mintAuthority = Keypair.generate();
// Address allowed to freeze tokens
const freezeAuthority = Keypair.generate();

// Connect to the network
const connection = new Connection(
  clusterApiUrl('devnet'),
  'confirmed'
);

// Call the built-in createMint function
const mint = await createMint(
  connection,
  payer, 
  mintAuthority.publicKey, 
  freezeAuthority.publicKey,
  9 // The number of decimals of the token
);

// Log the address of the mint account
console.log(mint.toBase58());
Enter fullscreen mode Exit fullscreen mode

This script sets up a connection, creates the necessary keys, adn then sends a transaction to create a mint account (which is then used to mint tokens).

Again, you'll be doing this via wallets most often, not Node scripts. The user will come to your website, connect their wallet, click a series of buttons, and you'll send their wallet a transaction. The flow will be the same as above, but you'll just use their wallet that's passed in through the DOM instead of creating new keys.

These are the two most used libraries for creating, minting, and transferring tokens and NFTs:
https://github.com/metaplex-foundation/js
https://spl.solana.com/token

Craft, for you have been given the gift of creation.

Here's a super handy collection of examples on how to do common interactions:
https://github.com/solana-developers/web3-examples

Where to from here?

You can now create million dollar apps on Solana using nothing but Javascript. Start by getting your hands dirty with an idea that feels fun or by modifying somethign from a tutorial (plently of them on SolDev).

Here's your certificate!
Solana for JS Devs cert

Now go and build! Here's some ideas - https://build.superteam.fun/ideas

Top comments (0)