### ArtifactStore Initialization Example Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/artifacts-management.md Example demonstrating how to initialize the ArtifactStore with custom file system functions for reading, writing, and checking file existence. ```typescript import { ArtifactStore } from '@railgun-community/wallet'; import { promises as fs } from 'fs'; import path from 'path'; const artifactStore = new ArtifactStore( async (filePath) => { try { return await fs.readFile(filePath); } catch { return null; } }, async (dir, filePath, data) => { const fullPath = path.join(dir, filePath); await fs.writeFile(fullPath, data); }, async (filePath) => { try { await fs.stat(filePath); return true; } catch { return false; } }, ); ``` -------------------------------- ### Check POI Requirement for Network (Example) Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/poi-management.md Example demonstrating how to check if POI is required for the Ethereum network. Ensure you have imported the necessary classes from '@railgun-community/wallet' and '@railgun-community/shared-models'. ```typescript import { POIRequired } from '@railgun-community/wallet'; import { NetworkName } from '@railgun-community/shared-models'; const required = await POIRequired.isRequiredForNetwork( NetworkName.Ethereum ); ``` -------------------------------- ### Setup Balance Monitoring Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/quick-start-patterns.md Set up callbacks to monitor balance updates and POI proof progress. Call `refreshBalances` to initiate a balance refresh. ```typescript import { setOnBalanceUpdateCallback, setOnWalletPOIProofProgressCallback, refreshBalances, getSerializedERC20Balances, getSerializedNFTBalances, } from '@railgun-community/wallet'; function setupBalanceMonitoring() { // Monitor balance changes setOnBalanceUpdateCallback((event) => { const walletID = event.railgunWalletID; const chain = event.chain; console.log(`\nBalance update for wallet ${walletID} on chain ${chain.id}`); // ERC20 balances if (event.balances.erc20.length > 0) { console.log('ERC20 Tokens:'); event.balances.erc20.forEach((token) => { console.log(` ${token.tokenAddress}: ${token.amount}`); }); } // NFT balances if (event.balances.nfts.length > 0) { console.log('NFTs:'); event.balances.nfts.forEach((nft) => { console.log(` ${nft.nftAddress}#${nft.tokenSubID}: ${nft.amount}`); }); } }); // Monitor POI proof generation setOnWalletPOIProofProgressCallback((event) => { console.log(`POI proof status: ${event.status}`); if (event.progress !== undefined) { console.log(`Progress: ${Math.round(event.progress * 100)}%`); } }); } async function refreshWalletBalance( walletID: string, chain: { type: number; id: number }, ) { console.log(`Refreshing balance for wallet ${walletID}...`); await refreshBalances(chain, [walletID]); console.log('Balance refresh initiated (will complete in background)'); } ``` -------------------------------- ### Get Transaction History and Monitor Balance Updates Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/transaction-history.md Example of how to use the Railgun wallet SDK to monitor balance updates via a callback and retrieve the full transaction history. Includes parsing logic for 'Send' transactions. ```typescript import { getTransactionHistory, setOnBalanceUpdateCallback, } from '@railgun-community/wallet'; // Monitor balance updates setOnBalanceUpdateCallback((event) => { console.log(`Balance updated for wallet ${event.railgunWalletID}`); console.log('ERC20:', event.balances.erc20); }); // Retrieve full history const history = await getTransactionHistory( 'wallet-123', TXIDVersion.V2, { type: 0, id: 1 }, ); // Parse history history.forEach((item) => { if (item.category === 'Send') { item.rail.forEach((erc20) => { console.log( `Sent ${erc20.amount} of ${erc20.tokenAddress}`, ); }); } }); ``` -------------------------------- ### clearArtifactCache Usage Example Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/artifacts-management.md Example demonstrating the usage of the clearArtifactCache function to clear all in-memory cached artifacts. ```typescript import { clearArtifactCache } from '@railgun-community/wallet'; clearArtifactCache(); ``` -------------------------------- ### Browser ArtifactStore Implementation Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/configuration.md Provides an example implementation of the ArtifactStore interface for browser environments using localForage. This enables client-side artifact storage. ```typescript import { ArtifactStore } from '@railgun-community/wallet'; import localforage from 'localforage'; const artifactStore = new ArtifactStore( // get function async (key) => { return await localforage.getItem(key); }, // store function async (dir, key, data) => { await localforage.setItem(`${dir}/${key}`, data); }, // exists function async (key) => { return await localforage.getItem(key) !== null; }, ); ``` -------------------------------- ### Node.js ArtifactStore Implementation Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/configuration.md Provides an example implementation of the ArtifactStore interface using Node.js file system operations. This is suitable for server-side or local applications. ```typescript import { ArtifactStore } from '@railgun-community/wallet'; import { promises as fs } from 'fs'; import path from 'path'; const artifactStore = new ArtifactStore( // get function async (filePath) => { try { return await fs.readFile(filePath); } catch (error) { return null; } }, // store function async (dir, filePath, data) => { const fullPath = path.join(dir, filePath); await fs.mkdir(path.dirname(fullPath), { recursive: true }); await fs.writeFile(fullPath, data); }, // exists function async (filePath) => { try { await fs.stat(filePath); return true; } catch { return false; } }, ); ``` -------------------------------- ### RAILGUN Documentation Format - Types Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/INDEX.md Demonstrates the documentation format for type definitions in the RAILGUN Wallet project. It covers type descriptions, field details, and usage examples. ```markdown ### Types ``` ### TypeName Description typescript code block with type definition ### Fields | Field | Type | Description | ### Example Usage example **Used by:** List of where type is used ``` ``` -------------------------------- ### overrideArtifact Usage Example Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/artifacts-management.md Example of how to use the overrideArtifact function to provide a custom artifact for a specific circuit variant. ```typescript import { overrideArtifact } from '@railgun-community/wallet'; overrideArtifact('2-2', { vkey: {...}, zkey: {...}, wasm: new Uint8Array(...), }); ``` -------------------------------- ### walletForID Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/wallet-management.md Gets a wallet by ID from the engine. Returns an AbstractWallet instance corresponding to the ID. ```APIDOC ## walletForID ### Description Gets a wallet by ID from the engine. ### Method ```typescript export const walletForID = (id: string): AbstractWallet ``` ### Parameters #### Path Parameters - **id** (string) - Required - The wallet ID. ### Returns AbstractWallet instance corresponding to the ID. ### Throws Error if no wallet exists for the given ID. ### Example ```typescript import { walletForID } from '@railgun-community/wallet'; const wallet = walletForID('wallet-123'); ``` ``` -------------------------------- ### ArtifactStore get Method Signature Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/artifacts-management.md Signature for the get method, which retrieves an artifact file from storage based on its path. Returns the file content or null if not found. ```typescript get(path: string): Promise ``` -------------------------------- ### Complete RAILGUN Engine Initialization Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/quick-start-patterns.md Initializes the RAILGUN engine with logging, database, artifact store, providers, and callbacks. This is a comprehensive setup for Node.js environments. ```typescript import { startRailgunEngine, setLoggers, setOnBalanceUpdateCallback, setOnUTXOMerkletreeScanCallback, ArtifactStore, } from '@railgun-community/wallet'; import { setFallbackProviderForNetwork, setPollingProviderForNetwork, } from '@railgun-community/wallet'; import level from 'level'; import { FallbackProvider, JsonRpcProvider } from 'ethers'; import { NetworkName } from '@railgun-community/shared-models'; // 1. Setup logging setLoggers( (msg) => console.log('[RAILGUN]', msg), (err) => console.error('[RAILGUN ERROR]', err), ); // 2. Create database const db = level('./railgun-db'); // 3. Create artifact store (Node.js example) import { promises as fs } from 'fs'; import path from 'path'; const artifactStore = new ArtifactStore( async (filePath) => { try { return await fs.readFile(filePath); } catch { return null; } }, async (dir, filePath, data) => { const fullPath = path.join(dir, filePath); await fs.mkdir(path.dirname(fullPath), { recursive: true }); await fs.writeFile(fullPath, data); }, async (filePath) => { try { await fs.stat(filePath); return true; } catch { return false; } }, ); // 4. Setup providers const fallbackProvider = new FallbackProvider([ { provider: new JsonRpcProvider('https://eth-rpc.example.com'), weight: 1 }, { provider: new JsonRpcProvider('https://eth-backup.example.com'), weight: 1 }, ]); setFallbackProviderForNetwork(NetworkName.Ethereum, fallbackProvider); // 5. Setup callbacks setOnBalanceUpdateCallback((event) => { console.log(`Wallet ${event.railgunWalletID} balance updated`); console.log('ERC20:', event.balances.erc20); }); setOnUTXOMerkletreeScanCallback((scanData) => { console.log(`Scan progress: ${Math.round(scanData.progress * 100)}%`); }); // 6. Start engine await startRailgunEngine( 'my-wallet-app', db, true, // shouldDebug artifactStore, false, // useNativeArtifacts (false for Node.js/web) false, // skipMerkletreeScans ['https://poi.railgun.org'], // poiNodeURLs [], // customPOILists false, // verboseScanLogging ); console.log('RAILGUN Engine initialized'); ``` -------------------------------- ### RAILGUN Documentation Format - Functions Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/INDEX.md Illustrates the standard format used for documenting functions within the RAILGUN Wallet project. This includes sections for signature, parameters, returns, throws, and examples. ```markdown ### Functions ``` ## functionName Description of what the function does. ### Full Signature typescript code block showing exact signature ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| ### Returns Description of return value ### Throws Errors that can be thrown ### Example typescript code example **Source:** src/path/to/file.ts:123 ``` ``` -------------------------------- ### Start RAILGUN Engine for Wallet Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/engine-initialization.md Initializes the RAILGUN Engine for a wallet application. Requires wallet details, database, artifact store, and configuration for native artifacts and merkletree scans. Optional parameters include POI node URLs and custom POI lists. ```typescript import { startRailgunEngine } from '@railgun-community/wallet'; import { getArtifactStore } from './artifact-store'; // Platform-specific implementation import level from 'level'; const db = level('./railgun-db'); const artifactStore = await getArtifactStore(); await startRailgunEngine( 'my-wallet-app', db, true, // shouldDebug artifactStore, false, // useNativeArtifacts (for web) false, // skipMerkletreeScans ['https://poi.railgun.org'], // poiNodeURLs [], // customPOILists false, // verboseScanLogging ); ``` -------------------------------- ### startRailgunEngineForPOINode Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/engine-initialization.md Initializes the RAILGUN Engine specifically for a Proof of Innocence (POI) node. This setup is optimized for POI node operations, including validation of POI merkleroots. ```APIDOC ## startRailgunEngineForPOINode ### Description Initializes the RAILGUN Engine for a Proof of Innocence (POI) node. This setup is optimized for POI node operations, including validation of POI merkleroots. ### Method `async` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **db** (AbstractLevelDOWN) - Required - LevelDOWN compatible database. - **shouldDebug** (boolean) - Required - Whether to forward Engine debug logs to Logger. - **artifactStore** (ArtifactStore) - Required - Persistent store for downloading artifacts. - **validatePOIMerkleroots** (POIMerklerootsValidator) - Required - Function to validate POI merkleroots. ### Response #### Success Response - Resolves with `void` when engine initialization is complete. #### Response Example None (resolves with void) ### Throws - Error if engine is already initialized or initialization fails. ``` -------------------------------- ### Validate Spendable Transaction with POI (Example) Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/poi-management.md Example demonstrating how to validate a transaction for POI. It checks the result and logs an error if the POI is invalid. Ensure 'chain', 'transactionRequest', and 'poiData' are defined in your scope. ```typescript import { POIValidator } from '@railgun-community/wallet'; const result = await POIValidator.isValidSpendableTransaction( 'wallet-123', TXIDVersion.V2, chain, transactionRequest, false, // useRelayAdapt poiData, ); if (!result.isValid) { console.error('Invalid POI:', result.error); } ``` -------------------------------- ### Get Wallet by ID Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/wallet-management.md Retrieves an AbstractWallet instance using its unique ID. Use this for general wallet access. ```typescript import { walletForID } from '@railgun-community/wallet'; const wallet = walletForID('wallet-123'); ``` -------------------------------- ### Engine Initialization and Control Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/INDEX.md Methods for initializing, starting, stopping, and checking the status of the RAILGUN Engine. Includes callbacks for merkletree scans and POI batching. ```APIDOC ## Engine Initialization and Control ### Description Methods to manage the lifecycle and status of the RAILGUN Engine. Supports callbacks for asynchronous events like merkletree scans and POI batch processing. ### Methods - `startRailgunEngine` - `stopRailgunEngine` - `getEngine` - `hasEngine` ### Callbacks - merkletree scans - POI batching ``` -------------------------------- ### Get Wallet by ID Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/configuration.md Retrieve an existing wallet instance using its unique identifier. Ensure the wallet has been previously created and stored. ```typescript import { walletForID, fullWalletForID } from '@railgun-community/wallet'; // Get wallet by ID (created elsewhere) const wallet = walletForID('wallet-id'); // Get specific full wallet const fullWallet = fullWalletForID('wallet-id'); ``` -------------------------------- ### Setup Fallback and Polling Providers Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/providers-and-networks.md Configure both fallback and polling JSON RPC providers for a network. The fallback provider handles general RPC requests, while the polling provider is optimized for efficient event listening with a configurable polling interval. ```typescript import { setFallbackProviderForNetwork, setPollingProviderForNetwork, loadProvider, } from '@railgun-community/wallet'; import { NETWORK_CONFIG, NetworkName, createFallbackProviderFromJsonConfig, } from '@railgun-community/shared-models'; import { createPollingJsonRpcProviderForListeners } from '@railgun-community/engine'; async function setupProviders() { const networkName = NetworkName.Ethereum; const networkConfig = NETWORK_CONFIG[networkName]; const chain = networkConfig.chain; // Create fallback provider const fallbackProvider = createFallbackProviderFromJsonConfig({ rpcEndpoints: [ { url: 'https://eth-mainnet.g.alchemy.com/v2/YOUR-KEY' }, { url: 'https://eth-rpc.publicnode.com' }, ], }); setFallbackProviderForNetwork(networkName, fallbackProvider); // Create polling provider const pollingProvider = await createPollingJsonRpcProviderForListeners( fallbackProvider, chain.id, 4000, // 4 second polling interval ); setPollingProviderForNetwork(networkName, pollingProvider); } ``` -------------------------------- ### Shield (Deposit) Tokens Workflow Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/quick-start-patterns.md Guides through the process of shielding (depositing) tokens into a RAILGUN wallet. It includes estimating gas costs and generating the shield transaction. ```typescript import { generateShieldTransaction, gasEstimateForUnprovenShield, } from '@railgun-community/wallet'; import { TXIDVersion, NetworkName } from '@railgun-community/shared-models'; import { ethers } from 'ethers'; async function shieldTokens() { const shieldPrivateKey = '0x...'; // Private key for signing const tokenAddress = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'; // USDC const amount = BigInt('1000000'); // 1 USDC (6 decimals) const railgunAddress = 'rail1pzq...'; // RAILGUN address // Step 1: Estimate gas const gasEstimate = await gasEstimateForUnprovenShield( TXIDVersion.V2, NetworkName.Ethereum, [ { tokenAddress, amount, recipientAddress: railgunAddress, }, ], [], { gasEstimate: BigInt('300000'), gasPrice: await provider.getGasPrice(), }, ); console.log('Gas estimate:', gasEstimate.gasEstimate); // Step 2: Generate shield transaction const tx = await generateShieldTransaction( TXIDVersion.V2, NetworkName.Ethereum, shieldPrivateKey, [ { tokenAddress, amount, recipientAddress: railgunAddress, }, ], [], ); // Step 3: Sign and send (using ethers) const signer = provider.getSigner(); const txResponse = await signer.sendTransaction(tx); const receipt = await txResponse.wait(); console.log('Shield confirmed:', receipt?.hash); } ``` -------------------------------- ### ArtifactStore Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/artifacts-management.md Class for managing artifact file storage and retrieval. It provides methods to get, store, and check for the existence of artifact files. ```APIDOC ## Class ArtifactStore ### Description Class for managing artifact file storage and retrieval. It provides methods to get, store, and check for the existence of artifact files. ### Constructor #### Parameters - **get** (function) - Function to retrieve artifact file from storage. - **store** (function) - Function to store artifact file. - **exists** (function) - Function to check if artifact exists. ### Methods #### get ##### Description Retrieves an artifact file from storage. ##### Signature `get(path: string): Promise` ##### Parameters - **path** (string) - Required - File path in storage ##### Returns File contents as string, Buffer, or null if not found. #### store ##### Description Stores an artifact file. ##### Signature `store(dir: string, path: string, item: string | Uint8Array): Promise` ##### Parameters - **dir** (string) - Required - Directory to store in - **path** (string) - Required - File path relative to dir - **item** (string | Uint8Array) - Required - File contents #### exists ##### Description Checks if artifact file exists. ##### Signature `exists(path: string): Promise` ##### Parameters - **path** (string) - Required - File path to check ##### Returns true if file exists, false otherwise. ``` -------------------------------- ### Start RAILGUN Engine for POI Node Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/engine-initialization.md Initializes the RAILGUN Engine specifically for a Proof of Innocence (POI) node. Requires a database, debug flag, artifact store, and a validator function for POI merkleroots. ```typescript export const startRailgunEngineForPOINode = async ( db: AbstractLevelDOWN, shouldDebug: boolean, artifactStore: ArtifactStore, validatePOIMerkleroots: POIMerklerootsValidator, ): Promise ``` -------------------------------- ### Example: Set RAILGUN SDK Loggers Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/configuration.md Configure the RAILGUN SDK to send log and error messages to the browser console or a custom monitoring service. This allows for centralized error tracking and debugging. ```typescript import { setLoggers } from '@railgun-community/wallet'; // Send logs to browser console setLoggers( (msg: string) => console.log('[RAILGUN]', msg), (err: Error | string) => console.error('[RAILGUN ERROR]', err), ); // Or send to monitoring service setLoggers( (msg: string) => monitoring.log('railgun', msg), (err: Error | string) => monitoring.error('railgun', err), ); ``` -------------------------------- ### Get Fallback Provider for Network Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/providers-and-networks.md Retrieves the fallback provider for a specified network. Use this to interact with a network using redundant RPC connections. ```typescript export const getFallbackProviderForNetwork = ( networkName: NetworkName, ): FallbackProvider ``` ```typescript import { getFallbackProviderForNetwork } from '@railgun-community/wallet'; import { NetworkName } from '@railgun-community/shared-models'; const provider = getFallbackProviderForNetwork(NetworkName.Ethereum); const blockNumber = await provider.getBlockNumber(); console.log('Current block:', blockNumber); ``` -------------------------------- ### RAILGUN Documentation Statistics Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/INDEX.md Summary statistics of the RAILGUN Wallet documentation coverage. This includes counts for files, lines, API modules, types, code examples, and error conditions. ```markdown ### Statistics | Metric | Count | |--------|-------| | Total files | 20 | | Total lines | 5,221 | | API reference modules | 14 | | Reference documents | 6 | | Exported functions | 60+ | | Type definitions | 25+ | | Code examples | 30+ | | Error conditions | 50+ | | Networks covered | 7 | ``` -------------------------------- ### Get Shields for TXID Version Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/shield-data.md Retrieves shield transactions for a specific TXID version (V2 or V3) on a given network, starting from a specified block. Useful for filtering shields by their version. ```typescript import { getShieldsForTXIDVersion } from '@railgun-community/wallet'; import { NetworkName, TXIDVersion } from '@railgun-community/shared-models'; const shieldsV2 = await getShieldsForTXIDVersion( TXIDVersion.V2, NetworkName.Ethereum, 17000000, ); console.log(`Found ${shieldsV2.length} V2 shields`); ``` -------------------------------- ### init Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/poi-management.md Initializes POI for the wallet with default and custom lists. This method sets up the necessary configurations for POI services. ```APIDOC ## init ### Description Initializes POI for wallet with default and custom lists. ### Method static init ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **poiNodeInterface** (POINodeInterface) - Interface to POI nodes - **customLists** (POIList[]) - Custom POI lists to add to defaults ``` -------------------------------- ### Initialize Ethers FallbackProvider Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/providers-and-networks.md Demonstrates how to create an Ethers.js FallbackProvider instance with multiple RPC endpoints and custom network chainId and quorum settings. ```typescript import { FallbackProvider, JsonRpcProvider } from 'ethers'; const provider = new FallbackProvider( [ { provider: new JsonRpcProvider('https://eth-rpc1.example.com'), weight: 1 }, { provider: new JsonRpcProvider('https://eth-rpc2.example.com'), weight: 1 }, ], 1, // network chainId 2, // quorum ); ``` -------------------------------- ### Get All Shields Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/shield-data.md Retrieves all shield transactions on a network since a specified block. Use this to get a comprehensive list of shield deposits. ```typescript import { getAllShields } from '@railgun-community/wallet'; import { NetworkName } from '@railgun-community/shared-models'; const shields = await getAllShields(NetworkName.Ethereum, 17000000); shields.forEach((shield) => { console.log('Shield:', { txid: shield.txid, commitmentHash: shield.commitmentHash, blockNumber: shield.blockNumber, }); }); ``` -------------------------------- ### Initialize Wallet POI Configuration Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/poi-management.md Initializes wallet-level Proof of Innocence (POI) configurations. This method requires a POI node interface and an array of custom POI lists. ```typescript export class WalletPOI { static init( poiNodeInterface: POINodeInterface, customLists: POIList[], ): void static getPOITxidMerklerootValidator( poiNodeURLs?: string[], ): MerklerootValidator static getPOILatestValidatedRailgunTxid( poiNodeURLs?: string[], ): GetLatestValidatedRailgunTxid } ``` -------------------------------- ### Initialize POI Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/poi-management.md Initializes POI for the wallet using default and custom lists. Requires a POINodeInterface and an array of custom POI lists. ```typescript static init( poiNodeInterface: POINodeInterface, customLists: POIList[], ): void ``` -------------------------------- ### startRailgunEngine Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/engine-initialization.md Initializes the RAILGUN Engine for a wallet. This method sets up the necessary components for the engine to operate within a wallet context, managing encrypted transaction history and private balance scans. ```APIDOC ## startRailgunEngine ### Description Initializes the RAILGUN Engine for a wallet. This method sets up the necessary components for the engine to operate within a wallet context, managing encrypted transaction history and private balance scans. ### Method `async` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **walletSource** (string) - Required - Name for wallet implementation. Encrypted in private transaction history. Maximum 16 characters, lowercase. - **db** (AbstractLevelDOWN) - Required - LevelDOWN compatible database for storing encrypted wallets. - **shouldDebug** (boolean) - Required - Whether to forward Engine debug logs to Logger. - **artifactStore** (ArtifactStore) - Required - Persistent store for downloading large artifact files. - **useNativeArtifacts** (boolean) - Required - Whether to download native C++ or web-assembly artifacts. TRUE for mobile, FALSE for nodejs and browser. - **skipMerkletreeScans** (boolean) - Required - Whether to skip merkletree syncs and private balance scans. Only set to TRUE in shield-only applications. - **poiNodeURLs** (string[]) - Optional - List of POI aggregator node URLs, in order of priority. - **customPOILists** (POIList[]) - Optional - POI lists for additional wallet protections after default lists. - **verboseScanLogging** (boolean) - Optional - Enable verbose logging during merkletree scans. ### Request Example ```typescript import { startRailgunEngine } from '@railgun-community/wallet'; import { getArtifactStore } from './artifact-store'; // Platform-specific implementation import level from 'level'; const db = level('./railgun-db'); const artifactStore = await getArtifactStore(); await startRailgunEngine( 'my-wallet-app', db, true, // shouldDebug artifactStore, false, // useNativeArtifacts (for web) false, // skipMerkletreeScans ['https://poi.railgun.org'], // poiNodeURLs [], // customPOILists false, // verboseScanLogging ); ``` ### Response #### Success Response - Resolves with `void` when engine initialization is complete. #### Response Example None (resolves with void) ### Throws - Error if engine is already initialized or if initialization fails. ``` -------------------------------- ### WalletPOI Class Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/poi-management.md Provides methods for wallet-level POI initialization and configuration. ```APIDOC ## WalletPOI Class Class for wallet-level POI initialization and configuration. ### Static Methods #### init Initializes the POI system for wallet operations. ##### Method `init( poiNodeInterface: POINodeInterface, customLists: POIList[], ): void` ##### Parameters - `poiNodeInterface` (POINodeInterface) - Required - Interface for interacting with the POI node. - `customLists` (POIList[]) - Required - Array of custom POI lists to be used. #### getPOITxidMerklerootValidator Retrieves a Merkle root validator for POI transaction IDs. ##### Method `getPOITxidMerklerootValidator( poiNodeURLs?: string[], ): MerklerootValidator` ##### Parameters - `poiNodeURLs` (string[]) - Optional - Array of POI node URLs. ##### Returns - `MerklerootValidator` - An instance of MerklerootValidator. #### getPOILatestValidatedRailgunTxid Retrieves the latest validated Railgun transaction ID from POI nodes. ##### Method `getPOILatestValidatedRailgunTxid( poiNodeURLs?: string[], ): GetLatestValidatedRailgunTxid` ##### Parameters - `poiNodeURLs` (string[]) - Optional - Array of POI node URLs. ##### Returns - `GetLatestValidatedRailgunTxid` - An object containing information about the latest validated Railgun TxID. ``` -------------------------------- ### Get Transaction History Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/README.md Retrieves the transaction history for a specific wallet. ```APIDOC ## Get Transaction History ### Description Retrieves the transaction history for a specific wallet. ### Method `getTransactionHistory` ### Parameters - `walletId` (string): The ID of the wallet whose transaction history to retrieve. - `txidVersion` (TXIDVersion): The version of the transaction ID format to use. - `chain` (Chain): The chain for which to retrieve transaction history. ### Request Example ```typescript import { getTransactionHistory } from '@railgun-community/wallet'; const history = await getTransactionHistory('wallet-123', TXIDVersion.V2, chain); history.forEach((tx) => { console.log(tx.category, tx.blockNumber, tx.rail); }); ``` ``` -------------------------------- ### getPollingProviderForNetwork Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/providers-and-networks.md Gets the polling provider for a network. This provider is used for listening to chain events. ```APIDOC ## getPollingProviderForNetwork ### Description Gets the polling provider for a network. This provider is used for listening to chain events. ### Method GET (conceptual) ### Endpoint N/A (SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **networkName** (NetworkName) - Required - Target network. ### Returns PollingJsonRpcProvider for listening to chain events. ### Throws Error if polling provider not yet loaded. ``` -------------------------------- ### Initialize the SDK Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/README.md Initializes the RAILGUN engine with necessary parameters. This is a prerequisite for most other SDK operations. ```APIDOC ## Initialize the SDK ### Description Initializes the RAILGUN engine with necessary parameters. This is a prerequisite for most other SDK operations. ### Method `startRailgunEngine` ### Parameters - `appName` (string): A unique identifier for your wallet application. - `db` (Database): An instance of the database to be used by the engine. - `isTestnet` (boolean): Flag indicating if operating in a testnet environment. - `artifactStore` (ArtifactStore): An object for storing and retrieving RAILGUN artifacts. - `useNativeArtifacts` (boolean): Whether to use native artifact loading. - `skipMerkletreeScans` (boolean): Whether to skip Merkle tree scans during initialization. ### Request Example ```typescript import { startRailgunEngine, ArtifactStore } from '@railgun-community/wallet'; await startRailgunEngine( 'my-wallet-app', db, true, artifactStore, false, // useNativeArtifacts false, // skipMerkletreeScans ); ``` ``` -------------------------------- ### getFallbackProviderForNetwork Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/providers-and-networks.md Gets the fallback provider for a network. This provider is used for redundant RPC connections. ```APIDOC ## getFallbackProviderForNetwork ### Description Gets the fallback provider for a network. This provider is used for redundant RPC connections. ### Method GET (conceptual) ### Endpoint N/A (SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **networkName** (NetworkName) - Required - Target blockchain network. ### Returns FallbackProvider instance for the network. ### Throws Error if provider not yet loaded for network. ### Example ```typescript import { getFallbackProviderForNetwork } from '@railgun-community/wallet'; import { NetworkName } from '@railgun-community/shared-models'; const provider = getFallbackProviderForNetwork(NetworkName.Ethereum); const blockNumber = await provider.getBlockNumber(); console.log('Current block:', blockNumber); ``` ``` -------------------------------- ### viewOnlyWalletForID Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/wallet-management.md Gets a view-only wallet by ID. Returns a RailgunWallet instance in view-only mode. ```APIDOC ## viewOnlyWalletForID ### Description Gets a view-only wallet by ID. ### Method ```typescript export const viewOnlyWalletForID = (id: string): RailgunWallet ``` ### Parameters #### Path Parameters - **id** (string) - Required - The wallet ID. ### Returns RailgunWallet instance in view-only mode. ### Throws Error if wallet does not exist or is not a view-only wallet. ``` -------------------------------- ### fullWalletForID Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/wallet-management.md Gets a full (non-view-only) wallet by ID. Returns a RailgunWallet instance for the given ID. ```APIDOC ## fullWalletForID ### Description Gets a full (non-view-only) wallet by ID. ### Method ```typescript export const fullWalletForID = (id: string): RailgunWallet ``` ### Parameters #### Path Parameters - **id** (string) - Required - The wallet ID. ### Returns RailgunWallet instance for the given ID. ### Throws Error if wallet does not exist or is a view-only wallet. ### Example ```typescript import { fullWalletForID } from '@railgun-community/wallet'; const wallet = fullWalletForID('wallet-123'); ``` ``` -------------------------------- ### Initialize Railgun Engine Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/README.md Initializes the Railgun engine with necessary parameters. Ensure you have an ArtifactStore and provide appropriate values for network and wallet settings. ```typescript import { startRailgunEngine, ArtifactStore } from '@railgun-community/wallet'; await startRailgunEngine( 'my-wallet-app', db, true, artifactStore, false, // useNativeArtifacts false, // skipMerkletreeScans ); ``` -------------------------------- ### Define ArtifactStore Interface Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/configuration.md Defines the interface for artifact storage operations, including getting, storing, and checking the existence of artifacts. ```typescript type GetArtifact = (path: string) => Promise; type StoreArtifact = ( dir: string, path: string, item: string | Uint8Array, ) => Promise; type ArtifactExists = (path: string) => Promise; ``` -------------------------------- ### Configuration Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/README.md Explains the configuration options available for the RAILGUN Wallet SDK, including network, logging, and artifact storage. ```APIDOC ## Configuration ### Description Details the various configuration parameters and setup options for the RAILGUN Wallet SDK, including engine initialization, logging, gas settings, network specifics, provider setup, POI node configuration, and artifact storage implementation. ### Configuration Areas - Engine initialization parameters - Logging configuration - Gas configuration - Network configuration - Provider setup - POI node configuration - Artifact storage implementation - Callback setup patterns ``` -------------------------------- ### Get Polling Provider for Network Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/providers-and-networks.md Retrieves the polling provider for a specified network. This provider is used for listening to chain events. ```typescript export const getPollingProviderForNetwork = ( networkName: NetworkName, ): PollingJsonRpcProvider ``` -------------------------------- ### Handling Engine Initialization Errors Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/errors.md Implement error handling for the `startRailgunEngine` function. This snippet shows how to differentiate between artifact download failures and cases where the engine is already initialized. ```typescript import { startRailgunEngine } from '@railgun-community/wallet'; import { ArtifactStore } from '@railgun-community/wallet'; try { await startRailgunEngine( 'my-app', db, true, artifactStore, false, false, ); } catch (error) { if (error instanceof Error) { if (error.message.includes('artifact')) { console.error('Artifact download failed'); } else if (error.message.includes('already initialized')) { console.error('Engine already started'); } } } ``` -------------------------------- ### Utilities Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/INDEX.md A collection of helper functions for common tasks such as key derivation, string comparison, and error handling. ```APIDOC ## Utilities ### Description A set of miscellaneous utility functions designed to assist with various common tasks within the RAILGUN Wallet SDK, including cryptographic operations, data validation, and error management. ### Functions - `mnemonicTo0xPKey` - `compareStringArrays` - `isDecimalStr` - `reportAndSanitizeError` - `assertNotBlockedAddress` ``` -------------------------------- ### Get TXID Merkleroot Validator Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/poi-management.md Creates a validator function for TXID merkleroots. Optionally accepts a list of POI node URLs. ```typescript static getPOITxidMerklerootValidator( poiNodeURLs?: string[], ): MerklerootValidator ``` -------------------------------- ### Get Full Wallet by ID Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/wallet-management.md Retrieves a full RailgunWallet instance (non-view-only) by its ID. This is used when full wallet functionality is required. ```typescript import { fullWalletForID } from '@railgun-community/wallet'; const wallet = fullWalletForID('wallet-123'); ``` -------------------------------- ### Initialize RAILGUN Engine with Custom POI Lists Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/configuration.md Add custom Proof of Innocence (POI) lists during engine initialization. This allows for user-defined address lists to be included in POI checks. ```typescript const customLists: POIList[] = [ { name: 'my-list', addresses: ['0xaddress1', '0xaddress2'], // ... other fields } ]; await startRailgunEngine( 'my-wallet', db, true, artifactStore, false, false, poiNodeURLs, customLists, // Custom lists ); ``` -------------------------------- ### Get RAILGUN Engine Instance Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/engine-initialization.md Retrieves the currently initialized RAILGUN Engine instance. This function will throw an error if the engine has not yet been initialized. ```typescript export const getEngine = (): RailgunEngine ``` -------------------------------- ### Gas Estimation and Proof Caching Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/INDEX.md Utilities for estimating transaction gas costs and managing cached zero-knowledge proofs to optimize transaction submission. ```APIDOC ## Gas and Broadcasting ### Description Provides essential utilities for managing gas estimations and caching zero-knowledge proofs to streamline transaction broadcasting and reduce costs. ### Methods - `getGasEstimate` - `gasEstimateResponse` - `setGasDetailsForTransaction` - `populateProvedTransaction` - `setCachedProvedTransaction` ``` -------------------------------- ### Initialize RAILGUN Engine with POI Node URLs Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/configuration.md Pass an array of POI node URLs during engine initialization. These URLs are used in priority order. ```typescript await startRailgunEngine( 'my-wallet', db, true, artifactStore, false, false, ['https://poi.railgun.org', 'https://poi-backup.railgun.org'] // Priority order ); ``` -------------------------------- ### Get Shield Private Key Signature Message Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/utilities.md Generates the message that must be signed with a shield private key for verification. Import from '@railgun-community/wallet'. ```typescript import { getShieldPrivateKeySignatureMessage } from '@railgun-community/wallet'; import { ethers } from 'ethers'; const message = getShieldPrivateKeySignatureMessage(); const signer = new ethers.Wallet(privateKey); const signature = await signer.signMessage(message); ``` -------------------------------- ### Utilities Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/README.md A collection of helper functions for various tasks, including key derivation, array comparison, and error handling. ```APIDOC ## Utilities ### Description A collection of utility functions for common tasks such as key derivation, comparing arrays, validating input, and error handling. ### Functions - `mnemonicTo0xPKey`: Converts a mnemonic phrase to a private key. - `compareStringArrays`: Compares two string arrays for equality. - `compareContractTransactionArrays`: Compares two arrays of contract transactions. - `isDecimalStr`: Checks if a string represents a decimal number. - `reportAndSanitizeError`: Reports and sanitizes an error. - `parseRailgunTokenAddress`: Parses a RAILGUN token address. - `assertNotBlockedAddress`: Asserts that an address is not blocked. ``` -------------------------------- ### Get View-Only Wallet by ID Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/wallet-management.md Retrieves a RailgunWallet instance configured for view-only access using its ID. Use this when read-only operations are sufficient. ```typescript import { viewOnlyWalletForID } from '@railgun-community/wallet'; // Example usage for viewOnlyWalletForID would go here, but is not provided in source. ``` -------------------------------- ### Load Blockchain Provider Configuration Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/configuration.md Set up a blockchain provider for a specific network using FallbackProvider for RPC endpoint redundancy. Configure the polling interval for event listeners. ```typescript import { loadProvider, setFallbackProviderForNetwork, setPollingProviderForNetwork } from '@railgun-community/wallet'; import { FallbackProvider } from 'ethers'; // Configure RPC endpoints const fallbackProvider = new FallbackProvider([ { provider: new JsonRpcProvider('https://eth-rpc.example.com'), weight: 1 }, { provider: new JsonRpcProvider('https://eth-backup.example.com'), weight: 1 }, ]); setFallbackProviderForNetwork(NetworkName.Ethereum, fallbackProvider); // Polling interval in milliseconds for event listeners const pollingInterval = 4000; // 4 seconds ``` -------------------------------- ### ArtifactDownloader Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/artifacts-management.md Class for downloading and caching proof artifacts. It handles the process of fetching necessary artifact files for circuit variants. ```APIDOC ## Class ArtifactDownloader ### Description Class for downloading and caching proof artifacts. It handles the process of fetching necessary artifact files for circuit variants. ### Constructor #### Parameters - **artifactStore** (ArtifactStore) - Persistent artifact storage. - **useNativeArtifacts** (boolean) - Whether to download native C++ or web-assembly artifacts. ### Methods #### downloadArtifacts ##### Description Downloads vkey, zkey, and wasm/dat files for a circuit variant. ##### Signature `downloadArtifacts(artifactVariantString: string): Promise` ##### Parameters - **artifactVariantString** (string) - Required - Circuit variant identifier ##### Throws Error if download fails or times out (45 second limit). #### getDownloadedArtifacts ##### Description Retrieves previously downloaded artifacts. ##### Signature `getDownloadedArtifacts(artifactVariantString: string): Promise` ##### Parameters - **artifactVariantString** (string) - Required - Circuit variant identifier ##### Returns Artifact object with vkey, zkey, and wasm/dat. ##### Throws Error if artifacts not found. ``` -------------------------------- ### Get Serialized ERC20 Balances Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/balance-management.md Converts engine token balances to the serialized RailgunERC20Amount format. This is useful for preparing balance data for on-chain interactions. ```typescript export const getSerializedERC20Balances = ( balances: TokenBalances, ): RailgunERC20Amount[] ``` -------------------------------- ### setOnWalletPOIProofProgressCallback Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/balance-management.md Sets a callback function to receive POI proof progress notifications. This allows tracking the progress of POI proof generation. ```APIDOC ## setOnWalletPOIProofProgressCallback ### Description Sets a callback function to receive POI proof progress notifications. This allows tracking the progress of POI proof generation. ### Method N/A (Synchronous SDK Method) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```typescript import { setOnWalletPOIProofProgressCallback } from '@railgun-community/wallet'; setOnWalletPOIProofProgressCallback((event) => { console.log('POI progress:', event.status, event.progress); }); ``` ### Response #### Success Response void #### Response Example N/A ``` -------------------------------- ### Get Serialized NFT Balances Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/api-reference/balance-management.md Converts engine token balances to the serialized RailgunNFTAmount format. This is useful for preparing NFT balance data for on-chain interactions. ```typescript export const getSerializedNFTBalances = ( balances: TokenBalances, ): RailgunNFTAmount[] ``` -------------------------------- ### RAILGUN Wallet File Structure Source: https://github.com/railgun-community/wallet/blob/main/_autodocs/INDEX.md Overview of the directory structure for the RAILGUN Wallet project. This helps in navigating and understanding the organization of documentation and source files. ```tree output/ ├── README.md # Start here: overview and navigation ├── INDEX.md # This file ├── types.md # Type definitions ├── errors.md # Error handling ├── configuration.md # Setup guide ├── glossary.md # Terminology ├── quick-start-patterns.md # Code examples └── api-reference/ # Module reference ├── engine-initialization.md ├── wallet-management.md ├── balance-management.md ├── shielding-transactions.md ├── transfer-transactions.md ├── unshield-transactions.md ├── cross-contract-calls.md ├── gas-and-broadcasting.md ├── artifacts-management.md ├── poi-management.md ├── providers-and-networks.md ├── shield-data.md ├── transaction-history.md └── utilities.md ```