🚀 Power of Solana Mobile Stack: A Technical Deep Dive

🚀 Power of Solana Mobile Stack: A Technical Deep Dive

Technical Guide For Building Mobile Apps on Solana

·

13 min read

✨ Introduction

Welcome to the world of Solana Mobile Stack (SMS), where the future of decentralized mobile applications meets the efficiency of the Solana network. This is your road map to start building with Flutter/React Native and integrate SMS to make your next dApp idea a reality.

🔑 Key SDK's of Solana Mobile Stack

🤔 Want to integrate and support different Solana wallets in your app?

Mobile Wallet Adapter(MWA) is just the SDK you want.

MWA is like a common language that allows mobile apps (aka dApps) to easily talk to different mobile wallets for Solana. This means developers only have to integrate MWA once in their dApp, and then it can work with any wallet that follows the MWA rules, like Phantom, backpack, Solfare, etc.

It saves developers from having to create specific code for each wallet, making things simpler and more efficient.

The image represents how MWA bridges the gap between dApps and Wallets.

Resource: https://github.com/solana-mobile/mobile-wallet

🤔 Want to integrate and support different Solana wallets in your app?

Seed Vault is a protective service for wallet apps on your phone. It uses the most secure parts of your device to safeguard keys and secrets.

Your important information stays in this secure space, and the Android interface ensures secure transactions without your secrets leaving this protected environment.

In short, Seed Vault keeps your wallet data safe in the most secure part of your phone.

Resource: https://github.com/solana-mobile/seed-vault-sdk

🤔 Looking for a special store just for dApps, to distribute your own?

The Solana dApp Store is a different way of distributing apps, especially those created within the Solana ecosystem.

It offers a channel for apps to connect directly with users, without being bound by the rules or revenue demands of other app stores.

The aim is to encourage the Solana community to actively contribute to managing the store's content.

Resource: https://github.com/solana-mobile/dapp-publishing

🤔 What if there was a web3 version of Razorpay or Stripe for mobile payments?

Say no more, Solana Pay has got you covered!

Solana Pay is a protocol designed separately from the Solana Mobile Stack, but it's a perfect match for mobile payments.

For developers wanting to add Solana Pay, they have created an example that shows how Wallet apps can use Android features to handle Solana Pay URLs from QR codes, NFC taps, messages, and web browsers, making it easy to launch Solana Pay requests.

The image represents how Solana Pay makes it easier to pay with dApps.

Resource: https://docs.solanapay.com/

✨ Getting Started :

In this section, I will be covering how to set up and develop a basic dApp with React Native and Flutter. You might think why not cover Android as well? The simple answer is that all the SDKs are natively made in Kotlin(Android) and you will find overwhelming examples of how to use them by just visiting their documentation and GitHub repos. Whereas in the cases of Flutter and React Native, choosing the right packages is more important than the code itself. But before all of it we will go through the core part of web3, wallet connection. yes, you heard it right.

📦 Prerequisites and Setup :

✔ A fundamental understanding of blockchain and Solana.

✔ Basic knowledge of either Flutter or React Native.

⚙ Installation guide to set up Flutter on your machine: https://docs.flutter.dev/get-started/install

⚙ React Native project setup guide: https://reactnative.dev/docs/environment-setup

✔ Create or connect to a Solana wallet. A wallet is essential for interacting with the Solana blockchain. You can leverage existing wallets or create a custom one using the available SDKs.

⚡Connecting Wallets: The Trio of Choices

✨ Three Ways to Connect :

Now, here's where the choices come in for connecting wallets:

  • Custodial Wallet: This is like having a wallet held by a trusted friend. It's easy, but users don't have complete control over transactions.

  • Connect with Wallet: Think of it as a universal pass—good for everyone. It's easy, users get to approve transactions and overall control.

  • Web3Auth: This is a middle ground, it allows connecting wallet using google sign in, but it comes with it's own restrictions

✨ Navigating the Landscape :

While connecting wallets, it's crucial to know that each way comes with its pros and cons. It's like choosing between different routes for a road trip. Depending on what users need and your app's vibe, you pick the best route.

🔨 Integrating SMS with Flutter :

Flutter integration with SMS mainly works with the following packages

