### Complete Dynamic SDK Setup Example in Swift Source: https://www.dynamic.xyz/docs/swift/sdk-reference/client-configuration This example demonstrates the complete setup for the Dynamic SDK in a SwiftUI application. It includes initializing the SDK with client properties and managing authentication state. ```swift import SwiftUI import DynamicSDKSwift import Combine @main struct MyApp: App { init() { _ = DynamicSDK.initialize( props: ClientProps( environmentId: "YOUR_ENV_ID", appLogoUrl: "https://example.com/logo.png", appName: "My App", redirectUrl: "myapp://", appOrigin: "https://example.com", logLevel: .info ) ) } var body: some Scene { WindowGroup { RootView() } } } struct RootView: View { @State private var isAuthenticated = false @State private var cancellables = Set() private let sdk = DynamicSDK.instance() var body: some View { Group { if isAuthenticated { HomeView() } else { LoginView() } } .onAppear { // Check current state isAuthenticated = sdk.auth.authenticatedUser != nil // Listen for changes sdk.auth.authenticatedUserChanges .receive(on: DispatchQueue.main) .sink { user in isAuthenticated = user != nil } .store(in: &cancellables) } } } ``` -------------------------------- ### Full Integration Example: Agent Wallet Setup and Trading Source: https://www.dynamic.xyz/docs/recipes/integrations/hyperliquid-agent-wallets This comprehensive example demonstrates the complete workflow for setting up and using an agent wallet on Hyperliquid. It covers master wallet creation, agent wallet generation, agent approval, listing active agents, and placing a limit order. Ensure necessary environment variables and helper functions are available. ```typescript import { getOrCreateMasterWallet } from './masterWallet'; import { createAgentWallet } from './agentWallet'; import { approveAgent } from './approveAgent'; import { listActiveAgents, placeLimitOrder } from './trade'; const IS_TESTNET = process.env.IS_TESTNET === 'true'; // 1. Get or create the MPC master wallet const master = await getOrCreateMasterWallet(); const masterAddress = master.accountAddress; // 2. Create a new agent keypair (store privateKey in secrets manager) const agent = createAgentWallet(); // 3. Approve the agent on Hyperliquid (idempotent) await approveAgent({ masterAddress, agentAddress: agent.account.address, agentName: 'MyTradingBot', isTestnet: IS_TESTNET, }); // 4. List active agents const agents = await listActiveAgents({ masterAddress, isTestnet: IS_TESTNET }); console.log('Active agents:', agents); // 5. Place an order through the agent await placeLimitOrder({ agentPrivateKey: agent.privateKey, asset: 0, // BTC-USD perp isBuy: true, price: '95000', size: '0.001', isTestnet: IS_TESTNET, }); ``` -------------------------------- ### Full useWalletDelegation Hook Usage Example Source: https://www.dynamic.xyz/docs/react/reference/hooks/embedded-wallets/usewalletdelegation An example demonstrating the initialization of the delegation process, checking if the prompt should be shown, getting wallet delegation status, and handling user interactions like denying or dismissing the prompt. ```typescript import { useWalletDelegation } from '@dynamic-labs/sdk-react-core'; const MyComponent = () => { const { initDelegationProcess, shouldPromptWalletDelegation, getWalletsDelegatedStatus, denyWalletDelegation, dismissDelegationPrompt, delegatedAccessEnabled, requiresDelegation } = useWalletDelegation(); const handleDelegateWallet = async () => { try { await initDelegationProcess(); console.log('Wallet delegation successful!'); } catch (error) { console.error('Failed to delegate wallet:', error); } }; // Automatically prompt on mount if needed useEffect(() => { if (shouldPromptWalletDelegation()) { initDelegationProcess(); } }, []); // Check delegation status of wallets const walletStatuses = getWalletsDelegatedStatus(); const hasDelegatedWallets = walletStatuses.some(w => w.status === 'delegated'); return (
{delegatedAccessEnabled && !hasDelegatedWallets && (

Enable delegated access for a better experience

)} {requiresDelegation && !hasDelegatedWallets && (

This app requires wallet delegation to function

)}
); }; ``` -------------------------------- ### Install Bitcoin Dependencies with pnpm Source: https://www.dynamic.xyz/docs/node/quickstart Install the Bitcoin-specific SDK package and core dependencies using `pnpm`. This example shows the minimal setup for Bitcoin integration. ```bash pnpm add @dynamic-labs-wallet/node-btc @dynamic-labs-wallet/core pnpm add -D tsx ``` -------------------------------- ### First Dynamic CLI Commands Source: https://www.dynamic.xyz/docs/cli/index Basic commands to get started with the Dynamic CLI after installation. These include logging in, checking status, and listing settings. ```sh dyn auth login # authenticate through your browser ``` ```sh dyn status # show the active organization, project, and environment ``` ```sh dyn settings list # discover every configurable project setting ``` -------------------------------- ### Complete Network Management Example Source: https://www.dynamic.xyz/docs/unity/wallets/general/network-management A comprehensive example demonstrating how to list available EVM and Solana networks and switch to the Polygon network using a wallet. This script requires a wallet to be initialized and available. ```csharp using DynamicSDK.Core; using UnityEngine; using System.Linq; public class NetworkManager : MonoBehaviour { private BaseWallet _wallet; private void Start() { _wallet = DynamicSDK.Instance.Wallets.UserWallets.FirstOrDefault(); if (_wallet != null) { ListAvailableNetworks(); } } public void ListAvailableNetworks() { Debug.Log("Available EVM Networks:"); foreach (var network in DynamicSDK.Instance.Networks.Evm.AvailableNetworks) { Debug.Log($" {network.Name} (Chain ID: {network.ChainId})"); } Debug.Log("Available Solana Networks:"); foreach (var network in DynamicSDK.Instance.Networks.Solana.AvailableNetworks) { Debug.Log($" {network.Name}"); } } public async void SwitchToPolygon() { if (_wallet == null || _wallet.Chain.ToUpper() != "EVM") { Debug.LogError("No EVM wallet available"); return; } var polygonNetwork = DynamicSDK.Instance.Networks.Evm.AvailableNetworks .FirstOrDefault(n => n.Name.Contains("Polygon")); if (polygonNetwork == null) { Debug.LogError("Polygon network not found"); return; } try { await DynamicSDK.Instance.Wallets.SwitchNetwork(_wallet, polygonNetwork.ChainId.ToString()); Debug.Log($"Switched to {polygonNetwork.Name}"); } catch (System.Exception e) { Debug.LogError($"Failed to switch: {e.Message}"); } } } ``` -------------------------------- ### Basic Viem Wallet Client Setup Source: https://www.dynamic.xyz/docs/node/wallets/server-wallets/viem-wallet-client Instantiate DynamicEvmWalletClient, authenticate, and then get a Viem WalletClient for a specific account and chain. This is the fundamental way to start interacting with EVM chains. ```typescript import { DynamicEvmWalletClient } from '@dynamic-labs-wallet/node-evm'; const evmClient = new DynamicEvmWalletClient({ environmentId: 'your-environment-id', }); await evmClient.authenticateApiToken('your-api-token'); // Get a Viem wallet client const walletClient = await evmClient.getWalletClient({ accountAddress: '0x1234567890123456789012345678901234567890', chainId: 11155111, // Sepolia rpcUrl: 'https://ethereum-sepolia-rpc.publicnode.com', }); // Use the wallet client const chainId = await walletClient.getChainId(); console.log('Chain ID:', chainId); ``` -------------------------------- ### Complete EVM Transaction Example Source: https://www.dynamic.xyz/docs/swift/sdk-reference/ethereum-integration This Swift code demonstrates how to get an EVM wallet, fetch the current gas price, create an Ethereum transaction, and send it using the Dynamic SDK. Ensure you have an EVM wallet configured in your Dynamic setup. ```swift import DynamicSDKSwift import SwiftBigInt let sdk = DynamicSDK.instance() // Get EVM wallet guard let wallet = sdk.wallets.userWallets.first(where: { $0.chain.uppercased() == "EVM" }) else { print("No EVM wallet found") return } // Get gas price let chainId = 84532 // Base Sepolia let client = sdk.evm.createPublicClient(chainId: chainId) let gasPrice = try await client.getGasPrice() // Create and send transaction let transaction = EthereumTransaction( from: wallet.address, to: "0xRecipient...", value: BigUInt(10000000000000000), // 0.01 ETH gas: BigUInt(21000), maxFeePerGas: gasPrice * 2, maxPriorityFeePerGas: gasPrice ) let txHash = try await sdk.evm.sendTransaction( transaction: transaction, wallet: wallet ) print("Transaction sent: \(txHash)") ``` -------------------------------- ### Install Delegation Toolkit (npm) Source: https://www.dynamic.xyz/docs/react-native/smart-wallets/smart-wallet-providers/metamask Install the Metamask Delegation Toolkit using npm. This is the first step in setting up smart accounts. ```bash npm install @metamask/delegation-toolkit ``` -------------------------------- ### Install Dynamic SDK Packages Source: https://www.dynamic.xyz/docs/react/reference/quickstart Install the core SDK package and the Ethereum connector. ```bash npm i @dynamic-labs/sdk-react-core @dynamic-labs/ethereum ``` -------------------------------- ### Complete BTC SDK Example Usage Source: https://www.dynamic.xyz/docs/node/btc/example-usage Demonstrates creating Native SegWit and Taproot wallets, deriving addresses, fetching all wallets, and signing messages using BIP-322. Wallet information is saved to btcWallet.json. ```typescript // Example usage demonstrating all available functions async function main() { try { console.log("Starting BTC Client Demo...\n"); // Initialize the BTC client const btcClient = await authenticatedBtcClient(); console.log("BTC client authenticated successfully\n"); // 1. Create a new Native SegWit Bitcoin wallet console.log("Creating new Native SegWit wallet..."); const segwitWallet = await btcClient.createWalletAccount({ thresholdSignatureScheme: ThresholdSignatureScheme.TWO_OF_TWO, onError: (error: Error) => { console.error("Native SegWit wallet creation error:", error); }, backUpToDynamic: true, bitcoinConfig: { addressType: BitcoinAddressType.NATIVE_SEGWIT, }, }); console.log("Native SegWit wallet created:", segwitWallet.accountAddress); console.log("Public key hex:", segwitWallet.publicKeyHex); // Save wallet info to file fs.writeFileSync("btcWallet.json", JSON.stringify(segwitWallet, null, 2)); console.log("Wallet saved to btcWallet.json\n"); // 2. Create a Taproot wallet console.log("Creating Taproot wallet..."); const taprootWallet = await btcClient.createWalletAccount({ thresholdSignatureScheme: ThresholdSignatureScheme.TWO_OF_TWO, onError: (error: Error) => { console.error("Taproot wallet creation error:", error); }, backUpToDynamic: true, bitcoinConfig: { addressType: BitcoinAddressType.TAPROOT, }, }); console.log("Taproot wallet created:", taprootWallet.accountAddress); // 3. Derive address from public key console.log("\nDeriving BTC address from public key..."); try { const { accountAddress } = btcClient.deriveAccountAddress({ rawPublicKey: segwitWallet.rawPublicKey, addressType: BitcoinAddressType.NATIVE_SEGWIT, }); console.log("Derived address:", accountAddress); } catch (error) { console.log("Could not derive address:", error); } // 4. Get all Bitcoin wallets console.log("\nGetting all Bitcoin wallets..."); try { const allWallets = await btcClient.getBitcoinWallets(); console.log("Found", allWallets.length, "Bitcoin wallets"); allWallets.forEach(wallet => { console.log(` - ${wallet.accountAddress}`); }); } catch (error) { console.log("Could not retrieve all wallets:", error); } // 5. Sign a message (BIP-322) console.log("\nSigning a message with BIP-322..."); try { const message = "Hello, Bitcoin! This is a test message from Dynamic BTC wallet."; const signature = await btcClient.signMessage({ message, accountAddress: segwitWallet.accountAddress, network: BitcoinNetwork.MAINNET, }); console.log("Message signed successfully (BIP-322)"); console.log("Signature (base64):", signature.substring(0, 50) + "..."); } catch (error) { console.log("Message signing failed:", error instanceof Error ? error.message : String(error)); } // 6. Sign a message with Taproot wallet console.log("\nSigning a message with Taproot wallet..."); try { const message = "Taproot signature test"; const signature = await btcClient.signMessage({ message, accountAddress: taprootWallet.accountAddress, network: BitcoinNetwork.MAINNET, }); console.log("Taproot message signed successfully"); console.log("Signature (base64):", signature.substring(0, 50) + "..."); } catch (error) { console.log("Taproot message signing failed:", error instanceof Error ? error.message : String(error)); } } catch (error) { console.error("An unexpected error occurred:", error); } } main(); ``` -------------------------------- ### Install Iframe Setup Package Source: https://www.dynamic.xyz/docs/react/reference/iframe Install the necessary package for iframe integration using npm. ```bash npm install @dynamic-labs/iframe-setup ``` -------------------------------- ### Run the Application Source: https://www.dynamic.xyz/docs/recipes/integrations/swaps/mayan Starts the development server for the application. Access the application at the specified local URL. ```bash pnpm dev ``` -------------------------------- ### Install Core Dependencies with pnpm Source: https://www.dynamic.xyz/docs/node/quickstart Install the core SDK packages and essential utilities like `viem` and `tsx` using `pnpm`. This example demonstrates installing packages for EVM and SVM support. ```bash pnpm add @dynamic-labs-wallet/node-evm @dynamic-labs-wallet/node-svm @dynamic-labs-wallet/core viem pnpm add -D tsx ``` -------------------------------- ### Start Development Server Source: https://www.dynamic.xyz/docs/react/smart-wallets/smart-wallet-providers/crossmint Command to launch the development server for testing the integration. Visit the provided URL to interact with the application. ```bash npm run dev ``` -------------------------------- ### Get Installation Link for Current Platform Source: https://www.dynamic.xyz/docs/javascript/reference/wallets/get-wallet-options-catalogue Retrieves the most relevant installation URL for the user's current platform from a list of installation URLs. Returns `undefined` if no matching platform is found. Useful for install-only wallets or fallback installation paths. ```typescript import { getInstallationLinkForCurrentPlatform } from '@dynamic-labs-sdk/client'; const url = getInstallationLinkForCurrentPlatform({ installationUrls: walletOption.installationUrls, }); if (url) { window.open(url, '_blank'); } ``` -------------------------------- ### Install Dynamic Client Package Source: https://www.dynamic.xyz/docs/javascript/authentication-methods/external-wallets Install the Dynamic client package using npm. This is the first step before initializing the client. ```bash npm install @dynamic-labs-sdk/client ``` -------------------------------- ### Scaffold a new serverless function Source: https://www.dynamic.xyz/docs/recipes/webhooks-serverless Run the Serverless setup command to scaffold a new Node.js HTTP API function. This command will guide you through the initial setup. ```bash serverless ``` -------------------------------- ### Complete Token Balance Loading Example Source: https://www.dynamic.xyz/docs/unity/wallets/general/token-balances An example script demonstrating how to load native and token balances for all user wallets. It iterates through wallets, fetches native balances, and then queries token balances for each wallet's chain and network. ```csharp using DynamicSDK.Core; using UnityEngine; using System.Collections.Generic; public class BalanceManager : MonoBehaviour { public async void LoadAllBalances() { var wallets = DynamicSDK.Instance.Wallets.UserWallets; foreach (var wallet in wallets) { // Get native balance string balance = await DynamicSDK.Instance.Wallets.GetBalance(wallet); Debug.Log($" ``` -------------------------------- ### Using the PWA Install Hook in a React Component Source: https://www.dynamic.xyz/docs/recipes/frameworks/react-pwa This example shows how to import and use the 'useInstallPWA' hook within a React component to display an install button. Ensure the component is rendered in a context where the PWA can be installed (e.g., served over HTTPS). ```tsx import { DynamicWidget } from "@dynamic-labs/sdk-react-core"; import { useInstallPWA } from "./useInstallPWA"; function App() { const installPWA = useInstallPWA(); return ( <> ); } export default App; ``` -------------------------------- ### Start Wallet Backup Process Source: https://www.dynamic.xyz/docs/react/reference/hooks/embedded-wallets/usewalletbackup Initiates the sequential backup process for wallets with progress tracking. This example shows how to start the backup and how to retry from a specific index if a failure occurs. ```typescript const { startBackup, backupState } = useWalletBackup(); await startBackup(() => { console.log('All wallets backed up!'); }); // Retry from failed index if (backupState.hasError && backupState.failedIndex !== null) { await startBackup(undefined, backupState.failedIndex); } ``` -------------------------------- ### Initialize and Use Dynamic XYZ SDK in SwiftUI Source: https://www.dynamic.xyz/docs/swift/sdk-reference/overview Demonstrates the complete setup for a SwiftUI application using the Dynamic XYZ SDK. This includes initializing the SDK with client properties and managing authentication state. ```swift import DynamicSDKSwift import SwiftUI import Combine @main struct MyApp: App { init() { _ = DynamicSDK.initialize( props: ClientProps( environmentId: "YOUR_ENV_ID", appLogoUrl: "https://example.com/logo.png", appName: "My App", redirectUrl: "myapp://", appOrigin: "https://example.com" ) ) } var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @State private var isAuthenticated = false @State private var cancellables = Set() private let sdk = DynamicSDK.instance() var body: some View { Group { if isAuthenticated { HomeView() } else { LoginView() } } .onAppear { isAuthenticated = sdk.auth.authenticatedUser != nil sdk.auth.authenticatedUserChanges .receive(on: DispatchQueue.main) .sink { isAuthenticated = user != nil } .store(in: &cancellables) } } } struct LoginView: View { var body: some View { Button("Sign In") { DynamicSDK.instance().ui.showAuth() } } } struct HomeView: View { private let sdk = DynamicSDK.instance() var body: some View { VStack { Text("Welcome!") Button("View Profile") { sdk.ui.showUserProfile() } Button("Logout") { Task { try await sdk.auth.logout() } } } } } ``` -------------------------------- ### Complete SVM SDK Example Usage Source: https://www.dynamic.xyz/docs/node/svm/example-usage Demonstrates creating an SVM wallet, retrieving wallet details, listing all SVM wallets, signing a message, and preparing a Solana transaction for signing. ```typescript // Example usage demonstrating all available functions async function main() { try { console.log("šŸš€ Starting SVM Client Demo...\n"); // Initialize the SVM client const svmClient = await authenticatedSvmClient(); console.log("āœ… SVM client authenticated successfully\n"); // 1. Create a new SVM wallet console.log("šŸ“ Creating new SVM wallet..."); const svmWallet = await svmClient.createWalletAccount({ thresholdSignatureScheme: ThresholdSignatureScheme.TWO_OF_TWO, onError: (error: Error) => { console.error("āŒ SVM wallet creation error:", error); }, backUpToDynamic: true, }); console.log("āœ… SVM wallet created:", svmWallet.accountAddress); console.log("externalServerKeyShares:", svmWallet.externalServerKeyShares); console.log("rawPublicKey:", svmWallet.rawPublicKey); // Save wallet info to file fs.writeFileSync("svmWallet.json", JSON.stringify(svmWallet, null, 2)); console.log("šŸ’¾ Wallet saved to svmWallet.json\n"); // 2. Get wallet information console.log("šŸ” Getting wallet details..."); try { const walletDetails = await svmClient.getWallet({ accountAddress: svmWallet.accountAddress, }); console.log("āœ… Wallet details retrieved:", walletDetails); } catch (error) { console.log("āš ļø Could not retrieve wallet details:", error); } // 3. Get all SVM wallets console.log("\nšŸ“‹ Getting all SVM wallets..."); try { const allWallets = await svmClient.getSvmWallets(); console.log("āœ… Found", allWallets.length, "SVM wallets"); } catch (error) { console.log("āš ļø Could not retrieve all wallets:", error); } // 4. Sign a message console.log("\nāœļø Signing a message..."); try { const message = "Hello, Solana! This is a test message from Dynamic SVM wallet."; const signedMessage = await svmClient.signMessage({ accountAddress: svmWallet.accountAddress, message, }); console.log("āœ… Message signed successfully"); console.log("Signature:", signedMessage); } catch (error) { console.log("āš ļø Message signing failed:", error instanceof Error ? error.message : String(error)); } // 5. Sign a transaction (Solana transfer example) console.log("\nšŸ’ø Preparing Solana transaction..."); const connection = new Connection("https://api.devnet.solana.com", "confirmed"); try { const amountInSol = 0.001; const recipientAddress = "EukgLDgaWNQRLemZSHK8Wc9EGhPhbG3wL9a1mxa3LHg6"; // Create transaction const transaction = new Transaction().add( SystemProgram.transfer({ fromPubkey: new PublicKey(svmWallet.accountAddress), toPubkey: new PublicKey(recipientAddress), lamports: amountInSol * LAMPORTS_PER_SOL, }) ); // Get latest blockhash const { blockhash } = await connection.getLatestBlockhash(); transaction.recentBlockhash = blockhash; transaction.feePayer = new PublicKey(svmWallet.accountAddress); console.log("šŸ“ Transaction prepared, signing with SVM wallet..."); // Sign the transaction — returns base58 Ed25519 signature (not the full signed tx) const signatureBase58 = await svmClient.signTransaction({ walletMetadata: svmWalletMetadata, // Assuming svmWalletMetadata is defined elsewhere transaction, }); // To broadcast: decode the signature and add it back to the transaction // import { decodeBase58, addSignatureToTransaction } from '@dynamic-labs-wallet/node-svm'; // const signedTx = addSignatureToTransaction({ transaction, signature: decodeBase58(signatureBase58), signerPublicKey }); // const txid = await connection.sendRawTransaction(signedTx.serialize()); } catch (error) { console.log("āš ļø Solana transaction signing failed:", error instanceof Error ? error.message : String(error)); } console.log("\nšŸŽ‰ SVM Client Demo Finished."); } catch (error) { console.error("āŒ An unexpected error occurred:", error); } } // Placeholder for svmWalletMetadata, assuming it's defined elsewhere in a real scenario const svmWalletMetadata = { accountAddress: "YOUR_SVM_WALLET_ADDRESS", // Replace with actual wallet address externalServerKeyShares: {}, rawPublicKey: "", thresholdSignatureScheme: ThresholdSignatureScheme.TWO_OF_TWO, backUpToDynamic: true, }; // Call the main function to run the example // main(); ``` -------------------------------- ### Complete MFA Setup Flow (ViewModel) Source: https://www.dynamic.xyz/docs/kotlin/mfa A comprehensive example demonstrating the MFA setup flow within a ViewModel. This includes generating a secret, updating the verification code, and verifying the device. ```kotlin import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.dynamic.sdk.android.DynamicSDK import com.dynamic.sdk.android.Models.MfaAddDevice import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class MfaSetupViewModel(private val sdk: DynamicSDK) : ViewModel() { private val _deviceInfo = MutableStateFlow(null) val deviceInfo: StateFlow = _deviceInfo private val _verificationCode = MutableStateFlow("") val verificationCode: StateFlow = _verificationCode private val _isLoading = MutableStateFlow(false) val isLoading: StateFlow = _isLoading private val _error = MutableStateFlow(null) val error: StateFlow = _error fun generateSecret() { viewModelScope.launch { _isLoading.value = true _error.value = null try { val device = sdk.mfa.addDevice("totp") _deviceInfo.value = device } catch (e: Exception) { _error.value = "Failed to generate secret: ${e.message}" } _isLoading.value = false } } fun updateCode(code: String) { _verificationCode.value = code } fun verifyDevice(onSuccess: () -> Unit) { viewModelScope.launch { _isLoading.value = true _error.value = null try { sdk.mfa.verifyDevice(_verificationCode.value.trim(), "totp") onSuccess() } catch (e: Exception) { _error.value = "Verification failed: ${e.message}" } _isLoading.value = false } } } ``` -------------------------------- ### Complete Example with Wallets Source: https://www.dynamic.xyz/docs/flutter/quickstart A complete Flutter example demonstrating integration with Dynamic SDK, including wallet functionalities. This snippet serves as a starting point for building authenticated applications with wallet support. ```dart import 'package:dynamic_sdk/dynamic_sdk.dart'; import 'package:flutter/material.dart'; class HomeView extends StatelessWidget { const HomeView({super.key}); ``` -------------------------------- ### Complete Example: Create and Unlock Password-Protected Wallet Source: https://www.dynamic.xyz/docs/react/wallets/embedded-wallets/mpc/password-encryption Demonstrates the recommended pattern for custom UI implementations: checking wallet state, unlocking if necessary, and then signing a message. This example includes creating a new password-protected wallet and unlocking an existing one. ```typescript import { useState } from 'react'; import { useDynamicWaas, useWalletPassword } from "@dynamic-labs/sdk-react-core"; import { ChainEnum } from "@dynamic-labs/sdk-api-core"; const PasswordProtectedWallet = () => { const [password, setPassword] = useState(''); const { createWalletAccount, getWaasWallets } = useDynamicWaas(); const { unlockWallet, checkWalletLockState, state } = useWalletPassword(); const createWallet = async () => { const wallet = await createWalletAccount([ChainEnum.Evm], password); console.log('Wallet created:', wallet); }; const unlock = async () => { const wallets = await getWaasWallets(); if (wallets.length === 0) return; // 1. Check if wallet is locked const recoveryState = await checkWalletLockState({ accountAddress: wallets[0].address, chainName: ChainEnum.Evm, }); if (recoveryState?.isPasswordEncrypted) { // 2. Unlock with the user's password await unlockWallet({ accountAddress: wallets[0].address, chainName: ChainEnum.Evm, password, }); } // 3. Wallet is now ready for signing, transactions, etc. console.log('Wallet ready'); }; return (
setPassword(e.target.value)} placeholder="Enter password" /> {state.error &&

Error: {state.error}

}
); }; ``` -------------------------------- ### Initialize Project and Install Dependencies with npm Source: https://www.dynamic.xyz/docs/recipes/integrations/telegram/telegram-server-wallets-bots Initializes a new project using npm and installs necessary libraries for the Telegram bot. ```bash # Initialize the project npm init -y # Install dependencies npm install @dynamic-labs-wallet/node-evm @supabase/supabase-js grammy viem npm install --save-dev typescript @types/node ``` -------------------------------- ### Get Latest Blockhash Example Source: https://www.dynamic.xyz/docs/flutter/sdk-reference/data-types Demonstrates how to fetch the latest blockhash and its validity information from a Solana connection. ```dart final connection = sdk.solana.createConnection(); final result = await connection.getLatestBlockhash(); print('Blockhash: ${result.blockhash}'); print('Valid until block: ${result.lastValidBlockHeight}'); ``` -------------------------------- ### Complete Wallet Management Example Source: https://www.dynamic.xyz/docs/swift/sdk-reference/wallet-management A comprehensive example demonstrating wallet management within a SwiftUI application. This includes listening for wallet updates, displaying balances, and signing messages. ```swift import SwiftUI import DynamicSDKSwift import Combine @MainActor class WalletViewModel: ObservableObject { @Published var wallets: [BaseWallet] = [] @Published var selectedWallet: BaseWallet? @Published var balance: String? @Published var isLoading = false private let sdk = DynamicSDK.instance() private var cancellables = Set() func startListening() { // Get current wallets wallets = sdk.wallets.userWallets selectedWallet = wallets.first // Listen for updates sdk.wallets.userWalletsChanges .receive(on: DispatchQueue.main) .sink { self?.wallets = newWallets if self?.selectedWallet == nil { self?.selectedWallet = newWallets.first } } .store(in: &cancellables) } func refreshBalance() { guard let wallet = selectedWallet else { return } isLoading = true Task { do { balance = try await sdk.wallets.getBalance(wallet: wallet) } catch { print("Balance error: \(error)") } isLoading = false } } func signMessage(_ message: String) async -> String? { guard let wallet = selectedWallet else { return nil } do { return try await sdk.wallets.signMessage(wallet: wallet, message: message) } catch { print("Sign error: \(error)") return nil } } } ``` -------------------------------- ### Get Wallet Options Catalogue Source: https://www.dynamic.xyz/docs/javascript/reference/wallets/get-wallet-options-catalogue Fetches a catalogue of all external wallet options a user can sign in with. This includes installed providers, and optionally mobile-specific options like deep linking and install links when `includeMobileOptions` is set to `true`. ```APIDOC ## getWalletOptionsCatalogue ### Description Retrieves a unified list of external wallet options for user sign-in, simplifying the process of rendering a wallet picker. ### Method Signature `getWalletOptionsCatalogue({ includeMobileOptions?: boolean })` ### Parameters #### Query Parameters - **includeMobileOptions** (boolean) - Optional - Set to `true` to include mobile-specific connection options such as URI-based connections (deeplinking and QR code), in-app browser entries, and install links. Defaults to `false`. ### Returns An ordered list of wallet option objects, where each object contains connection details for a specific wallet. ### Example Usage ```typescript import { getWalletOptionsCatalogue } from '@dynamic-labs-sdk/client'; const walletOptions = await getWalletOptionsCatalogue({ includeMobileOptions: true, }); for (const walletOption of walletOptions) { console.log(walletOption.name, walletOption.connectionOptions); } ``` ``` -------------------------------- ### Full SDK Initialization Example Source: https://www.dynamic.xyz/docs/flutter/sdk-reference/data-types A complete example demonstrating the initialization of the Dynamic SDK within a Flutter application's main function. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); await DynamicSDK.instance.initialize( environmentId: 'YOUR_ENV_ID', ); runApp(MyApp()); } ``` -------------------------------- ### Example Usage of WalletProperties Source: https://www.dynamic.xyz/docs/node/reference/types/wallet-properties Demonstrates how to create an instance of the WalletProperties interface with sample data. This example includes all required properties and an optional derivationPath, illustrating a typical configuration for a wallet. ```typescript const walletProperties: WalletProperties = { chainName: 'EVM', walletId: 'wallet_123456', accountAddress: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6', externalServerKeyShares: [ // ServerKeyShare objects ], thresholdSignatureScheme: ThresholdSignatureScheme.TWO_OF_TWO, derivationPath: 'm/44\'/60\'/0\'/0/0', externalServerKeySharesBackupInfo: { passwordEncrypted: false, backups: { dynamic: [], googleDrive: [], iCloud: [], user: [], external: [] } } }; ``` -------------------------------- ### GitHub Actions CI Example Source: https://www.dynamic.xyz/docs/cli/guides/authentication This example demonstrates how to install the Dynamic CLI and run a non-interactive `dyn apply --dry-run` command in a GitHub Actions workflow, using a secret for the CLI token and disabling color output. ```yaml - name: Check Dynamic config drift env: DYN_CLI_TOKEN: ${{ secrets.DYN_CLI_TOKEN }} run: | npm install -g @dynamic-labs/dynamic-console-cli dyn apply -f envs/live.yaml --dry-run --no-color ``` -------------------------------- ### Install Delegation Toolkit Source: https://www.dynamic.xyz/docs/react/smart-wallets/smart-wallet-providers/metamask Install the Delegation Toolkit using npm, yarn, pnpm, or bun. ```bash npm install @metamask/delegation-toolkit ``` ```bash yarn add @metamask/delegation-toolkit ``` ```bash pnpm add @metamask/delegation-toolkit ``` ```bash bun add @metamask/delegation-toolkit ``` -------------------------------- ### Get User MFA Devices Example Source: https://www.dynamic.xyz/docs/flutter/sdk-reference/data-types Retrieves a list of the user's MFA devices and prints their IDs and types. ```dart final devices = await sdk.mfa.getUserDevices(); for (final device in devices) { print('Device ID: ${device.id}'); print('Type: ${device.type?.name}'); } ``` -------------------------------- ### Verify Dynamic CLI Installation Source: https://www.dynamic.xyz/docs/cli Verify the installation by running the help command. This confirms the 'dyn' binary is accessible and shows its basic usage. ```sh dyn --help ``` -------------------------------- ### Add Dynamic SDK Dependency Source: https://www.dynamic.xyz/docs/flutter/quickstart Add the dynamic_sdk dependency to your pubspec.yaml file and run 'flutter pub get' to install it. ```yaml dependencies: dynamic_sdk: ^1.2.4 ``` ```bash flutter pub get ``` -------------------------------- ### React Native Funding Options Usage Example Source: https://www.dynamic.xyz/docs/react-native/reference/wallets/funding A basic example demonstrating how to integrate the show and hide funding options functionality within a React Native component. Ensure you replace './path-to-your-client' with the actual path to your Dynamic client setup. ```typescript import { useReactiveClient } from '@dynamic-labs/react-hooks'; import { dynamicClient } from './path-to-your-client'; // Replace with your actual client path export const useDynamicClient = () => useReactiveClient(dynamicClient); const FundingComponent = () => { const client = useDynamicClient() const handleShowFunding = () => { client.ui.fundingOptions.show() } const handleHideFunding = () => { client.ui.fundingOptions.hide() } return ( <>