### Install Dependencies
Source: https://docs.solanamobile.com/get-started/react-native/mobile-wallet-adapter
Install the necessary packages for the Mobile Wallet Adapter using yarn or npm.
```APIDOC
## Install dependencies
* **`@solana-mobile/mobile-wallet-adapter-protocol`**
* Base library that implements the MWA client. Include this, but only import `transact` from the wrapper library.
* **`@solana-mobile/mobile-wallet-adapter-protocol-web3js`**
* A convenience wrapper for the base library that enables with `web3.js` primitives like `Transaction`.
```shell yarn theme={null}
yarn add \
@solana-mobile/mobile-wallet-adapter-protocol-web3js \
@solana-mobile/mobile-wallet-adapter-protocol \
```
```shell npm theme={null}
npm install \
@solana-mobile/mobile-wallet-adapter-protocol-web3js \
@solana-mobile/mobile-wallet-adapter-protocol \
```
```
--------------------------------
### Initialize and Install Solana Mobile Dapp Store CLI (Shell)
Source: https://docs.solanamobile.com/dapp-store/publishing-cli/setup
This sequence of commands initializes a new project directory for publishing, installs the Solana Mobile dapp-store CLI as a development dependency, and then initializes the CLI.
```shell
mkdir publishing
cd publishing
pnpm init
pnpm install --save-dev @solana-mobile/dapp-store-cli
npx dapp-store init
npx dapp-store --help
```
--------------------------------
### Install Dependencies for React Native Web3JS
Source: https://docs.solanamobile.com/get-started/react-native/installation
Installs the necessary libraries for integrating the Mobile Wallet Adapter with React Native and Solana. This includes @wallet-ui/react-native-web3js, react-native-quick-crypto for polyfills, @solana/web3.js for blockchain interaction, and expo-dev-client for development builds.
```npm
npm install @wallet-ui/react-native-web3js react-native-quick-crypto @solana/web3.js expo-dev-client
```
```yarn
yarn add @wallet-ui/react-native-web3js react-native-quick-crypto @solana/web3.js expo-dev-client
```
```pnpm
pnpm add @wallet-ui/react-native-web3js react-native-quick-crypto @solana/web3.js expo-dev-client
```
--------------------------------
### Install Mobile Wallet Adapter Dependencies
Source: https://docs.solanamobile.com/get-started/react-native/mobile-wallet-adapter
Commands to install the required Mobile Wallet Adapter protocol packages using yarn or npm. These packages provide the necessary primitives for dApp-to-wallet communication.
```shell
yarn add @solana-mobile/mobile-wallet-adapter-protocol-web3js @solana-mobile/mobile-wallet-adapter-protocol
```
```shell
npm install @solana-mobile/mobile-wallet-adapter-protocol-web3js @solana-mobile/mobile-wallet-adapter-protocol
```
--------------------------------
### PWA Web Manifest Example
Source: https://docs.solanamobile.com/dapp-store/build-and-sign-an-apk
Provides a basic structure for a PWA web manifest file. This JSON file defines essential metadata for a Progressive Web App, including its name, icons, and start URL, which is a prerequisite for wrapping PWAs in a Trusted Web Activity for the dApp Store.
```json
{
"name": "APP_NAME",
"short_name": "APP_NAME",
"scope": "/",
"start_url": "/",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
```
--------------------------------
### Install Solana Web3.js Dependencies (NPM)
Source: https://docs.solanamobile.com/reference/typescript/web3js
Installs the necessary Solana Web3.js and related packages using NPM. This includes the core web3 library, random value generation, URL polyfills, and buffer support for React Native.
```shell
npm install \
@solana/web3.js \
react-native-get-random-values \
react-native-url-polyfill \
@craftzdog/react-native-buffer
```
--------------------------------
### Install and Test Android APK
Source: https://docs.solanamobile.com/dapp-store/build-and-sign-an-apk
Installs the generated signed release APK onto a device or emulator for testing. This command is used to verify the app's functionality and Digital Asset Links configuration.
```bash
bubblewrap install app-release-signed.apk
```
--------------------------------
### Install Solana Mobile Wallet Standard Package
Source: https://docs.solanamobile.com/get-started/web/installation
Installs the Mobile Wallet Adapter package into your web application using npm. This is the first step to integrating Solana Pay functionality.
```shell
npm install @solana-mobile/wallet-standard-mobile
```
--------------------------------
### Prepare PNPM with Corepack (Shell)
Source: https://docs.solanamobile.com/dapp-store/publishing-cli/setup
This snippet demonstrates how to enable and prepare PNPM using Corepack, ensuring the correct version is activated. It includes a fallback for cases where jq is not installed.
```shell
corepack enable
corepack prepare pnpm@`npm info pnpm --json | jq -r .version` --activate
```
```shell
corepack prepare pnpm@7.13.4 --activate
```
--------------------------------
### Install Bubblewrap CLI
Source: https://docs.solanamobile.com/dapp-store/build-and-sign-an-apk
Installs the Bubblewrap CLI globally using npm. This tool is used to convert PWAs into Android apps via Trusted Web Activities (TWA).
```bash
npm i -g @bubblewrap/cli
```
--------------------------------
### MobileWalletProvider Setup
Source: https://docs.solanamobile.com/get-started/react-native/setup
Wrap your app's root component with MobileWalletProvider to manage wallet connection state and provide access to the useMobileWallet hook.
```APIDOC
## MobileWalletProvider Setup
### Description
Wrap your app's root component with `MobileWalletProvider` from `@wallet-ui/react-native-web3js`. This provider manages the wallet connection state and exposes the `useMobileWallet` hook to all child components.
### Method
Component Setup
### Endpoint
N/A (Component Integration)
### Parameters
#### Props
- **chain** (string) - Required - The Solana cluster to connect to (e.g. `'solana:devnet'`, `'solana:mainnet-beta'`).
- **endpoint** (string) - Required - The RPC endpoint URL for the cluster.
- **identity** (object) - Required - Your app's identity shown to the user during wallet authorization.
##### Identity object
- **name** (string) - Required - Your app's display name.
- **uri** (string) - Required - Your app's website URL.
- **icon** (string) - Required - Path to your app icon, relative to `uri`.
### Request Example
```tsx App.tsx
import { MobileWalletProvider } from '@wallet-ui/react-native-web3js';
import { clusterApiUrl } from '@solana/web3.js';
const chain = 'solana:devnet';
const endpoint = clusterApiUrl('devnet');
const identity = {
name: 'My Solana App',
uri: 'https://mysolanaapp.com',
icon: 'favicon.png',
};
export default function App() {
return (
{/* Your app content */}
);
}
```
### Response
N/A (Component Setup)
```
--------------------------------
### Install expo-secure-store for Custom Cache
Source: https://docs.solanamobile.com/recipes/mobile-wallet-adapter/caching-wallet-authorization
Command to install the expo-secure-store package, which can be used to create an encrypted cache for authorization details.
```shell
npx expo install expo-secure-store
```
--------------------------------
### Sign In with Solana using Mobile Wallet Adapter
Source: https://docs.solanamobile.com/get-started/web/ux-guidelines
This example shows how to combine `connect` and `signMessage` into a single user action using the `signIn()` method, which is specifically supported by the Mobile Wallet Adapter. This approach avoids browser restrictions on programmatic navigation and ensures a secure sign-in flow on Android Web.
```typescript
import { useWallet } from '@solana/wallet-adapter-react'
import { useWalletModal } from '@solana/wallet-adapter-react-ui';
import { SolanaMobileWalletAdapterWalletName } from '@solana-mobile/wallet-standard-mobile'
export default function SignInButton() {
const { connected, signIn, wallet, wallets } = useWallet();
const { setVisible: showWalletSelectionModal } = useWalletModal();
const handleSignInButtonClick = () => {
// MWA is only available if user is on Android Web environments (e.g Android Chrome).
if (wallet?.adapter?.name === SolanaMobileWalletAdapterWalletName) {
// If MWA is present, immediately sign in.
const input: SolanaSignInInput = {
domain: window.location.host,
statement: "Sign in to My Web App",
uri: window.location.origin,
}
const output = await signIn(input);
} else {
// Else, show modal as usual.
showWalletSelectionModal(true)
}
}
return ;
}
```
--------------------------------
### Add Dependencies
Source: https://docs.solanamobile.com/get-started/react-native/invoke-mwa-sessions-directly
Install the necessary React Native libraries for the Mobile Wallet Adapter protocol.
```APIDOC
## Add dependencies
Solana Mobile has published two React Native libraries to use Mobile Wallet Adapter.
* [`@solana-mobile/mobile-wallet-adapter-protocol`](https://github.com/solana-mobile/mobile-wallet-adapter/tree/main/js/packages/mobile-wallet-adapter-protocol) is the core library that implements the Mobile Wallet Adapter protocol for React Native.
* [`@solana-mobile/mobile-wallet-adapter-protocol-web3js`](https://github.com/solana-mobile/mobile-wallet-adapter/tree/main/js/packages/mobile-wallet-adapter-protocol-web3js) is a convenience wrapper package around the core library that enables use of common types from `@solana/web3.js` – such as `Transaction` and `Uint8Array`.
These libraries provide a convenient API to connect, issue signing requests to a locally installed wallet app, and receive responses.
```bash yarn theme={null}
yarn add @solana-mobile/mobile-wallet-adapter-protocol-web3js \
@solana-mobile/mobile-wallet-adapter-protocol
```
```bash npm theme={null}
npm install @solana-mobile/mobile-wallet-adapter-protocol-web3js \
@solana-mobile/mobile-wallet-adapter-protocol \
```
```
--------------------------------
### Localize Store Details in config.yaml
Source: https://docs.solanamobile.com/dapp-store/publishing-cli/prepare
This example demonstrates how to localize app store details, such as name and descriptions, for different locales within the `config.yaml` file. It shows the structure for providing default English (`en-US`) and French (`fr-FR`) localized content.
```yaml
release:
catalog:
en-US:
name: Name of app in English
...
fr-FR:
name: >-
Name of app in French (France)
short_description: >-
Short app description in French (France)
long_description: |
Long app description in French (France)
new_in_version: >-
New version features in French (France)
saga_features: >-
Saga features in French (France)
```
--------------------------------
### Install Solana Web3.js Dependencies (Yarn)
Source: https://docs.solanamobile.com/reference/typescript/web3js
Installs the necessary Solana Web3.js and related packages using Yarn. This includes the core web3 library, random value generation, URL polyfills, and buffer support for React Native.
```shell
yarn add \
@solana/web3.js \
react-native-get-random-values \
react-native-url-polyfill \
@craftzdog/react-native-buffer
```
--------------------------------
### Import into a file
Source: https://docs.solanamobile.com/get-started/react-native/mobile-wallet-adapter
Import the necessary components from the installed packages into your TypeScript file.
```APIDOC
### Import into a file
```tsx theme={null}
import {
transact,
Web3MobileWallet,
} from "@solana-mobile/mobile-wallet-adapter-protocol-web3js";
```
```
--------------------------------
### Link to Solana dApp Store Listing from Kotlin
Source: https://docs.solanamobile.com/dapp-store/link-to-dapp-listing-page
Creates an Android `Intent` to navigate to the dApp Store listing page using the `solanadappstore` URI scheme. It ensures that an activity exists to handle the intent before starting the activity.
```kotlin
// Create an Android intent to navigate to the listing page
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse("solanadappstore://details?id=com.solanamobile.mintyfresh")
// Make sure there's an activity that can handle this intent
resolveActivity(packageManager)?.let {
startActivity(this)
}
}
```
--------------------------------
### Solana Project Output Structure
Source: https://docs.solanamobile.com/recipes/solana-development/anchor-integration
This illustrates the typical directory structure generated by the Solana mobile project setup. These directories contain accounts, instructions, programs, types, and errors related to your smart contract.
```text
src/generated/your-program/
accounts/
instructions/
programs/
types/
errors/
```
--------------------------------
### Initialize PWA Project with Bubblewrap CLI
Source: https://docs.solanamobile.com/dapp-store/build-and-sign-an-apk
Initializes a new PWA project by providing the URL to the web manifest. This command prompts for configuration details like domain, display mode, splash screen, icons, and signing keystore.
```bash
bubblewrap init --manifest https://your-pwa-url.com/manifest.json
```
--------------------------------
### Create Solana RPC Client Instance (Kotlin)
Source: https://docs.solanamobile.com/android-native/rpc-requests
Demonstrates how to create an instance of SolanaRpcClient. It requires an RPC endpoint URL and a network driver, such as KtorNetworkDriver, for making HTTP requests.
```kotlin
import com.solana.rpc.SolanaRpcClient
import com.solana.networking.KtorNetworkDriver
val rpcClient = SolanaRpcClient("https://api.devnet.solana.com", KtorNetworkDriver())
```
--------------------------------
### Instantiate MobileWalletAdapter Client
Source: https://docs.solanamobile.com/get-started/kotlin/setup
Learn how to create an instance of the MobileWalletAdapter client, providing your dApp's identity information.
```APIDOC
## Instantiate MobileWalletAdapter Client
The `MobileWalletAdapter` object is used to connect to wallets and send MWA requests. You must define your dApp's `ConnectionIdentity` so wallets can display your dApp's information.
### Request Body
- **connectionIdentity** (ConnectionIdentity) - Required - Your dApp's identity metadata.
- **identityUri** (Uri) - Required - Your app's website URL.
- **iconUri** (Uri) - Required - Path to your app icon, relative to `identityUri`.
- **identityName** (String) - Required - Your app's display name shown to the user during wallet authorization.
### Request Example
```kotlin
import android.net.Uri
import com.solana.mobilewalletadapter.clientlib.ConnectionIdentity
import com.solana.mobilewalletadapter.clientlib.MobileWalletAdapter
// Define dApp's identity metadata
val solanaUri = Uri.parse("https://yourdapp.com")
val iconUri = Uri.parse("favicon.ico") // resolves to https://yourdapp.com/favicon.ico
val identityName = "Solana Kotlin dApp"
// Construct the client
val walletAdapter = MobileWalletAdapter(connectionIdentity = ConnectionIdentity(
identityUri = solanaUri,
iconUri = iconUri,
identityName = identityName
))
```
### Response
This action does not directly return a response in the traditional sense, but it initializes the `walletAdapter` object for subsequent operations.
```
--------------------------------
### Install Anchor for React Native
Source: https://docs.solanamobile.com/recipes/solana-development/anchor-integration
Installs the Anchor library version 0.28.0, which is recommended for React Native due to a polyfill issue in later versions. Supports both Yarn and npm package managers.
```shell
yarn add @coral-xyz/anchor@0.28.0
```
```shell
npm install @coral-xyz/anchor@0.28.0
```
--------------------------------
### Instantiate Anchor Program in TypeScript
Source: https://docs.solanamobile.com/recipes/solana-development/anchor-integration
Demonstrates how to import an IDL and use the AnchorProvider to create an instance of a Program. It utilizes useMemo to ensure the provider and program instances are cached correctly.
```typescript
import { BasicCounter as BasicCounterProgram } from "../../basic-counter/target/types/basic_counter";
import { AnchorProvider, Program } from "@coral-xyz/anchor";
const COUNTER_PROGRAM_ID = "ADraQ2ENAbVoVZhvH5SPxWPsF2hH5YmFcgx61TafHuwu";
const counterProgramId = useMemo(() => {
return new PublicKey(COUNTER_PROGRAM_ID);
}, []);
const provider = useMemo(() => {
if (!anchorWallet) {
return null;
}
return new AnchorProvider(connection, anchorWallet, {
preflightCommitment: "confirmed",
commitment: "processed",
});
}, [anchorWallet, connection]);
const counterProgram = useMemo(() => {
if (!provider) {
return null;
}
return new Program(
idl as BasicCounterProgram,
counterProgramId,
provider
);
}, [counterProgramId, provider]);
```
--------------------------------
### Set Solana Web3JS Entry Point
Source: https://docs.solanamobile.com/get-started/react-native/installation
Configures the application's entry point to include the crypto polyfill first, ensuring compatibility with @solana/web3.js. This involves updating the 'index.js' file and potentially the 'package.json' to point to the new entry point.
```javascript
import './polyfill';
import 'expo-router/entry'; // If using Expo Router
```
```json
{
"main": "./index.js"
}
```
--------------------------------
### Sign In with Solana (SIWS) using Kotlin MWA Client
Source: https://docs.solanamobile.com/get-started/kotlin/quickstart
Demonstrates the Sign In with Solana (SIWS) flow, combining wallet authorization and message signing into a single step. It also shows how to include SIWS payload within a `transact` session for subsequent requests. Requires ActivityResultSender and MobileWalletAdapter.
```kotlin
import com.solana.mobilewalletadapter.clientlib.*
val sender = ActivityResultSender(this)
val walletAdapter = MobileWalletAdapter(/* ... */)
val result = walletAdapter.signIn(
sender,
SignInWithSolana.Payload("yourdomain.com", "Sign in to My App")
)
when (result) {
is TransactionResult.Success -> {
val signInResult = result.authResult.signInResult
println("Signed in successfully")
}
is TransactionResult.NoWalletFound -> {
println("No MWA compatible wallet app found on device.")
}
is TransactionResult.Failure -> {
println("Error signing in: " + result.e.message)
}
}
// SIWS within a transact session
val transactResult = walletAdapter.transact(sender,
SignInWithSolana.Payload("yourdomain.com", "Sign in to My App")) { authResult ->
/* Send additional MWA requests here */
}
```
--------------------------------
### Instantiate MobileWalletAdapter Client (Kotlin)
Source: https://docs.solanamobile.com/android-native/using_mobile_wallet_adapter
Initializes the MobileWalletAdapter client with your dApp's identity information. This includes the app name, URI, and icon URI, which are displayed to the user in the wallet app.
```kotlin
import com.solana.mobilewalletadapter.clientlib.*
// Define dApp's identity metadata
val solanaUri = Uri.parse("https://yourdapp.com")
val iconUri = Uri.parse("favicon.ico") // resolves to https://yourdapp.com/favicon.ico
val identityName = "Solana Kotlin dApp"
// Construct the client
val walletAdapter = MobileWalletAdapter(connectionIdentity = ConnectionIdentity(
identityUri = solanaUri,
iconUri = iconUri,
identityName = identityName
))
```
--------------------------------
### Establishing an MWA Session
Source: https://docs.solanamobile.com/android-native/using_mobile_wallet_adapter
Uses the transact method to initiate a connection session with a locally installed MWA-compliant wallet.
```APIDOC
## transact(sender)
### Description
Dispatches an association intent to the wallet app and handles the connection lifecycle.
### Parameters
- **sender** (ActivityResultSender) - Required - The current Android activity context.
### Response
- **TransactionResult** (Object) - Returns the result of the transaction session, including potential auth tokens.
### Request Example
```kotlin
val sender = ActivityResultSender(this)
val result = walletAdapter.transact(sender) { authResult ->
// Perform wallet operations here
}
```
```
--------------------------------
### Sign and Send SOL Transfer Transaction with Mobile Wallet Adapter
Source: https://docs.solanamobile.com/get-started/kotlin/quickstart
This Kotlin snippet demonstrates how to initiate a transaction session, fetch the latest blockhash, construct a SOL transfer, and then request the wallet to sign and send the transaction. It also includes handling success and failure scenarios.
```kotlin
import com.funkatronics.encoders.Base58
import com.solana.publickey.SolanaPublicKey
import com.solana.transaction.*
import com.solana.mobilewalletadapter.clientlib.*
import com.solana.rpc.SolanaRpcClient
import com.solana.networking.KtorNetworkDriver
val sender = ActivityResultSender(this)
val walletAdapter = MobileWalletAdapter(/* ... */)
val result = walletAdapter.transact(sender) { authResult ->
val userAddress = SolanaPublicKey(authResult.accounts.first().publicKey)
// Fetch latest blockhash
val rpcClient = SolanaRpcClient("https://api.devnet.solana.com", KtorNetworkDriver())
val blockhashResponse = rpcClient.getLatestBlockhash()
// Build a SOL transfer transaction
val transferTx = Transaction(
Message.Builder()
.addInstruction(
SystemProgram.transfer(
userAddress,
SolanaPublicKey(""),
1_000_000L // lamports
)
)
.setRecentBlockhash(blockhashResponse.result!!.blockhash)
.build()
)
// Sign and send the transaction
signAndSendTransactions(arrayOf(transferTx.serialize()))
}
when (result) {
is TransactionResult.Success -> {
val txSignatureBytes = result.successPayload?.signatures?.first()
txSignatureBytes?.let {
println("Transaction signature: " + Base58.encodeToString(it))
}
}
is TransactionResult.NoWalletFound -> {
println("No MWA compatible wallet app found on device.")
}
is TransactionResult.Failure -> {
println("Error during signing and sending: " + result.e.message)
}
}
```
--------------------------------
### Define Cache Interface for MobileWalletProvider
Source: https://docs.solanamobile.com/recipes/mobile-wallet-adapter/caching-wallet-authorization
Defines the generic Cache interface required by MobileWalletProvider. This interface specifies the methods for getting, setting, and clearing cached authorization data.
```typescript
interface Cache {
clear(): Promise;
get(): Promise;
set(value: T): Promise;
}
```
--------------------------------
### Get Wallet Capabilities
Source: https://docs.solanamobile.com/get-started/react-native/mobile-wallet-adapter
Retrieves the capabilities and limitations of the wallet's Mobile Wallet Adapter implementation. This includes information on transaction limits, supported transaction versions, and optional features.
```typescript
const result = await transact(async (wallet: Web3MobileWallet) => {
return await wallet.getCapabilities();
});
```
--------------------------------
### Sign Transactions Manually with Mobile Wallet Adapter
Source: https://docs.solanamobile.com/recipes/solana-development/anchor-integration
Shows how to generate serialized instructions from an Anchor program, construct a transaction, and sign it manually using the Mobile Wallet Adapter session.
```typescript
const {counterProgram, counterPDA} = useCounterProgram();
const signIncrementTransaction = async () => {
return await transact(async (wallet: Web3MobileWallet) => {
const authorizationResult = wallet.authorize({
cluster: RPC_ENDPOINT,
identity: APP_IDENTITY,
}));
const latestBlockhash = await connection.getLatestBlockhash();
const incrementInstruction = await counterProgram.methods
.increment(new anchor.BN(amount))
.accounts({
counter: counterPDA,
})
.instruction();
const incrementTransaction = new Transaction({
...latestBlockhash,
feePayer: authorizationResult.publicKey,
}).add(incrementInstruction);
const signedTransactions = await wallet.signTransactions({
transactions: [incrementTransaction],
});
return signedTransactions[0];
});
}
```
--------------------------------
### Add SHA256 Fingerprint to TWA Manifest
Source: https://docs.solanamobile.com/dapp-store/build-and-sign-an-apk
Adds the generated SHA256 fingerprint to the Trusted Web Activity (TWA) manifest using the Bubblewrap CLI. This is part of the Digital Asset Links setup.
```bash
bubblewrap fingerprint add
```
--------------------------------
### Fetch Latest Blockhash using Solana RPC Client (Kotlin)
Source: https://docs.solanamobile.com/android-native/rpc-requests
This example shows how to call the getLatestBlockhash method on a SolanaRpcClient instance. It handles both successful responses containing a blockhash and error responses.
```kotlin
import com.solana.rpc.SolanaRpcClient
import com.solana.networking.KtorNetworkDriver
val rpcClient = SolanaRpcClient("https://api.devnet.solana.com", KtorNetworkDriver())
val response = rpcClient.getLatestBlockhash()
if (response.result) {
println("Latest blockhash: ${response.result.blockhash}")
} else if (response.error) {
println("Failed to fetch latest blockhash: ${response.error.message}")
}
```
--------------------------------
### MobileWalletAdapter.signIn()
Source: https://docs.solanamobile.com/android-native/using_mobile_wallet_adapter
Initiates the Sign-In with Solana (SIWS) flow to verify wallet ownership.
```APIDOC
## signIn()
### Description
Initiates the SIWS flow, prompting the user to sign a statement message to verify ownership of the wallet.
### Method
Kotlin Method
### Parameters
- **sender** (ActivityResultSender) - Required - The current Android activity context.
- **payload** (SignInWithSolana.Payload) - Required - Contains the domain and statement for the sign-in request.
### Response
- **TransactionResult.Success** - Returns an AuthorizationResult containing a SignInResult object.
- **SignInResult** - Contains fields defined in the SIWS spec for backend verification.
```
--------------------------------
### Generate JavaScript Code with Codama
Source: https://docs.solanamobile.com/recipes/solana-development/anchor-integration
This command uses the codama CLI to generate JavaScript code for the Solana project. Ensure codama is installed and configured correctly. The output will be placed in the directory specified by `scripts.js.args`.
```shell
npx codama run js
```
--------------------------------
### Instantiate MobileWalletAdapter
Source: https://docs.solanamobile.com/android-native/using_mobile_wallet_adapter
Configures the dApp identity and initializes the MobileWalletAdapter client to facilitate communication with local wallet applications.
```APIDOC
## Instantiate MobileWalletAdapter
### Description
Initializes the client with dApp metadata required for wallet authorization prompts.
### Parameters
- **identityName** (String) - Required - The name of your application.
- **identityUri** (Uri) - Required - The web URL associated with your application.
- **iconUri** (Uri) - Required - The path to your application icon.
### Request Example
```kotlin
val walletAdapter = MobileWalletAdapter(connectionIdentity = ConnectionIdentity(
identityUri = Uri.parse("https://yourdapp.com"),
iconUri = Uri.parse("favicon.ico"),
identityName = "Solana Kotlin dApp"
))
```
```
--------------------------------
### Configure Crypto Polyfill for Solana Web3JS
Source: https://docs.solanamobile.com/get-started/react-native/installation
Sets up the crypto polyfill required by @solana/web3.js in React Native projects. It involves creating a 'polyfill.js' file to install the polyfill and ensuring it's imported before any other code that utilizes the Solana SDK.
```javascript
import { install } from 'react-native-quick-crypto';
install();
```
--------------------------------
### Configure Android SDK Tools Directory (Shell)
Source: https://docs.solanamobile.com/dapp-store/publishing-cli/setup
This command sets the ANDROID_TOOLS_DIR environment variable in a .env file, pointing to the Android SDK build tools directory. This is necessary for the dapp-store CLI.
```shell
echo "ANDROID_TOOLS_DIR=\"\"" > .env
```
--------------------------------
### Configure Native Android App Signing
Source: https://docs.solanamobile.com/dapp-store/build-and-sign-an-apk
Sets up the signing configuration within the app's 'build.gradle' file for release builds. This includes specifying the keystore file, passwords, and key alias, ensuring that the application is properly signed when built for release.
```kotlin
android {
signingConfigs {
dappStore {
storeFile file("keystores/my-app-name.keystore")
storePassword "your_keystore_password"
keyAlias "my-app-name"
keyPassword "your_key_password"
}
}
buildTypes {
release {
signingConfig signingConfigs.dappStore
}
}
}
```
--------------------------------
### Display Name for Solana Mobile Wallet Adapter
Source: https://docs.solanamobile.com/get-started/web/ux-guidelines
This component illustrates how to customize the display name for the Solana Mobile Wallet Adapter (MWA) in a wallet list. It replaces the default adapter name with 'Use Installed Wallet' when MWA is detected, providing a clearer user experience on Android Web.
```typescript
import { SolanaMobileWalletAdapterWalletName } from '@solana-mobile/wallet-standard-mobile'
export default function WalletListItem({ wallet, onPress }){
// If we are showing MWA, use a descriptive display name.
const displayName = (wallet.adapter.name === SolanaMobileWalletAdapterWalletName)
? `Use Installed Wallet` : wallet.adapter.name
return (
);
};
```
--------------------------------
### Instantiate MobileWalletAdapter Client in Kotlin
Source: https://docs.solanamobile.com/get-started/kotlin/setup
Initializes the MobileWalletAdapter client with your dApp's identity metadata. This includes your dApp's URI, icon URI, and display name, which are shown to the user during wallet authorization. Ensure the URIs are correctly parsed.
```kotlin
import android.net.Uri
import com.solana.mobilewalletadapter.clientlib.*
// Define dApp's identity metadata
val solanaUri = Uri.parse("https://yourdapp.com")
val iconUri = Uri.parse("favicon.ico") // resolves to https://yourdapp.com/favicon.ico
val identityName = "Solana Kotlin dApp"
// Construct the client
val walletAdapter = MobileWalletAdapter(connectionIdentity = ConnectionIdentity(
identityUri = solanaUri,
iconUri = iconUri,
identityName = identityName
))
```
--------------------------------
### Submit dApp Update using CLI
Source: https://docs.solanamobile.com/dapp-store/publishing_releases
Command to submit an update for your dApp to the Solana dApp Publisher Portal. This command requires the path to your keypair and confirms compliance with store policies.
```bash
npx dapp-store publish update -k --requestor-is-authorized --complies-with-solana-dapp-store-policies
```
--------------------------------
### Sign and Send Solana Transactions
Source: https://docs.solanamobile.com/get-started/react-native/quickstart
Illustrates how to construct a transaction, request the wallet to sign it, and broadcast it to the network. It requires a connection object and the user's account address.
```typescript
import { useMobileWallet } from '@wallet-ui/react-native-web3js';
import { PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
function SendTransactionButton() {
const { account, signAndSendTransaction, connection } = useMobileWallet();
const handleSendTransaction = async () => {
if (!account) return;
const { blockhash } = await connection.getLatestBlockhash();
const transaction = new Transaction({
recentBlockhash: blockhash,
feePayer: new PublicKey(account.address),
}).add(
SystemProgram.transfer({
fromPubkey: new PublicKey(account.address),
toPubkey: new PublicKey('11111111111111111111111111111111'),
lamports: 1_000_000,
}),
);
const signature = await signAndSendTransaction(transaction);
console.log('Transaction signature:', signature);
};
return ;
}
```
--------------------------------
### Native Android: Configure Dual Signing (Kotlin)
Source: https://docs.solanamobile.com/recipes/general/publishing-from-google-play
Configures `build.gradle` for a Native Android project to support dual signing configurations for both Google Play and the dApp Store. It sets up separate `signingConfigs` and `productFlavors` for each store.
```kotlin
android {
signingConfigs {
googlePlay {
storeFile file("keystores/googleplay.keystore")
storePassword "your_googleplay_keystore_password"
keyAlias "googleplay"
keyPassword "your_googleplay_key_password"
}
dappStore {
storeFile file("keystores/my-app-name.keystore")
storePassword "your_dappstore_keystore_password"
keyAlias "my-app-name"
keyPassword "your_dappstore_key_password"
}
}
flavorDimensions "store"
productFlavors {
googlePlay {
dimension "store"
}
dappStore {
dimension "store"
}
}
buildTypes {
release {
productFlavors.googlePlay {
signingConfig signingConfigs.googlePlay
}
productFlavors.dappStore {
signingConfig signingConfigs.dappStore
}
}
}
}
```
--------------------------------
### Build dApp Store APK via Gradle
Source: https://docs.solanamobile.com/dapp-store/publishing-from-google-play
Executes the Gradle task to build a signed APK specifically for the dApp Store flavor.
```bash
./gradlew assembleDappStoreRelease
```
--------------------------------
### Fetch Latest Blockhash via RPC
Source: https://docs.solanamobile.com/android-native/building-json-rpc-requests
This snippet demonstrates how to use the Rpc20Driver to send a request to the Solana Devnet. It covers initializing the driver, constructing the request, handling potential errors, and deserializing the result into a Blockhash object.
```kotlin
fun getLatestBlockhash(): Blockhash {
val rpc = Rpc20Driver("https://api.devnet.solana.com", KtorHttpDriver())
val requestId = UUID.randomUUID().toString()
val request = createBlockhashRequest(commitment, requestId)
val response = rpc.makeRequest(request, BlockhashResponse.serializer())
response.error?.let { error ->
throw BlockhashException("Could not fetch latest blockhash: ${error.code}, ${error.message}")
}
val base58Blockhash = response.result?.value?.blockhash
return Blockhash.from(base58Blockhash ?: throw BlockhashException("Could not fetch latest blockhash: UnknownError"))
}
```