@vndrei21/stacks-wallet-kit-test-mobile
v1.0.2
Published
A React Native/Expo SDK for building Stacks blockchain applications with Google authentication and wallet management.
Downloads
27
Readme
@stacks-wallet-kit/mobile
A React Native/Expo SDK for building Stacks blockchain applications with Google authentication and wallet management.
Purpose
This SDK enables seamless Web2 authentication for mobile apps and provides easy wallet backup to a safe place without requiring users to store or remember their mnemonic phrase. It simplifies blockchain operations by handling the complexity of parsing arguments and data, allowing developers to focus on building their applications rather than managing low-level blockchain interactions.
The mobile SDK imports functionality from the @stacks-wallet-kit/core package, which is platform-agnostic and shared between this mobile SDK and the web extension SDK, ensuring consistency across platforms.
Installation
npm install @stacks-wallet-kit/mobile
# or
yarn add @stacks-wallet-kit/mobile
# or
pnpm add @stacks-wallet-kit/mobileNote: This package works with npm, yarn, and pnpm. Choose the package manager that fits your project.
Required Polyfills
The SDK requires Node.js polyfills to work in React Native/Expo environments. These polyfills are typically provided by your dependencies, but you may need to ensure they're properly initialized.
Required Polyfill Packages
The following polyfills are required for the SDK to function correctly:
react-native-get-random-values- Providescrypto.getRandomValues()for cryptographic operationsbuffer- Provides Node.jsBufferAPI (usually included transitively)expo-standard-web-crypto(Expo only) - Provides Web Crypto API polyfillfast-text-encoding- ProvidesTextEncoderandTextDecoderAPIs
Polyfill Setup
If you're using Expo Router, you can create an index.js file in your project root to ensure polyfills are loaded before your app starts:
// index.js
// Polyfills must be imported before expo-router/entry
// Order matters - altering it can cause initialization errors
// Import formatjs polyfills first (if using internationalization)
import '@formatjs/intl-getcanonicallocales/polyfill.js'
import '@formatjs/intl-locale/polyfill'
import '@formatjs/intl-numberformat/polyfill-force'
import '@formatjs/intl-pluralrules/polyfill'
// Crypto polyfills - must be before any crypto usage
import 'react-native-get-random-values'
import { polyfillWebCrypto } from 'expo-standard-web-crypto'
import 'fast-text-encoding'
// Initialize Web Crypto API polyfill
polyfillWebCrypto()
// Buffer polyfill - required for SDK operations
if (typeof global.Buffer === 'undefined') {
global.Buffer = require('buffer').Buffer
}
// Now import expo-router entry point
import 'expo-router/entry'Then update your package.json:
{
"main": "index.js"
}Note: If you're using expo-router/entry directly (without a custom entry point), the polyfills may be provided by your dependencies. However, if you encounter errors like ReferenceError: Buffer is not defined or initializebytes errors, you should set up the polyfills as shown above.
Installing Polyfill Packages
npm install react-native-get-random-values buffer
# For Expo projects:
npm install expo-standard-web-crypto fast-text-encodingTroubleshooting: If you encounter initialization errors on some platforms (e.g., Mac vs Linux), try:
- Clearing Metro bundler cache:
npx expo start --clear - Deleting
node_modulesand reinstalling dependencies - Ensuring all polyfills are installed and initialized before SDK usage
Quick Start
import { MobileClient, NetworkType } from '@stacks-wallet-kit/mobile'
const client = new MobileClient(
'your-web-client-id',
'your-ios-client-id',
NetworkType.Testnet,
{
scopes: ['email', 'profile'],
devnetUrl: 'http://10.0.2.2:3999',
}
)
client.setNetwork(NetworkType.Devnet)
const wallet = await client.createWallet() // Optional passphrase
const accounts = await client.getWalletAccounts()
const account = accounts[0]
const balance = await client.getBalance(account)MobileClient Configuration
Constructor Parameters
new MobileClient(
webClientId: string, // Required: Google OAuth web client ID
iosClientId: string, // Required: Google OAuth iOS client ID
network: NetworkType, // Required: Initial network (Mainnet, Testnet, or Devnet)
configOptions?: { // Optional: Configuration options
scopes?: string[] // Optional: Additional OAuth scopes
storageManager?: IStorageManager // Optional: Custom storage manager
mainnetUrl?: string // Optional: Custom mainnet API URL
testnetUrl?: string // Optional: Custom testnet API URL
devnetUrl?: string // Optional: Custom devnet API URL
}
)Default Configuration
Storage Manager:
- If not provided,
MobileClientautomatically selects a storage implementation:- Expo: Uses
SecureStore(Expo SecureStore) - React Native: Uses
KeyChainStorage(react-native-keychain)
- Expo: Uses
OAuth Scopes:
- Default scope:
https://www.googleapis.com/auth/drive.appdata(required for Google Drive backup) - Additional scopes can be provided via the
scopesparameter and will be merged with the default scope
Stacks API URLs:
- Mainnet:
https://api.hiro.so/ - Testnet:
https://api.testnet.hiro.so/ - Devnet:
http://10.0.2.2:3999/(Android emulator compatible)
Google Sign-In Configuration:
offlineAccess: true- Enables refresh token supportforceCodeForRefreshToken: true- Forces code exchange for refresh tokens
Internal Components
MobileClient automatically initializes the following components:
- Authentication:
GoogleAuthwith provided client IDs and scopes - Backup Manager:
BackupManagerwithGoogleBackupClient - Wallet Manager:
WalletManagerfor wallet operations - Encryption Manager:
EncryptionManagerfor encryption/decryption - Stacks Client:
StacksClientwith configured network and API URLs - Stacking Client:
StackingClientwith configured network
API Reference
Authentication
loginWithGoogle()
Sign in with Google and check if a wallet backup exists.
const result: { accessToken: string; hasBackup: boolean } =
await client.loginWithGoogle()signOut()
Sign out from Google authentication.
await client.signOut()Wallet
createWallet(passphrase?: string)
Create a new wallet with a generated mnemonic.
const wallet: Wallet = await client.createWallet() // Optional passphrasestoreExistingWallet(mnemonic: string, passphrase?: string)
Store an existing wallet from a mnemonic phrase.
const mnemonic: string = 'abandon abandon abandon ...'
const wallet: Wallet = await client.storeExistingWallet(mnemonic) // Optional passphrasegetWalletAccounts()
Get all accounts in the wallet.
const accounts: WalletAccount[] = await client.getWalletAccounts()createAccount()
Create a new account in the wallet.
const newAccount: WalletAccount = await client.createAccount()Backup
backupWallet(password: string)
Backup the wallet to Google Drive.
await client.backupWallet('wallet-password')retrieveWallet(password: string)
Retrieve a wallet from Google Drive backup.
const { wallet, mnemonic }: { wallet: Wallet; mnemonic: string } =
await client.retrieveWallet('wallet-password')deleteBackup(password: string)
Delete the wallet backup from Google Drive.
await client.deleteBackup('wallet-password')deleteBackupWithoutPassword()
Delete the wallet backup without requiring a password.
await client.deleteBackupWithoutPassword()Stacks
getBalance(account)
Get the STX balance for an account.
const accounts: WalletAccount[] = await client.getWalletAccounts()
const account: WalletAccount = accounts[0]
const balance: number = await client.getBalance(account) // Returns: numbersendStx(accountIndex, to, amount, network, memo?)
Send STX tokens to another address.
const txid: string = await client.sendStx(
0, // account index
'ST1AWHANXSGZ3SY8XQC2J7S18E22KJJW9B3JT2T54', // recipient
0.002, // amount in STX
NetworkType.Devnet, // network
'Test memo' // optional memo
) // Returns: stringtransferNFT(accountIndex, contractId, tokenId, to, network)
Transfer an NFT to another address. Designed for SIP-9 NFT trait compliant contracts.
const txid: string = await client.transferNFT(
0, // account index
'STJK0PY5JPPNR4PZWR7HVS7T92B1MKHQKBT5Q6MX.nft-test', // contract ID
'2', // token ID
'ST10WDE40SQ62CSWRE99NA0KWBZ74NNK4FNS9T19Q', // recipient
NetworkType.Devnet // network
) // Returns: stringtransferFT(accountIndex, contractId, amount, to, network)
Transfer fungible tokens to another address. Designed for SIP-10 FT trait compliant contracts.
const txid: string = await client.transferFT(
0, // account index
'STJK0PY5JPPNR4PZWR7HVS7T92B1MKHQKBT5Q6MX.ft-test', // contract ID
100 * 1000000, // amount in micro-units (100 tokens with 6 decimals)
'ST10WDE40SQ62CSWRE99NA0KWBZ74NNK4FNS9T19Q', // recipient
NetworkType.Devnet // network
) // Returns: stringmakeContractCall(contractAddress, functionName, functionArgs, postConditionMode?)
Make a contract call to any Stacks smart contract.
import {
uintCV,
standardPrincipalCV,
PostConditionMode,
ClarityValue,
} from '@stacks/transactions'
const contractAddress: string =
'STJK0PY5JPPNR4PZWR7HVS7T92B1MKHQKBT5Q6MX.nft-test'
const functionName: string = 'transfer'
const functionArgs: ClarityValue[] = [
uintCV('2'), // token-id
standardPrincipalCV(senderAddress), // sender
standardPrincipalCV(recipientAddress), // recipient
]
// With default post condition mode (PostConditionMode.Deny)
const txid: string = await client.makeContractCall(
contractAddress,
functionName,
functionArgs
) // Returns: string
// With custom post condition mode
const txid2: string = await client.makeContractCall(
contractAddress,
functionName,
functionArgs,
PostConditionMode.Allow // Optional: defaults to PostConditionMode.Deny
) // Returns: stringStacking
Solo Stacking
stackSTX(account, amount, lockPeriod, maxAmount, options?)
Stack STX to earn Bitcoin rewards.
Note: If options is not provided, the signature will be automatically generated by a backend service for mainnet and testnet networks.
const accounts: WalletAccount[] = await client.getWalletAccounts()
const account: WalletAccount = accounts[0]
// Basic usage (signature generated by backend)
const txid: string = await client.stackSTX(
account,
1000, // amount to stack in STX
1, // lock period in cycles
1000 // max amount in STX
) // Returns: string
// With custom signer options (skip backend signature generation)
const txid2: string = await client.stackSTX(account, 1000, 1, 1000, {
signerSignature: '0x...', // Optional: custom signer signature
signerKey: '0x...', // Optional: custom signer key
authId: '123', // Optional: custom auth ID
}) // Returns: stringstackExtend(account, extendCount, maxAmount, options?)
Extend the stacking lock period.
Note: If options is not provided, the signature will be automatically generated by a backend service for mainnet and testnet networks.
const accounts: WalletAccount[] = await client.getWalletAccounts()
const account: WalletAccount = accounts[0]
// Basic usage (signature generated by backend)
const txid: string = await client.stackExtend(
account,
2, // number of cycles to extend
1000 // max amount in STX
) // Returns: string
// With custom signer options (skip backend signature generation)
const txid2: string = await client.stackExtend(account, 2, 1000, {
signerSignature: '0x...', // Optional: custom signer signature
signerKey: '0x...', // Optional: custom signer key
authId: '123', // Optional: custom auth ID
}) // Returns: stringstackIncrease(account, increaseBy, maxAmount, currentLockPeriod, options?)
Increase the amount being stacked.
Note: If options is not provided, the signature will be automatically generated by a backend service for mainnet and testnet networks.
const accounts: WalletAccount[] = await client.getWalletAccounts()
const account: WalletAccount = accounts[0]
// Basic usage (signature generated by backend)
const txid: string = await client.stackIncrease(
account,
500, // amount to increase by in STX
1500, // max amount in STX
1 // current lock period
) // Returns: string
// With custom signer options (skip backend signature generation)
const txid2: string = await client.stackIncrease(account, 500, 1500, 1, {
signerSignature: '0x...', // Optional: custom signer signature
signerKey: '0x...', // Optional: custom signer key
authId: '123', // Optional: custom auth ID
}) // Returns: stringStacking with a Pool
delegateSTX(account, amount, delegateTo, untilBurnHeight?)
Delegate STX to a stacking pool.
import { StackingPool } from '@stacks-wallet-kit/core'
const pool: StackingPool = {
name: 'Pool Name',
address: 'SP...',
}
const accounts: WalletAccount[] = await client.getWalletAccounts()
const account: WalletAccount = accounts[0]
const txid: string = await client.delegateSTX(
account,
1000, // amount to delegate in STX
pool, // stacking pool
100000 // optional: until burn height
) // Returns: stringrevokeDelegation(account)
Revoke STX delegation from a stacking pool.
const accounts: WalletAccount[] = await client.getWalletAccounts()
const account: WalletAccount = accounts[0]
const txid: string = await client.revokeDelegation(account) // Returns: stringNetwork
setNetwork(network)
Set the network for all operations.
import { NetworkType } from '@stacks-wallet-kit/mobile'
client.setNetwork(NetworkType.Mainnet)
client.setNetwork(NetworkType.Testnet)
client.setNetwork(NetworkType.Devnet)Configuration
Android Emulator Setup
When testing on Android emulator, use 10.0.2.2 instead of localhost for devnet URLs:
const client: MobileClient = new MobileClient(
'web-client-id',
'ios-client-id',
NetworkType.Devnet,
{
devnetUrl: 'http://10.0.2.2:3999', // Android emulator host
}
)Custom Storage Manager
You can provide a custom storage manager by implementing the IStorageManager interface from the @stacks-wallet-kit/core package. Make sure to install the core package:
npm install @stacks-wallet-kit/core
# or
yarn add @stacks-wallet-kit/core
# or
pnpm add @stacks-wallet-kit/coreimport { IStorageManager } from '@stacks-wallet-kit/core'
class CustomStorage implements IStorageManager {
async setItem<T>(key: string, value: T): Promise<void> {
// Your implementation
}
async getItem<T>(key: string): Promise<T | null> {
// Your implementation
}
async removeItem(key: string): Promise<void> {
// Your implementation
}
async clear(): Promise<void> {
// Your implementation
}
}
const client = new MobileClient(
'web-client-id',
'ios-client-id',
NetworkType.Testnet,
{
storageManager: new CustomStorage(),
}
)Types
NetworkType
enum NetworkType {
Mainnet = 'mainnet',
Testnet = 'testnet',
Devnet = 'devnet',
}WalletAccount
interface WalletAccount {
index: number
publicKey: string
addresses: {
mainnet: string
testnet: string
}
}StackingPool
interface StackingPool {
name: string
address: string
}Examples
Complete Wallet Flow
import { MobileClient, NetworkType } from '@stacks-wallet-kit/mobile'
import { Wallet, WalletAccount } from '@stacks-wallet-kit/core'
async function walletFlow(): Promise<void> {
const client: MobileClient = new MobileClient(
'web-client-id',
'ios-client-id',
NetworkType.Devnet,
{ devnetUrl: 'http://10.0.2.2:3999' }
)
const { hasBackup }: { accessToken: string; hasBackup: boolean } =
await client.loginWithGoogle()
let wallet: Wallet
if (hasBackup) {
const result: { wallet: Wallet; mnemonic: string } =
await client.retrieveWallet('password')
wallet = result.wallet
} else {
wallet = await client.createWallet() // Optional passphrase
await client.backupWallet('password')
}
const accounts: WalletAccount[] = await client.getWalletAccounts()
const account: WalletAccount = accounts[0]
const balance: number = await client.getBalance(account)
if (balance > 0.01) {
const txid: string = await client.sendStx(
0,
'ST1AWHANXSGZ3SY8XQC2J7S18E22KJJW9B3JT2T54',
0.01,
NetworkType.Devnet,
'Test payment'
)
}
}NFT Transfer Example
import { MobileClient, NetworkType } from '@stacks-wallet-kit/mobile'
import { WalletAccount } from '@stacks-wallet-kit/core'
async function transferNFT(): Promise<void> {
const client: MobileClient = new MobileClient(
'web-client-id',
'ios-client-id',
NetworkType.Devnet
)
const accounts: WalletAccount[] = await client.getWalletAccounts()
const account: WalletAccount = accounts[0]
const txid: string = await client.transferNFT(
account.index,
'SP1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ.my-nft',
'1',
'ST1AWHANXSGZ3SY8XQC2J7S18E22KJJW9B3JT2T54',
NetworkType.Devnet
)
}Custom Contract Call Example
import { MobileClient, NetworkType } from '@stacks-wallet-kit/mobile'
import {
uintCV,
standardPrincipalCV,
ClarityValue,
PostConditionMode,
} from '@stacks/transactions'
async function customContractCall(): Promise<void> {
const client: MobileClient = new MobileClient(
'web-client-id',
'ios-client-id',
NetworkType.Devnet
)
const contractAddress: string =
'SP1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ.my-contract'
const functionName: string = 'my-function'
const functionArgs: ClarityValue[] = [
uintCV(100),
standardPrincipalCV('ST1AWHANXSGZ3SY8XQC2J7S18E22KJJW9B3JT2T54'),
]
// With optional post condition mode
const txid: string = await client.makeContractCall(
contractAddress,
functionName,
functionArgs,
PostConditionMode.Allow
)
}