⚡ solana_wallet_adapter (https://pub.dev/packages/solana_wallet_adapter)

It is a common package used to integrate SMS Mobile Wallet Adapter.

⚡ solana_mobile_client (https://pub.dev/packages/solana_mobile_client)

This package is commonly used to communicate with Solana client.

⚡solana (https://pub.dev/packages/solana)

This package is Solana web3js package equivalent built for dart.

Additionally,

⚡ solana_pay (https://pub.dev/packages/solana_pay)

This package can be used to integrate Solana Pay Protocol with your app.

As I mentioned earlier, choosing the right packages is important and as devs, it is easy to figure out the rest from there so instead of me giving some random code examples, here is well well-written comprehensive tutorial that covers building a basic dApp in Flutter.

https://medium.com/@ronak01.raj/a-comphrensive-tutotial-building-dapps-with-flutter-and-solana-mobile-stack-sms-e452356a0adb

🔨 Integrating SMS with React Native :

React Native integration with SMS mainly works with the following packages

⚡ wallet-adapter-mobile (https://www.npmjs.com/package/@solana-mobile/wallet-adapter-mobile)

It is a common package used to integrate SMS Mobile Wallet Adapter for react.

⚡ wallet-adapter-react-native (https://www.npmjs.com/package/@solana-mobile/mobile-wallet-adapter-walletlib)

This is a package that provides React Native bridge for the native mobile-wallet-adapter-walletlib library and it is designed for Wallet apps built in React Native. It provides an API to implement the wallet endpoint of the mobile wallet adapter protocol.

⚡ solana (https://www.npmjs.com/package/@solana/web3.js)

Package used to communicate with the Solana web rpc

Additionally,

⚡ solana-pay (https://www.npmjs.com/package/@solana/pay)

This package is used to integrate Solana Pay in React Native.

Just like for Flutter, we have a well-written tutorial that covers the basics https://medium.com/@laura.estupinand/solana-mobile-stack-developer-tutorial-building-a-dapp-in-react-native-125998ba3681

📱 Advantages of building with Saga Phone :

Do you own a Saga phone and want to unlock its full potential for development? Say no further here it is!

Saga has an in-built hardware wallet called Seed Vault, which not even the Android OS can touch.

It makes working with Web3 much easier and smoother than regular web apps.

With apps like Phantom or Solflare, doing transactions on the Solana network is as simple as a screen touch, with occasional PIN inputs for security.

It's all about a straightforward and user-friendly experience!

Get yours here https://two.solanamobile.com/

🛠 Additional Tools :

Many emerging tools want to make the process of integrating Solana in dApps a seamless task. I have listed and briefed about 2 such tools that you might find useful and want to use in your next dApp.

🎉 CandyPay :

CandyPay simplifies Solana payments for businesses by providing an easy-to-use solution.

It overcomes technical challenges, offers a user-friendly experience, and ensures mobile support, making it hassle-free for merchants to accept Solana transactions.

🎉 Saganize :

Saganize simplifies and secures Solana Mobile transactions with Solwave, a Kotlin SDK.

Developers can effortlessly add in-app transactions without building a separate wallet, ensuring swift approvals, seamless user experiences, and top-notch security through advanced encryption.

Users can onboard easily, log in once for hassle-free transactions, and approve with a quick PIN entry within the Saganize ecosystem.

Enough of Frontend, Now Let's checkout backend stuff also

🔥Building Custodial Wallets with Solana Mobile Stack :

1. Authentication and Single Sign-On (SSO)

Creating a custodial wallet on the Solana Mobile Stack starts with a robust authentication system. Leveraging Firebase for Single Sign-On (SSO) simplifies the authentication process by allowing users to sign in using various providers such as email, Google, or Apple. Firebase's authentication services provide a secure and efficient way to manage user logins and retrieve an idToken post successful authentication.

// Example of Firebase authentication and obtaining idToken
const idToken = await firebase.auth().currentUser.getIdToken();

2. Backend Integration

Backend Technologies: Express and Nest.js

Selecting the right backend technology is crucial for seamless integration with the Solana Mobile Stack. Developers have the option to choose between Express and Nest.js, both of which are powerful frameworks for building the backend infrastructure.

  • Express: Known for its simplicity and speed, Express is a minimalist Node.js framework. It enables developers to set up routes and middleware effortlessly, making it an ideal choice for straightforward APIs.

  • Nest.js: Built on top of Express, Nest.js offers a more structured and scalable approach to building APIs. Its modular architecture and TypeScript support enhance code organization and maintainability, making it a suitable choice for complex backend structures.

3. Custodial Wallet Creation

Following successful authentication, the backend generates a Solana wallet for the user using the Solana Web3.js library. The subsequent code snippet illustrates the process of generating a keypair, storing the public key securely in the frontend, and preserving the private key in the backend.

import { Keypair } from "@solana/web3js";

const keypair = Keypair.generate();
const publicKey = keypair.publicKey.toString();
// Save publicKey in the frontend, and securely store keypair.privateKey in the backend database.

⚡Backend Structure for Solana Mobile Apps :

Developers creating Solana mobile apps often need to design a backend architecture that caters to mobile client. This backend is responsible for managing on-chain interactions, normal backend functionality, and if needed facilitating communication with smart contracts. but mostly smart contract is integrated from frontend only

Make It Scalable, Secure, and Efficient

To ensure your Solana mobile app's backend is robust, scalable, and secure:

  • Implement scalability measures to accommodate growth in user base and data.

  • Strengthen security protocols, including encryption, to safeguard user data and transactions.

  • Centralize computational tasks in the backend to enhance app performance, keeping it fast, simple, and secure.

1. Common Backend Functionality

A robust backend must support standard functionalities, including user authentication, authorization, and seamless interaction with the Solana blockchain. This involves creating APIs that handle user requests, validate transactions, and ensure data consistency.

2. On-Chain Interaction

Interfacing with the Solana blockchain is facilitated through the Solana Web3.js library. This encompasses tasks such as querying blockchain data, executing transactions, and handling relevant events. Your backend should have dedicated APIs for these interactions, ensuring that data remains synchronized between the blockchain and your app.

3. Backend Development with Express and Nest.js

Express Backend:

Express, known for its lightweight nature, offers developers the flexibility to swiftly set up APIs. By defining routes and middleware, developers can create a backend that efficiently serves Solana mobile apps.

Nest.js Backend:

Nest.js, building upon Express, introduces a more structured and scalable approach. Its modular architecture, TypeScript support, and powerful dependency injection system make it an excellent choice for complex backend architectures.

4. Choosing the Right Database

Selecting the appropriate database system depends on the specific needs of your Solana mobile app. Consider factors such as data structure, scalability, and query requirements when deciding between SQL and NoSQL databases.

Database Choices: SQL vs. NoSQL

Choosing the right database system is crucial for the efficient functioning of your backend.

  • SQL Databases: SQL databases, such as PostgreSQL or MySQL, offer strong consistency and are well-suited for scenarios where data integrity is paramount. They are particularly useful when dealing with complex queries and relationships between data.

  • NoSQL Databases: NoSQL databases like MongoDB or Cassandra provide flexibility and scalability. They are suitable for scenarios where data structure may evolve over time and need to handle large volumes of data.

Consider the specific requirements of your Solana mobile app when selecting a database system, and ensure that it integrates seamlessly with your chosen backend framework

🔐Smart Contract Development with Anchor :

Solana smart contracts, often referred to as programs, are developed using the Anchor framework, which is based on Rust.

1. Writing Smart Contracts in Anchor

Developers articulate smart contracts in Rust, leveraging the Anchor framework. These contracts encapsulate the business logic and operations to be executed on the Solana blockchain. Rust's safety features and performance optimizations make it an excellent choice for writing secure and efficient smart contracts.

2. IDL and Generating Types

To facilitate interaction with smart contracts in the frontend, developers can utilize the Interface Definition Language (IDL) or generate types by building the program. IDL provides a structured way to define methods and data structures within smart contracts, simplifying integration. Generating types ensures that your frontend code is type-safe and can communicate effectively with the Solana smart contracts.

Integrating Frontend with Solana Smart Contracts (Anchor):

Once you have built the frontend, established a robust backend structure, and developed smart contracts using the Anchor framework in Rust, the next step is to seamlessly integrate your mobile app with these Solana smart contracts. This integration allows your app to interact with the blockchain and execute operations on the smart contract.

⚒️ Integrating Frontend with Solana Smart Contracts (Anchor):

Once you have built the frontend, established a robust backend structure, and developed smart contracts using the Anchor framework in Rust, the next step is to seamlessly integrate your mobile app with these Solana smart contracts. This integration allows your app to interact with the blockchain and execute operations on the smart contract.

1. Establishing Communication:

To interact with Solana smart contracts, your frontend needs to communicate with the Solana blockchain using the Solana Web3.js library. This library enables your app to send transactions and query data on the blockchain.

import {Connection} from "@solana/web3js"

const connection = new Connection("https://api.devnet.solana.com");

2. Connecting to the Smart Contract:

To connect to a specific smart contract (program) deployed on Solana, you'll need the program ID or the address of the deployed program. This information is crucial for your app to identify and interact with the correct smart contract.

import {PublicKey} from "@solana/web3js";
const programId = new PublicKey("your-program-id");

3. Handling Transactions:

Your mobile app can initiate transactions that trigger functions within the smart contract. These transactions can involve various operations, such as sending tokens, updating data, or executing specific actions defined in the contract

// Example of initiating a transaction to interact with a Solana smart contract
const transaction = new Transaction().add(
  anchor.web3.SystemProgram.transfer({
    fromPubkey: userWallet.publicKey,
    toPubkey: contractAddress,
    lamports: 100000, // Amount in lamports (SOL)
  })
);

// Sign and send the transaction
await anchor.web3.sendTransaction(transaction, [userWallet]);

4. Utilizing Anchor's Library:

Anchor provides a library that simplifies interactions with Solana smart contracts. You can use the generated TypeScript bindings from the Anchor IDL to call the smart contract's functions directly from your app's frontend

import { Wallet } from "@coral-xyz/anchor";
import {Keypair, Connection, SendAndConfirmTransaction} from "@solana/web3js";

const Sample = () => { 
const connection = new Connection("https://api.devnet.solana.com/");
const wallet = useAnchorWallet(); 
const program = anchorProgram(wallet as Wallet);
const programId = new PublicKey("your-program-id-here");
const accounts = [ { pubkey: programId, isWritable: false, isSigner: false, },]

const instruction = new TransactionInstruction({ keys: accounts, programId: programId, data: Buffer.from([your-function-parameters-here]), });

const transaction = new Transaction().add(instruction);

const { blockhash } = await connection.getRecentBlockhash(); transaction.recentBlockhash = blockhash; 
transaction.feePayer = wallet.publicKey; const signedTransaction = await wallet.signTransaction(transaction); 
const signature = await sendAndConfirmTransaction( connection, signedTransaction );
}

Refer to the official documentation of anchor for more reference.

Docs : https://www.anchor-lang.com/

💭 My experience and final thoughts :

SMS is a good entry point for developers to work on Solana based dApps.

I recommend starting with one of the blogs shared earlier to build your first dApp and slowly customize it to your needs. Why so?

  1. You will be able to debug and solve any issues pretty quickly, which will help you get a grip on things. This will be beneficial when you start customizing the app for your specifications and come across new/general errors.

  2. You will learn the use cases covered by the packages you will integrate.

During development, only some of your use cases might be covered and you have to work with some unstable packages but SMS is actively improving day by day.

All the packages/SDKs are open source and checking on all the issues and active PRs are some good starting points to debug and fix errors in your app. And don't forget to join the super-active discord community of SMS, which is always there to guide and help you.

If you come across a solution for existing issues, contribute to the SDK's and help out the community to improve the SDK's for everyone.

🔖 Resources :

🔗 Official Website: solanamobile.com

🔗 Join the Discord: discord.com/invite/solanamobile

🔗 Official Docs: docs.solanamobile.com/getting-started

🔗 React Native Firebase : https://rnfirebase.io/

🔗 Solana Cookbook : https://solanacookbook.com/

🔗 Anchor Program Tutorial : https://www.quicknode.com/guides/solana-development/anchor/how-to-write-your-first-anchor-program-in-solana-part-1

🔗 And all the other links provided throughout the blog

🤖 References :

https://docs.solanamobile.com/getting-started/overview

https://heybeluga.com/articles/solana-saga-phone-review/

https://docs.candypay.fun/checkout/introduction.html

https://github.com/saganize

Image credits
https://hornbull.substack.com/p/the-1st-crypto-phone

https://twitter.com/candypayfun/status/1621227243006734337