### Complete Test Setup Example Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/09-test-utilities.md A comprehensive example demonstrating how to configure the provider, set up multiple test accounts, and mint test tokens for a complete testing scenario. ```typescript import { web3 } from '@alephium/web3' import { testAddress, testPrivateKeyWallet, testMnemonic, mintToken } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' // 1. Configure provider for devnet web3.setCurrentNodeProvider('http://127.0.0.1:22973') // 2. Set up test accounts const wallet1 = testPrivateKeyWallet // Create additional test account const wallet2 = PrivateKeyWallet.FromMnemonic({ mnemonic: testMnemonic, addressIndex: 1 }) // 3. Mint test tokens if needed const tokenId = '0x1234567890abcdef...' // Replace with actual token ID try { await mintToken({ token: { id: tokenId, amount: '1000000000' } }) } catch (error) { console.log('Token minting unavailable (might not be devnet)') } // 4. Now ready for testing console.log('Wallet 1:', wallet1.address) console.log('Wallet 2:', wallet2.address) ``` -------------------------------- ### Development environment setup Source: https://github.com/alephium/alephium-web3/blob/master/packages/web3-react/README.md Command to install dependencies and start the development server. ```bash npm install npm run dev ``` -------------------------------- ### Quick Start: Setup, Wallet, and Transaction Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/12-complete-api-summary.md This snippet demonstrates the basic workflow for interacting with the Alephium blockchain. It covers setting up the node provider, creating a private key wallet, and submitting a simple transfer transaction. ```typescript // 1. Setup providers import { web3, NodeProvider } from '@alephium/web3' web3.setCurrentNodeProvider('https://node.testnet.alephium.org') // 2. Create wallet import { PrivateKeyWallet } from '@alephium/web3-wallet' const wallet = new PrivateKeyWallet({ privateKey: '0x...' }) // 3. Sign and submit transaction const result = await wallet.signAndSubmitTransferTx({ signerAddress: wallet.address, destinations: [{ address: 'tgx7VNFoP9DJiFMFgXXtafQZkUvyEdDHT9ryamHJYrjq', attoAlphAmount: '1000000000000000000' // 1 ALPH }] }) console.log('TX ID:', result.txId) ``` -------------------------------- ### Install from sources Source: https://github.com/alephium/alephium-web3/blob/master/packages/web3-react/README.md Commands to install dependencies and build the project from the cloned repository. ```bash npm install npm run build ``` -------------------------------- ### Deploy Contract Example Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/08-smart-contract-module.md A comprehensive example demonstrating contract deployment, including setting up the provider, creating a wallet, compiling bytecode, and submitting the deployment transaction with gas parameters. ```typescript import { Contract, web3 } from '@alephium/web3' import { PrivateKeyWallet } from '@alephium/web3-wallet' // Set up provider web3.setCurrentNodeProvider('https://node.testnet.alephium.org') // Create wallet const wallet = new PrivateKeyWallet({ privateKey: '0x...' }) // Compile contract (typically done offline) const bytecode = '0x0101...' // From Ralph compiler // Deploy contract const deployResult = await wallet.signAndSubmitDeployContractTx({ signerAddress: wallet.address, bytecode, initialAttoAlphAmount: '100000000000000000', // 0.1 ALPH gasAmount: 50000, gasPrice: BigInt(1_000_000_000_000) // 10^12 attoAlph/unit }) console.log('Contract ID:', deployResult.contractId) console.log('Contract Address:', deployResult.contractAddress) // Contract is now deployed and ready to interact with ``` -------------------------------- ### Provider Setup Check Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Demonstrates how to handle the common pitfall of missing provider setup. The code shows how to catch the error when no node provider is set and subsequently configure it using web3.setCurrentNodeProvider. ```typescript // Error: No node provider is set try { web3.getCurrentNodeProvider() } catch (e) { // Must call setCurrentNodeProvider first web3.setCurrentNodeProvider('...') } ``` -------------------------------- ### Start Testing Services for Alephium WalletConnect Provider Source: https://github.com/alephium/alephium-web3/blob/master/packages/walletconnect/README.md Starts the necessary services (Alephium node, Redis, WalletConnect relay) required for running tests. Navigate to the docker directory first. ```bash cd docker && docker-compose up -d ``` -------------------------------- ### Using Pre-configured Test Wallet Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/09-test-utilities.md For a fast setup in tests, use the pre-configured `testPrivateKeyWallet`. No additional wallet creation is needed. ```typescript import { testPrivateKeyWallet } from '@alephium/web3-test' // Fast, no wallet creation needed const wallet = testPrivateKeyWallet ``` -------------------------------- ### Wallet Creation and Usage Example Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Demonstrates various ways to create and use PrivateKeyWallet instances, including from existing keys, random generation, and mnemonics. Shows how to sign and submit transactions. ```typescript import { PrivateKeyWallet, generateMnemonic, deriveSecp256K1PrivateKey, getHDWalletPath } from '@alephium/web3-wallet' import { web3 } from '@alephium/web3' // Set up global provider web3.setCurrentNodeProvider('https://node.testnet.alephium.org') // Method 1: Create from existing private key const wallet1 = new PrivateKeyWallet({ privateKey: '0x...' }) // Method 2: Random wallet const wallet2 = PrivateKeyWallet.Random() const wallet2Group1 = PrivateKeyWallet.Random(1) // In group 1 // Method 3: From mnemonic const mnemonic = generateMnemonic(12) const wallet3 = PrivateKeyWallet.FromMnemonic({ mnemonic, addressIndex: 0 }) // Method 4: Mnemonic with target group const wallet4 = PrivateKeyWallet.FromMnemonicWithGroup(mnemonic, 2) // Use the wallet to sign and submit transactions const result = await wallet3.signAndSubmitTransferTx({ signerAddress: wallet3.address, destinations: [{ address: wallet4.address, attoAlphAmount: '1000000000000000000' }] }) console.log('Transaction ID:', result.txId) ``` -------------------------------- ### Example Usage of SECP256K1 Derivation Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Demonstrates deriving a SECP256K1 private key and its corresponding derivation path using a mnemonic. ```typescript const key = deriveSecp256K1PrivateKey(mnemonic, 0) const [keyForGroup3, index] = deriveSecp256K1PrivateKeyForGroup(mnemonic, 3) const path = getSecp259K1Path(0) // "m/44'/1234'/0'/0/0" ``` -------------------------------- ### Full Transaction Lifecycle Example Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/10-transaction-module.md Demonstrates the complete process of building, signing, submitting, and checking the status of a transfer transaction using PrivateKeyWallet and TransactionBuilder. ```typescript import { TransactionBuilder, web3 } from '@alephium/web3' import { PrivateKeyWallet } from '@alephium/web3-wallet' // Setup const nodeProvider = web3.getCurrentNodeProvider() const wallet = new PrivateKeyWallet({ privateKey: '0x...' }) const builder = TransactionBuilder.from(nodeProvider) // 1. Build unsigned transaction const unsignedTx = await builder.buildTransferTx({ signerAddress: wallet.address, destinations: [{ address: 'tgx7VNFoP9DJiFMFgXXtafQZkUvyEdDHT9ryamHJYrjq', attoAlphAmount: '1000000000000000000' }], gasAmount: 20000, gasPrice: BigInt(1_000_000_000_000) }, wallet.publicKey) // 2. Sign the transaction const signResult = await wallet.signUnsignedTx({ signerAddress: wallet.address, unsignedTx: unsignedTx.unsignedTx }) // 3. Submit to blockchain const submitResult = await wallet.submitTransaction({ unsignedTx: unsignedTx.unsignedTx, signature: signResult.signature }) // 4. Check status const status = await nodeProvider.transactions.getTransactionsStatus({ txId: submitResult.txId }) console.log('Transaction status:', status.type) ``` -------------------------------- ### Install and Load react-native-get-random-values Source: https://github.com/alephium/alephium-web3/blob/master/README.md Install the `react-native-get-random-values` package and require it in your entry point before importing `@alephium/web3`. This is necessary because `@noble/secp256k1` requires `crypto.getRandomValues`, which is not available by default in React Native. ```typescript // index.ts (entry point) require('react-native-get-random-values') // ... then load your app ``` -------------------------------- ### web3.getDefaultExplorerProvider Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/01-core-providers.md Gets a pre-configured explorer provider for a known network (mainnet, testnet, devnet). ```APIDOC ## web3.getDefaultExplorerProvider ### Description Get a pre-configured explorer provider for a known network. ### Method Static method of the `web3` namespace. ### Parameters #### Arguments - **networkId** ('mainnet' | 'testnet' | 'devnet') - The ID of the network. ### Returns - **ExplorerProvider** — An ExplorerProvider instance for the specified network. ### Example ```typescript const explorerProvider = web3.getDefaultExplorerProvider('testnet') ``` ``` -------------------------------- ### Distinguish Error Types During Wallet Setup Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/06-errors.md Implement robust error handling during wallet setup by checking the type and message of caught errors. This allows for specific logging or actions based on the error's nature, such as account or address-related issues. ```typescript async function robustWalletSetup(privateKey: string) { try { const wallet = new PrivateKeyWallet({ privateKey }) const account = await wallet.getSelectedAccount() return wallet } catch (error) { if (error instanceof Error) { const message = error.message if (message.includes('Invalid account')) { console.error('Account validation failed') } else if (message.includes('address')) { console.error('Address-related error') } else { console.error('Unknown error:', message) } } throw error } } ``` -------------------------------- ### Comprehensive Web3 Utility Usage Example Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/07-utility-functions.md Illustrates the usage of various utility functions including byte encoding/decoding, signing/verifying signatures, handling large numbers, and stringifying data. ```typescript import { binToHex, hexToBinUnsafe, sign, verifySignature, toNonNegativeBigInt, stringify, isHexString } from '@alephium/web3' // Encoding example const privateKey = '0x...' const message = 'Hello, Alephium' const messageHex = Buffer.from(message).toString('hex') // Signing const signature = sign(messageHex, privateKey) console.log('Signature:', signature) // Verification const isValid = verifySignature(publicKey, messageHex, signature) console.log('Valid:', isValid) // Amount handling const amount = toNonNegativeBigInt('1000000000000000000') // 1 ALPH console.log('Amount:', amount.toString()) // Logging const data = { amount, signature } console.log('Data:', stringify(data)) ``` -------------------------------- ### Import Test Constants and Wallet Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/09-test-utilities.md Import pre-configured test constants and a wallet instance for quick setup in testing environments. You can also create additional accounts from the test mnemonic. ```typescript import { testMnemonic, testAddress, testPrivateKeyWallet, testPassword } from '@alephium/web3-test' // Quick setup for testing const wallet = testPrivateKeyWallet console.log('Test address:', wallet.address) // Or create additional accounts from test mnemonic import { PrivateKeyWallet } from '@alephium/web3-wallet' const anotherAccount = PrivateKeyWallet.FromMnemonic({ mnemonic: testMnemonic, addressIndex: 1 }) ``` -------------------------------- ### Get HD Wallet Derivation Path Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Get the full BIP44 derivation path for a given key type and address index. Throws an error if the address index is invalid. ```typescript import { getHDWalletPath } from '@alephium/web3-wallet' const path = getHDWalletPath('default', 5) // "m/44'/1234'/0'/0/5" ``` -------------------------------- ### web3.getDefaultNodeProvider Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/01-core-providers.md Gets a pre-configured node provider for a known network (mainnet, testnet, devnet). ```APIDOC ## web3.getDefaultNodeProvider ### Description Get a pre-configured node provider for a known network. ### Method Static method of the `web3` namespace. ### Parameters #### Arguments - **networkId** ('mainnet' | 'testnet' | 'devnet') - The ID of the network. ### Returns - **NodeProvider** — A NodeProvider instance for the specified network. ### Example ```typescript const mainnetProvider = web3.getDefaultNodeProvider('mainnet') const testnetProvider = web3.getDefaultNodeProvider('testnet') const devnetProvider = web3.getDefaultNodeProvider('devnet') ``` ``` -------------------------------- ### Vitest Test Example: Transfer ALPH Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/09-test-utilities.md An example demonstrating how to use the test utilities within a Vitest test suite to perform and verify an ALPH transfer transaction using a pre-configured test wallet. ```typescript import { describe, it, expect } from 'vitest' import { web3 } from '@alephium/web3' import { testPrivateKeyWallet } from '@alephium/web3-test' describe('Wallet Transfer', () => { it('should transfer ALPH', async () => { // Use test wallet const wallet = testPrivateKeyWallet // Create transfer transaction const result = await wallet.signAndSubmitTransferTx({ signerAddress: wallet.address, destinations: [ { address: 'tgx7VNFoP9DJiFMFgXXtafQZkUvyEdDHT9ryamHJYrjq', attoAlphAmount: '1000000000000000000' } ] }) // Verify transaction was submitted expect(result.txId).toBeDefined() expect(result.signature).toBeDefined() }) }) ``` -------------------------------- ### Grouped Account Example Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/05-types.md Illustrates the structure of a grouped account object, including its key type, address, public key, and group number. ```typescript // A grouped account with default key const account: GroupedAccount = { keyType: 'default', address: 'tgx7VNFoP9DJiFMFgXXtafQZkUvyEdDHT9ryamHJYrjq', publicKey: '02a1b2c3...', group: 2 } ``` -------------------------------- ### Common Patterns: Submitting Transactions Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/12-complete-api-summary.md Provides examples for submitting various types of transactions, including transfers, contract deployments, script executions, and message signing. ```APIDOC ## Common Patterns: Submitting Transactions ```typescript // Transfer ALPH const transferResult = await wallet.signAndSubmitTransferTx({ signerAddress: wallet.address, destinations: [{ address: recipient, attoAlphAmount: amount }], gasAmount: 20000 }) // Deploy contract const deployResult = await wallet.signAndSubmitDeployContractTx({ signerAddress: wallet.address, bytecode: contractBytecode, initialAttoAlphAmount: '100000000000000000' }) // Execute script const scriptResult = await wallet.signAndSubmitExecuteScriptTx({ signerAddress: wallet.address, bytecode: scriptBytecode, attoAlphAmount: '1000000000000000000' }) // Sign arbitrary message const messageResult = await wallet.signMessage({ signerAddress: wallet.address, message: 'Hello, Alephium!' }) ``` ``` -------------------------------- ### Configuring Network Providers Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Illustrates how to set the current node provider for the Alephium Web3 library to connect to different networks. Examples include mainnet, testnet, devnet, and a custom node with an API key. ```typescript import { web3 } from '@alephium/web3' // Mainnet web3.setCurrentNodeProvider( web3.getDefaultNodeProvider('mainnet') ) // Testnet web3.setCurrentNodeProvider( web3.getDefaultNodeProvider('testnet') ) // Devnet (local) web3.setCurrentNodeProvider( web3.getDefaultNodeProvider('devnet') ) // Custom node with API key web3.setCurrentNodeProvider( 'https://custom-node.example.com', 'your-api-key' ) ``` -------------------------------- ### Unit Testing Transaction Signing Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Provides an example of unit testing transaction signing functionality using vitest. It demonstrates mocking wallet and transaction data to verify that signatures and transaction IDs are correctly generated. ```typescript import { describe, it, expect, vi } from 'vitest' describe('Transaction Signing', () => { it('should sign transfer transactions', async () => { const wallet = new PrivateKeyWallet({ privateKey: '0x...' }) const txData = { signerAddress: wallet.address, destinations: [...] } const result = await wallet.signUnsignedTx({ signerAddress: wallet.address, unsignedTx: mockUnsignedTx }) expect(result.signature).toBeDefined() expect(result.txId).toBeDefined() }) }) ``` -------------------------------- ### Accessing Default Gas Constants Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Provides an example of importing and logging the default gas constants provided by the Alephium Web3 library. These constants represent standard values for gas amount, price, and total cost. ```typescript import { DEFAULT_GAS_AMOUNT, DEFAULT_GAS_PRICE, DEFAULT_GAS_ATTOALPH_AMOUNT } from '@alephium/web3' console.log('Default gas amount:', DEFAULT_GAS_AMOUNT) // 20000 console.log('Default gas price:', DEFAULT_GAS_PRICE) // 10^11 attoAlph console.log('Default total:', DEFAULT_GAS_ATTOALPH_AMOUNT) // 2000000000000000 attoAlph = 0.002 ALPH ``` -------------------------------- ### Struct Class fromJson Example Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/08-smart-contract-module.md Demonstrates deserializing struct metadata from a JSON object, typically obtained from compiler output. ```typescript const struct = Struct.fromJson({ name: 'MyStruct', fieldNames: ['value', 'owner'], fieldTypes: ['U256', 'Address'], isMutable: [true, false] }) ``` -------------------------------- ### Get Default Explorer Provider Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/01-core-providers.md Retrieves a pre-configured explorer provider for a known Alephium network (mainnet, testnet, or devnet). ```typescript const explorerProvider = web3.getDefaultExplorerProvider('testnet') ``` -------------------------------- ### Basic Transfer Transaction Parameters Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/05-types.md Example of constructing parameters for a basic ALPH transfer transaction, specifying the signer, destination, amount, gas, and gas price. ```typescript // A transfer transaction const transferParams: SignTransferTxParams = { signerAddress: account.address, destinations: [ { address: 'tgx7VNFoP9DJiFMFgXXtafQZkUvyEdDHT9ryamHJYrjq', attoAlphAmount: '1000000000000000000' // 1 ALPH } ], gasAmount: 20000, gasPrice: 10n ** 11n } ``` -------------------------------- ### Integration Testing ALPH Transfer on Devnet Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Shows an example of integration testing an ALPH transfer on a local devnet using vitest. It covers setting up the provider, creating wallets, minting tokens, submitting a transfer transaction, and asserting the transaction ID. ```typescript describe('Transfer Integration', () => { it('should transfer ALPH on devnet', async () => { web3.setCurrentNodeProvider('http://127.0.0.1:22973') const wallet = PrivateKeyWallet.Random() const recipient = PrivateKeyWallet.Random() // Mint initial funds await mintToken({ token: { id: ALPH_TOKEN_ID, amount: '1000000000000000000' } }) const result = await wallet.signAndSubmitTransferTx({ signerAddress: wallet.address, destinations: [{ address: recipient.address, attoAlphAmount: '1000000000000000000' }] }) expect(result.txId).toBeDefined() }, { timeout: 30000 }) }) ``` -------------------------------- ### Migration Guide: Sub-path Exports Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Illustrates the change in import paths for sub-modules between v2 and v3 of the Alephium Web3 library. It shows the old import style and the new, more direct import style for modules like api-explorer. ```typescript // Old (v2) import { FungibleTokenMetadata } from '@alephium/web3/dist/src/api/api-explorer' // New (v3) import { FungibleTokenMetadata } from '@alephium/web3/api/explorer' ``` -------------------------------- ### GL Key Type Path Helpers Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Helper functions to get derivation paths for various key types used in GL (Global Ledger) contexts. ```APIDOC ## GL Key Types ### `getGlSecp256K1Path(addressIndex: number): string` Gets the derivation path for a GL SECP256K1 key. ### `getGlSecp256R1Path(addressIndex: number): string` Gets the derivation path for a GL SECP256R1 (P-256) key. ### `getGlEd25519Path(addressIndex: number): string` Gets the derivation path for a GL Ed25519 key. ### `getGlWebauthnPath(addressIndex: number): string` Gets the derivation path for a GL WebAuthn key. ``` -------------------------------- ### Insufficient Gas Error Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Illustrates the common pitfall of insufficient gas leading to an 'out of gas' error. The example shows a transaction failing due to a low gasAmount and provides a hint to use a reasonable amount, such as the DEFAULT_GAS_AMOUNT. ```typescript // Fails with "out of gas" await wallet.signAndSubmitTransferTx({ signerAddress: wallet.address, destinations: [{ ... }], gasAmount: 100 // Too low! }) // Fix: use reasonable gas amount // Use DEFAULT_GAS_AMOUNT (20000) as base ``` -------------------------------- ### Common Patterns: Setting Up Providers Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/12-complete-api-summary.md Demonstrates how to set up node and explorer providers, either globally or per instance. ```APIDOC ## Common Patterns: Setting Up Providers ```typescript // Global setup web3.setCurrentNodeProvider('https://node.testnet.alephium.org') web3.setCurrentExplorerProvider('https://backend.testnet.alephium.org') // Per-instance setup const nodeProvider = new NodeProvider('https://node.testnet.alephium.org') const wallet = new PrivateKeyWallet({ privateKey: '0x...', nodeProvider }) ``` ``` -------------------------------- ### SECP256K1 Key Derivation Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Functions for deriving SECP256K1 private keys from a mnemonic, optionally for a specific group or starting index. Also includes a function to get the derivation path. ```APIDOC ## SECP256K1 (Default) ### `deriveSecp256K1PrivateKey(mnemonic: string, fromAddressIndex?: number, passphrase?: string): string` Derives a SECP256K1 private key from a mnemonic phrase. Allows specifying a starting address index and an optional passphrase. ### `deriveSecp256K1PrivateKeyForGroup(mnemonic: string, targetGroup: number, fromAddressIndex?: number, passphrase?: string): [string, number]` Derives a SECP256K1 private key for a specific target group. Returns the private key and the actual address index used. ### `getSecp259K1Path(addressIndex: number): string` Retrieves the derivation path for a SECP256K1 key at a given address index. ``` -------------------------------- ### Schnorr (BIP340) Key Derivation Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Functions for deriving Schnorr (BIP340) private keys from a mnemonic, optionally for a specific group or starting index. Also includes a function to get the derivation path. ```APIDOC ## Schnorr (BIP340) ### `deriveSchnorrPrivateKey(mnemonic: string, fromAddressIndex?: number, passphrase?: string): string` Derives a Schnorr (BIP340) private key from a mnemonic phrase. Allows specifying a starting address index and an optional passphrase. ### `deriveSchnorrPrivateKeyForGroup(mnemonic: string, targetGroup: number, fromAddressIndex?: number, passphrase?: string): [string, number]` Derives a Schnorr (BIP340) private key for a specific target group. Returns the private key and the actual address index used. ### `getSchnorrPath(addressIndex: number): string` Retrieves the derivation path for a Schnorr (BIP340) key at a given address index. ``` -------------------------------- ### Scaffold a Skeleton Project Source: https://github.com/alephium/alephium-web3/blob/master/README.md Run this command to initialize a new project for smart contract development. ```bash npx @alephium/cli init [-t (base | react | nextjs)] ``` -------------------------------- ### Setting up Wallet for Vitest Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/09-test-utilities.md Demonstrates how to set up a wallet using `testPrivateKeyWallet` within a Vitest `beforeEach` hook for testing purposes. Note that `PrivateKeyWallet` does not require explicit cleanup. ```typescript import { describe, it, beforeEach } from 'vitest' import { testPrivateKeyWallet } from '@alephium/web3-test' describe('Wallet Tests', () => { let wallet beforeEach(() => { wallet = testPrivateKeyWallet }) it('should work', async () => { // Test using wallet }) // Cleanup if needed // (PrivateKeyWallet doesn't require cleanup) }) ``` -------------------------------- ### Get GL Key Type Derivation Paths Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Helper functions to get derivation paths for various GL key types including SECP256K1, SECP256R1, Ed25519, and WebAuthn. ```typescript // SECP256K1 function getGlSecp256K1Path(addressIndex: number): string // SECP256R1 (P-256) function getGlSecp256R1Path(addressIndex: number): string // Ed25519 function getGlEd25519Path(addressIndex: number): string // WebAuthn function getGlWebauthnPath(addressIndex: number): string ``` -------------------------------- ### Build and Test Commands Source: https://github.com/alephium/alephium-web3/blob/master/packages/web3/README.md Commands for building the package, running packaging checks, and executing unit tests. ```bash pnpm build # Build CJS + ESM + types pnpm check # Run publint + attw packaging checks pnpm test # Run unit tests ``` -------------------------------- ### Using Test Utilities for Wallets and Addresses Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/12-complete-api-summary.md Leverage pre-configured test wallets and utilities for creating test accounts with specific mnemonics and indices. ```typescript import { testPrivateKeyWallet, testAddress, testMnemonic } from '@alephium/web3-test' // Use pre-configured test account const wallet = testPrivateKeyWallet // Create test accounts at different indices import { PrivateKeyWallet } from '@alephium/web3-wallet' const account1 = PrivateKeyWallet.FromMnemonic({ mnemonic: testMnemonic, addressIndex: 0 }) const account2 = PrivateKeyWallet.FromMnemonic({ mnemonic: testMnemonic, addressIndex: 1 }) ``` -------------------------------- ### Common Patterns: Creating Accounts Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/12-complete-api-summary.md Illustrates different methods for creating new wallet accounts, including from private keys, randomly, or from mnemonics. ```APIDOC ## Common Patterns: Creating Accounts ```typescript // From private key const wallet1 = new PrivateKeyWallet({ privateKey: '0x...' }) // Randomly const wallet2 = PrivateKeyWallet.Random(targetGroup) // From mnemonic const wallet3 = PrivateKeyWallet.FromMnemonic({ mnemonic: 'word word ...', addressIndex: 0 }) // For specific group const wallet4 = PrivateKeyWallet.FromMnemonicWithGroup( mnemonic, targetGroup ) ``` ``` -------------------------------- ### Create Accounts from Private Key Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/12-complete-api-summary.md Instantiate a wallet using a private key. ```typescript // From private key const wallet1 = new PrivateKeyWallet({ privateKey: '0x...' }) ``` -------------------------------- ### Get Default Primitive Value Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/07-utility-functions.md Retrieves the default value for specified primitive types, such as 'U256' or 'ByteVec'. ```typescript import { getDefaultPrimitiveValue } from '@alephium/web3' const zero = getDefaultPrimitiveValue('U256') const empty = getDefaultPrimitiveValue('ByteVec') ``` -------------------------------- ### Get Transaction Status Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/10-transaction-module.md Retrieve the current status of a submitted transaction using its ID (hash) with the `getTransactionStatus` method. ```APIDOC ## Transaction Status ### `async getTransactionStatus(txId: string): Promise` Get the current status of a submitted transaction. **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | txId | string | Transaction ID (hash) | **Returns:** `Promise` — Current transaction status **Status Values:** - `NotFound` — Transaction not in mempool or confirmed - `MemoryPool` — Transaction pending in mempool - `Confirmed` — Transaction confirmed in a block ```typescript const status = await builder.nodeProvider.transactions.getTransactionsStatus({ txId: '0x...' }) console.log('Status:', status.type) ``` ``` -------------------------------- ### Build Command Source: https://github.com/alephium/alephium-web3/blob/master/README.md Execute this command to build the modernized packages using a dual-build approach. ```bash pnpm build ``` -------------------------------- ### PrivateKeyWallet Usage Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Demonstrates various ways to instantiate and use the `PrivateKeyWallet` class, including creation from a private key, random generation, and derivation from a mnemonic. ```APIDOC ## `PrivateKeyWallet` Class ### Instantiation Methods: 1. **From existing private key:** ```typescript const wallet1 = new PrivateKeyWallet({ privateKey: '0x...' }) ``` 2. **Random wallet generation:** ```typescript // Generates a random wallet const wallet2 = PrivateKeyWallet.Random() // Generates a random wallet in group 1 const wallet2Group1 = PrivateKeyWallet.Random(1) ``` 3. **From mnemonic:** ```typescript const mnemonic = generateMnemonic(12) const wallet3 = PrivateKeyWallet.FromMnemonic({ mnemonic, addressIndex: 0 }) ``` 4. **Mnemonic with target group:** ```typescript const wallet4 = PrivateKeyWallet.FromMnemonicWithGroup(mnemonic, 2) ``` ### Usage Example: ```typescript // Use the wallet to sign and submit transactions const result = await wallet3.signAndSubmitTransferTx({ signerAddress: wallet3.address, destinations: [{ address: wallet4.address, attoAlphAmount: '1000000000000000000' }] }) console.log('Transaction ID:', result.txId) ``` ``` -------------------------------- ### Get Default Node Provider Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/01-core-providers.md Retrieves a pre-configured node provider for a known Alephium network (mainnet, testnet, or devnet). ```typescript const mainnetProvider = web3.getDefaultNodeProvider('mainnet') const testnetProvider = web3.getDefaultNodeProvider('testnet') const devnetProvider = web3.getDefaultNodeProvider('devnet') ``` -------------------------------- ### Get Current Explorer Provider Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/01-core-providers.md Retrieves the currently set global explorer provider. Returns undefined if no provider has been set. ```typescript const explorerProvider = web3.getCurrentExplorerProvider() ``` -------------------------------- ### Set Current Node and Explorer Providers Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/12-complete-api-summary.md Configure the global node and explorer providers for the web3 instance. Alternatively, set up providers for a specific instance. ```typescript // Global setup web3.setCurrentNodeProvider('https://node.testnet.alephium.org') web3.setCurrentExplorerProvider('https://backend.testnet.alephium.org') // Per-instance setup const nodeProvider = new NodeProvider('https://node.testnet.alephium.org') const wallet = new PrivateKeyWallet({ privateKey: '0x...', nodeProvider }) ``` -------------------------------- ### Using Event Subscription Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/07-utility-functions.md Demonstrates how to use the Subscription interface to subscribe to events and unsubscribe when no longer needed. ```typescript import { Subscription } from '@alephium/web3' const subscription: Subscription = subscribeToEvents(options) subscription.subscribe((event) => { console.log('Event received:', event) }) subscription.unsubscribe() ``` -------------------------------- ### Get Transaction Status Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/10-transaction-module.md Retrieves the current status of a submitted transaction using its ID. The status can be NotFound, MemoryPool, or Confirmed. ```typescript const status = await builder.nodeProvider.transactions.getTransactionsStatus({ txId: '0x...' }) console.log('Status:', status.type) ``` -------------------------------- ### enable Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/02-signer-providers.md Connects to and enables the interactive signer with optional configuration. It validates the returned account before returning. ```APIDOC ## enable ### Description Connect to and enable the interactive signer with optional configuration. Validates the returned account before returning. ### Method `async enable(opt?: EnableOptions): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **opt** (EnableOptions) - Optional configuration for the interactive signer ### Request Example None provided in source. ### Response #### Success Response (200) `Promise` — Selected account after validation #### Response Example None provided in source. ### Error Handling Throws `Error` if the account data is invalid. ``` -------------------------------- ### Get Selected Account with PrivateKeyWallet Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Retrieves the account associated with the PrivateKeyWallet. This method always returns the same account for a given wallet instance. ```typescript const wallet = new PrivateKeyWallet({ privateKey: '0x...' }) const account = await wallet.getSelectedAccount() console.log(account.address) ``` -------------------------------- ### Handling Groupless Accounts and Cross-Group Transactions Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Demonstrates creating a groupless account and submitting a cross-group transaction, explicitly specifying the target group. It also shows how to check for and handle necessary funding transactions. ```typescript import { PrivateKeyWallet } from '@alephium/web3-wallet' // Create a groupless account const wallet = new PrivateKeyWallet({ privateKey: '0x...', keyType: 'gl-secp256k1' // Groupless key type }) // When submitting transfer to different group const result = await wallet.signAndSubmitTransferTx({ signerAddress: wallet.address, group: 1, // Explicitly specify target group destinations: [{ address: recipient, attoAlphAmount: '1000000000000000000' }] }) // Check if funding transactions were needed if ('fundingTxs' in result && result.fundingTxs) { console.log(`${result.fundingTxs.length} funding transactions created`) } ``` -------------------------------- ### Instantiate ExplorerProvider Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/01-core-providers.md Instantiate ExplorerProvider with a base URL, optional API key, and custom fetch function. It supports direct instantiation, copying from an existing provider, or using a custom request handler. ```typescript export class ExplorerProvider { constructor(baseUrl: string, apiKey?: string, customFetch?: typeof fetch) constructor(provider: ExplorerProvider) constructor(handler: ApiRequestHandler) } ``` ```typescript const originalProvider = new ExplorerProvider('https://backend.mainnet.alephium.org') const proxiedProvider = ExplorerProvider.Proxy(originalProvider) ``` -------------------------------- ### Get Current Node Provider Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/01-core-providers.md Retrieves the currently set global node provider. This function will throw an error if no provider has been set. ```typescript const provider = web3.getCurrentNodeProvider() ``` -------------------------------- ### PrivateKeyWallet Constructor Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Initializes a new PrivateKeyWallet instance with a given private key and optional configuration. This wallet holds the private key in memory and can sign transactions directly. ```APIDOC ## PrivateKeyWallet Constructor ### Description Initializes a new `PrivateKeyWallet` instance with a given private key and optional configuration. This wallet holds the private key in memory and can sign transactions directly. ### Parameters #### Parameters - **privateKey** (string) - Required - Private key as hex string - **keyType** (KeyType) - Optional - Signature scheme (default, bip340-schnorr, gl-secp256k1, etc.) - **nodeProvider** (NodeProvider) - Optional - Node provider for transaction submission - **explorerProvider** (ExplorerProvider) - Optional - Explorer provider (optional) ``` -------------------------------- ### Import Node API Types Source: https://github.com/alephium/alephium-web3/blob/master/README.md Imports types for interacting with the Alephium full node API. Ensure the package is installed and configured correctly. ```typescript // Node API types (generated from the Alephium full node OpenAPI spec) import { Balance, Transaction } from '@alephium/web3/api/node' ``` -------------------------------- ### Token Transfer Transaction Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Example of constructing and signing a transaction to transfer ALPH and custom tokens. Ensure token amounts match the token's decimals. ```typescript // Example token transfer const result = await wallet.signAndSubmitTransferTx({ signerAddress: wallet.address, destinations: [{ address: recipient, attoAlphAmount: '100000000000000000', tokens: [ { id: '25a2522b0c3ad3b8b1e13c1fed5ac9de36fa2a5d9c89176ce5e80e70d5302f54', amount: '1000000' } ] }] }) ``` -------------------------------- ### EnableOptionsBase Interface Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/05-types.md A base interface for wallet connection options, allowing for arbitrary key-value pairs. ```typescript export interface EnableOptionsBase { [key: string]: any } ``` -------------------------------- ### ExplorerProvider Constructor Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/01-core-providers.md Initializes the ExplorerProvider class to access the Alephium Explorer backend API. It supports direct instantiation with a base URL, copying from an existing provider, or using a custom request handler. ```APIDOC ## ExplorerProvider Constructor ### Description Initializes the ExplorerProvider class to access the Alephium Explorer backend API. It supports direct instantiation with a base URL, copying from an existing provider, or using a custom request handler. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signatures ```typescript constructor(baseUrl: string, apiKey?: string, customFetch?: typeof fetch) constructor(provider: ExplorerProvider) constructor(handler: ApiRequestHandler) ``` ### Parameter Details - **baseUrl** (string) - Required - Explorer backend URL (e.g., `https://backend.mainnet.alephium.org`) - **apiKey** (string) - Optional - Optional API key for authenticated access - **customFetch** (typeof fetch) - Optional - Custom fetch implementation ### Usage Example ```typescript const explorerProvider = new ExplorerProvider('https://backend.mainnet.alephium.org') ``` ``` -------------------------------- ### Get Group of Alephium Address Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/03-address-module.md Use `groupOfAddress` to retrieve the group (shard) number (0-3) to which an Alephium address belongs. Ensure you import the function from '@alephium/web3'. ```typescript import { groupOfAddress } from '@alephium/web3' const group = groupOfAddress('tgx7VNFoP9DJiFMFgXXtafQZkUvyEdDHT9ryamHJYrjq') console.log(`Address is in group ${group}`) ``` -------------------------------- ### Initialize and Set Default ExplorerProvider Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/01-core-providers.md Initializes an ExplorerProvider for a specific network and optionally sets it as the global default. This allows for easy querying of token and contract event information. ```typescript import { ExplorerProvider, web3 } from '@alephium/web3' // Create explorer provider for mainnet const explorerProvider = new ExplorerProvider( 'https://backend.mainnet.alephium.org' ) // Set as global default (optional) web3.setCurrentExplorerProvider(explorerProvider) // Query token information const tokenInfo = await explorerProvider.tokens.getTokensTokenId({ tokenId: '25a2522b0c3ad3b8b1e13c1fed5ac9de36fa2a5d9c89176ce5e80e70d5302f54' }) // Get contract events const events = await explorerProvider.contractEvents.getContractEventsContractaddress({ contractAddress: 'cjw...abc' }) ``` -------------------------------- ### Get Selected Account Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/02-signer-providers.md Retrieves the currently selected account after validation. Ensure the account data is valid, as an error will be thrown if the address does not match the public key. ```typescript const signer = new PrivateKeyWallet({ privateKey: '...' }) const account = await signer.getSelectedAccount() console.log(account.address, account.publicKey) ``` -------------------------------- ### Handle No Node Provider Set Error Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/06-errors.md This snippet shows how to trigger the 'No node provider is set' error when attempting to get the current node provider before it has been configured. ```typescript web3.getCurrentNodeProvider() // Error: No node provider is set. ``` -------------------------------- ### Build Commands for Alephium WalletConnect Provider Source: https://github.com/alephium/alephium-web3/blob/master/packages/walletconnect/README.md Commands to build the package, perform checks, and run tests. Ensure the monorepo build system is configured correctly. ```bash pnpm build # Build CJS + ESM + types pnpm check # Run publint + attw packaging checks pnpm test # Run unit tests (requires WalletConnect relay — see below) ``` -------------------------------- ### Building and Submitting Transactions Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/12-complete-api-summary.md Construct unsigned transactions for transfers, sign them with a wallet, and submit them to the network. ```typescript const builder = TransactionBuilder.from(nodeProvider) const unsignedTx = await builder.buildTransferTx({ signerAddress: address, destinations: [{ address: recipient, attoAlphAmount: amount }] }, publicKey) const signed = await wallet.signUnsignedTx({ signerAddress: address, unsignedTx: unsignedTx.unsignedTx }) const submitted = await wallet.submitTransaction({ unsignedTx: unsignedTx.unsignedTx, signature: signed.signature }) ``` -------------------------------- ### Deploy Contract with Bytecode Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/08-smart-contract-module.md Deploys a compiled Ralph contract using its bytecode and an initial amount of attoAlph. ```typescript const bytecode = '0x0101020304...' // Compiled contract const deployResult = await signer.signAndSubmitDeployContractTx({ signerAddress: signer.address, bytecode, initialAttoAlphAmount: '100000000000000000' }) ``` -------------------------------- ### PrivateKeyWallet.FromMnemonicWithGroup Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/04-wallet-classes.md Creates a PrivateKeyWallet instance from a mnemonic, searching for a key that matches a target group. Allows specifying key type, starting address index, passphrase, and node provider. ```APIDOC ## PrivateKeyWallet.FromMnemonicWithGroup ### Description Create a wallet from a mnemonic, finding a key that matches the target group. ### Method Signature `static FromMnemonicWithGroup(mnemonic: string, targetGroup: number, keyType?: KeyType, fromAddressIndex?: number, passphrase?: string, nodeProvider?: NodeProvider): PrivateKeyWallet` ### Parameters - **mnemonic** (string) - Required - BIP39 mnemonic - **targetGroup** (number) - Required - Target group (0-3) - **keyType** (KeyType) - Optional - Key type (default: 'default') - **fromAddressIndex** (number) - Optional - Starting address index (default: 0) - **passphrase** (string) - Optional - Optional passphrase (default: '') - **nodeProvider** (NodeProvider) - Optional - Node provider (default: global provider) ### Returns `PrivateKeyWallet` — First wallet matching target group ### Example ```typescript const wallet = PrivateKeyWallet.FromMnemonicWithGroup( mnemonic, 1 // Find a key in group 1 ) ``` ``` -------------------------------- ### Derive Private Key for Specific Group Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Find a private key that belongs to a target group by iterating through indices starting from a specified point. Requires the mnemonic and target group number. ```typescript import { deriveSecp256K1PrivateKeyForGroup } from '@alephium/web3-wallet' // Find key in group 2 const [privateKey, usedIndex] = deriveSecp256K1PrivateKeyForGroup( mnemonic, 2, 0 // start searching from index 0 ) console.log(`Key at index ${usedIndex} is in group 2`) ``` -------------------------------- ### Create Remote ExplorerProvider Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/01-core-providers.md Creates an explorer provider with a custom request handler. Useful for testing or remote forwarding. ```typescript const remoteProvider = ExplorerProvider.Remote(async (args) => { // Custom request logic return response }) ``` -------------------------------- ### Expired Mnemonic Passphrase Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/13-advanced-topics.md Explains the pitfall of using an expired or incorrect mnemonic passphrase, which results in deriving a different private key. The example demonstrates how different passphrases lead to distinct wallet instances. ```typescript // Derivation with wrong passphrase const wallet1 = PrivateKeyWallet.FromMnemonic({ mnemonic, passphrase: 'passphrase1' }) const wallet2 = PrivateKeyWallet.FromMnemonic({ mnemonic, passphrase: 'passphrase2' // Different passphrase = different key! }) // wallet1 and wallet2 are different accounts ``` -------------------------------- ### Build Contract Instructions Source: https://github.com/alephium/alephium-web3/blob/master/_autodocs/11-codec-and-encoding.md Construct sequences of contract instructions using predefined types. These are typically generated by the Ralph compiler. ```typescript import { Method, LoadLocal, LoadImmFieldByIndex, ApproveAlph, CallExternal, DestroySelf, Assert } from '@alephium/web3/codec' // Build instruction sequences const instructions: Instr[] = [ { type: 'LoadLocal', index: 0 }, { type: 'ApproveAlph', amount: BigInt(1000) }, { type: 'CallExternal', contractId: '...' }, { type: 'Assert' } ] // These are typically generated by the Ralph compiler ```