### Angular CLI Help Source: https://github.com/ethers-io/ethers.js/blob/main/testcases/test-env/angular/README.md Command to get help with the Angular CLI. ```bash ng help ``` -------------------------------- ### Network Creation Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Examples of creating Network instances. ```typescript import { Network } from "ethers"; const sepolia = Network.from("sepolia"); const custom = new Network("mychain", 1337); ``` -------------------------------- ### Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/providers.md Demonstrates how to get a default provider for the mainnet using ethers.js. ```typescript import { getDefaultProvider } from "ethers"; // Uses Ethers' default API keys const provider = getDefaultProvider("mainnet"); ``` -------------------------------- ### Contract Deployment Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Example of deploying a contract using ContractFactory. ```typescript const factory = new ContractFactory(abi, bytecode, signer); const contract = await factory.deploy(constructorArg1, constructorArg2); ``` -------------------------------- ### FetchRequest Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md An example of creating a FetchRequest, setting headers, and fetching data using getUrl. ```typescript import { FetchRequest } from "ethers"; const req = new FetchRequest("https://api.example.com/data"); req.setHeader("Authorization", "Bearer token"); const resp = await FetchRequest.getUrl(req); ``` -------------------------------- ### Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wallet.md Demonstrates how to create and use a Wallet instance. ```typescript import { Wallet } from "ethers"; // Create new random wallet const wallet = Wallet.create(); // Create from private key const wallet2 = new Wallet("0x..."); // Create from mnemonic const wallet3 = Wallet.fromPhrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"); // Connect to provider const connectedWallet = wallet.connect(provider); // Sign and send transaction const tx = await connectedWallet.sendTransaction({ to: "0x...", value: "1000000000000000000" }); ``` -------------------------------- ### Example of Faster Keystore Encryption Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Example demonstrating faster but less secure keystore encryption using custom N value. ```typescript import { encryptKeystoreJson } from "ethers"; const json = await encryptKeystoreJson( { address: "0x...", privateKey: "0x..." }, "password", { N: 2**14 } // Faster but less secure ); ``` -------------------------------- ### Build Project Source: https://github.com/ethers-io/ethers.js/blob/main/testcases/test-env/angular/README.md Command to build the Angular project for production. ```bash ng build ``` -------------------------------- ### Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wallet.md Demonstrates how to create a Wallet instance from a mnemonic phrase and derive accounts. ```typescript import { Wallet } from "ethers"; const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; const wallet = Wallet.fromPhrase(mnemonic); // Derive first account (m/44'/60'/0'/0/0) const account0 = wallet.derivePath("m/44'/60'/0'/0/0"); // Derive second account const account1 = wallet.derivePath("m/44'/60'/0'/0/1"); ``` -------------------------------- ### Example Usage of Wordlist Class Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wordlists.md Demonstrates how to use the `Wordlist` class methods for getting words, their indices, splitting, and joining phrases. ```typescript import { Wordlist, LangEn } from "ethers"; // Get English wordlist const wordlist = LangEn; // Get word at index 0 const firstWord = wordlist.getWord(0); // "abandon" // Get index of word const index = wordlist.getWordIndex("abandon"); // 0 // Split phrase const words = wordlist.split("abandon abandon abandon ..."); // Join words const phrase = wordlist.join(["abandon", "abandon", ...]); ``` -------------------------------- ### Creating a Wallet Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/README.md Examples of creating a wallet. ```typescript import { Wallet } from "ethers"; // From private key const wallet = new Wallet("0x..."); // From mnemonic const wallet2 = Wallet.fromPhrase("abandon abandon ... about"); // Connect to provider const connectedWallet = wallet.connect(provider); ``` -------------------------------- ### JsonRpcProvider Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/providers.md Example of how to use the JsonRpcProvider to connect to a local node and fetch data. ```typescript import { JsonRpcProvider } from "ethers"; const provider = new JsonRpcProvider("http://localhost:8545"); const balance = await provider.getBalance("0x..."); const blockNumber = await provider.getBlockNumber(); ``` -------------------------------- ### HMAC and Key Derivation Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/crypto.md Example of how to use computeHmac and scrypt functions. ```typescript import { computeHmac, scrypt } from "ethers"; const hmac = computeHmac("sha256", "0xkey", "0xdata"); const derived = await scrypt("password", "salt", 2**14, 8, 1, 32); ``` -------------------------------- ### Transaction Configuration Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Example of constructing a TransactionRequest object. ```typescript const tx = { to: "0x...", from: "0x...", value: parseEther("1.0"), data: "0x", gasLimit: 21000, maxFeePerGas: parseUnits("50", "gwei"), maxPriorityFeePerGas: parseUnits("2", "gwei") }; ``` -------------------------------- ### Example Usage of ID Hash Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/hash.md Shows how to use the `id` function to get an event topic. ```typescript import { id } from "ethers"; // Get event topic const transferTopic = id("Transfer(address,address,uint256)"); // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef ``` -------------------------------- ### Running End-to-End Tests Source: https://github.com/ethers-io/ethers.js/blob/main/testcases/test-env/angular/README.md Command to execute end-to-end tests. ```bash ng e2e ``` -------------------------------- ### Running Unit Tests Source: https://github.com/ethers-io/ethers.js/blob/main/testcases/test-env/angular/README.md Command to execute unit tests using Karma. ```bash ng test ``` -------------------------------- ### TypedDataDomain Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md An example of creating a TypedDataDomain object. ```typescript const domain = { name: "MyApp", version: "1", chainId: 1, verifyingContract: "0x..." }; ``` -------------------------------- ### Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/contract.md Deploy a contract with constructor arguments. ```typescript import { ContractFactory, ethers } from "ethers"; const abi = ["constructor(uint256 initialValue)"]; const bytecode = "0x..."; // Contract bytecode const factory = new ContractFactory(abi, bytecode, signer); // Deploy with constructor arguments const contract = await factory.deploy(100); // Wait for deployment await contract.waitForDeployment(); ``` -------------------------------- ### Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wallet.md Illustrates encrypting an account to keystore JSON and then decrypting it. ```typescript import { encryptKeystoreJson, decryptKeystoreJson } from "ethers"; // Encrypt const encrypted = await encryptKeystoreJson({ address: "0x...", privateKey: "0x..." }, "password"); // Decrypt const account = await decryptKeystoreJson(encrypted, "password"); ``` -------------------------------- ### Example Usage: Number Conversion Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/utils.md Demonstrates how to use getBigInt, toBeHex, and formatEther for number conversions. ```typescript import { getBigInt, toBeHex, formatEther } from "ethers"; const value = getBigInt("1000000000000000000"); const hex = toBeHex(value); // "0xde0b6b3a7640000" const ethers = formatEther(value); // "1.0" ``` -------------------------------- ### Hash Functions Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/crypto.md Example of how to use the keccak256 and sha256 hash functions. ```typescript import { keccak256, sha256 } from "ethers"; const hash = keccak256("0x01"); // "0x5380c7b7ae81a58eb98d9c78de4a1fd7fd5de8ab3c6bb440a2453e8ca7d64aaf" const hash2 = sha256("0x01"); ``` -------------------------------- ### Development Server Source: https://github.com/ethers-io/ethers.js/blob/main/testcases/test-env/angular/README.md Command to run the Angular development server and access the application. ```bash ng serve ``` -------------------------------- ### Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wallet.md Shows how to create a Mnemonic instance from a phrase and compute its seed. ```typescript import { Mnemonic } from "ethers"; // Create from phrase const mnemonic = Mnemonic.fromPhrase("abandon abandon ... about"); // Get seed for wallet derivation const seed = mnemonic.computeSeed(); ``` -------------------------------- ### Install Ethers.js with npm Source: https://github.com/ethers-io/ethers.js/blob/main/README.md Install the ethers.js library using npm for Node.js projects. ```bash /home/ricmoo/some_project> npm install ethers ``` -------------------------------- ### Creating a Provider Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/README.md Examples of creating a provider. ```typescript import { JsonRpcProvider, getDefaultProvider } from "ethers"; // Custom RPC endpoint const provider = new JsonRpcProvider("http://localhost:8545"); // Default Ethers provider with built-in keys const mainnet = getDefaultProvider("mainnet"); ``` -------------------------------- ### Random Number Generation Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/crypto.md Example of how to use the randomBytes function. ```typescript import { randomBytes } from "ethers"; const random = randomBytes(32); // 32 random bytes ``` -------------------------------- ### Code Scaffolding Source: https://github.com/ethers-io/ethers.js/blob/main/testcases/test-env/angular/README.md Command to generate new components or other Angular artifacts. ```bash ng generate component component-name ``` ```bash ng generate directive|pipe|service|class|guard|interface|enum|module ``` -------------------------------- ### assert Function Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/errors.md Example of using the assert function to validate input. ```typescript assert(value > 0, "Value must be positive", "INVALID_ARGUMENT", { argument: "value", value }); ``` -------------------------------- ### Usage Examples Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/constants.md Demonstrates how to use various constants for common tasks like checking for the zero address, converting Wei to Ether, and checking for maximum values. ```typescript import { ZeroAddress, WeiPerEther, MaxUint256 } from "ethers"; // Check if address is zero if (address === ZeroAddress) { console.log("Burn address"); } // Convert Wei to Ether const etherAmount = wei / WeiPerEther; // Check for max value if (value === MaxUint256) { console.log("Maximum value"); } ``` -------------------------------- ### isCallException Function Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/errors.md Example usage of the isCallException type guard. ```typescript if (isCallException(err)) { console.log("Contract reverted:", err.reason); } ``` -------------------------------- ### Example Usage of Typed Data Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/hash.md Demonstrates how to use TypedDataEncoder to hash data and verifyTypedData to verify a signature. ```typescript import { TypedDataEncoder, verifyTypedData } from "ethers"; const domain = { name: "MyApp", version: "1", chainId: 1, verifyingContract: "0x..." }; const types = { Message: [ { name: "content", type: "string" }, { name: "timestamp", type: "uint256" } ] }; const value = { content: "Hello", timestamp: 123456789 }; // Hash the data const hash = TypedDataEncoder.from(types).hash(value); // Verify signature const signer = verifyTypedData(domain, types, value, signature); ``` -------------------------------- ### Example Usage: Data Encoding Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/utils.md Demonstrates how to use concat, hexlify, and dataSlice for data manipulation. ```typescript import { concat, hexlify, dataSlice } from "ethers"; const combined = concat(["0x1234", "0x5678"]); // "0x12345678" const bytes = hexlify([1, 2, 3]); // "0x010203" const slice = dataSlice("0x123456", 1, 2); // "0x34" ``` -------------------------------- ### Example Usage - Contract Address Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/address.md Demonstrates how to compute contract addresses using CREATE and CREATE2 methods. ```typescript import { getCreateAddress, getCreate2Address } from "ethers"; // Get address from CREATE (traditional) const addr = getCreateAddress({ from: "0x1234567890123456789012345678901234567890", nonce: 0 }); // Get address from CREATE2 (deterministic) const addr2 = getCreate2Address({ from: "0x1234567890123456789012345678901234567890", salt: "0x0000000000000000000000000000000000000000000000000000000000000001", initCodeHash: "0x..." // keccak256 of contract bytecode }); ``` -------------------------------- ### Interface Usage Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/abi.md Demonstrates how to create an Interface instance, encode function calls, decode function results, parse transactions, and parse event logs using ethers.js. ```typescript import { Interface } from "ethers"; // Create interface from JSON ABI const abi = [ "function balanceOf(address owner) view returns (uint256)", "function transfer(address to, uint256 amount) returns (bool)", "event Transfer(address indexed from, address indexed to, uint256 value)" ]; const iface = new Interface(abi); // Encode function call const data = iface.encodeFunctionData("transfer", ["0x1234....", "1000000000000000000"]); // Decode function result const result = iface.decodeFunctionResult("balanceOf", "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000"); // Parse transaction const parsed = iface.parseTransaction({ data }); if (parsed) { console.log(parsed.name); // "transfer" console.log(parsed.args); // [to, amount] } // Parse event log const logDesc = iface.parseLog({ topics: ["0xddf252ad..."], data: "0x0000..." }); ``` -------------------------------- ### Sending a Transaction Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/README.md Example of sending a transaction. ```typescript const signer = wallet.connect(provider); const tx = await signer.sendTransaction({ to: recipientAddress, value: parseEther("1.0") }); const receipt = await tx.wait(); ``` -------------------------------- ### makeError Function Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/errors.md Example of creating a custom error using makeError. ```typescript throw makeError("Custom message", "INVALID_ARGUMENT", { argument: "amount", value: -100 }); ``` -------------------------------- ### Test Runner Setup Source: https://github.com/ethers-io/ethers.js/blob/main/misc/test-browser/index.html This script sets up the testing environment by importing Mocha, a custom reporter, and the test suite, then runs the tests. ```javascript // Must import Mocha first; completely await import("./static/mocha.js"); // Load our custom Reporter (after importing mocha) import { MyReporter } from "/static/reporter.js"; // Setup the global environment and set out reporter mocha.setup({ ui: 'bdd' }); mocha.reporter(MyReporter); // Import the tests await import("./tests/index.js"); // Run Mocha! mocha.run(); ``` -------------------------------- ### Error Handling Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/README.md Example of using type guards for safe error handling. ```typescript try { // code } catch (e) { if (isError(e, "CALL_EXCEPTION")) { // e is typed as CallExceptionError console.log(e.reason); } } ``` -------------------------------- ### AccessList Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/transaction.md Demonstrates using the accessListify function. ```typescript import { accessListify } from "ethers"; const accessList = accessListify({ to: "0x...", data: "0x...", accessList: [ { address: "0x...", storageKeys: [ "0x0000000000000000000000000000000000000000000000000000000000000000" ] } ] }); ``` -------------------------------- ### Usage Example: Wallet Creation and Mnemonic Validation Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wordlists.md Demonstrates creating a wallet from a mnemonic phrase using a specific wordlist and validating/splitting a mnemonic. ```typescript import { Wallet, LangEn, wordlists } from "ethers"; // Create wallet from mnemonic using English wordlist const wallet = Wallet.fromPhrase("abandon abandon abandon ... about", undefined, LangEn); // Or use global wordlists object const spanishWordlist = wordlists.es; // Validate and split mnemonic const words = spanishWordlist.split("mezclar múltiple ..."); ``` -------------------------------- ### Bytes32 String Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/abi.md Illustrates the usage of encodeBytes32String and decodeBytes32String. ```typescript import { encodeBytes32String, decodeBytes32String } from "ethers"; const encoded = encodeBytes32String("hello"); const decoded = decodeBytes32String(encoded); // decoded === "hello" ``` -------------------------------- ### AbiCoder Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/abi.md Demonstrates how to use the AbiCoder to encode and decode contract data. ```typescript import { AbiCoder } from "ethers"; const coder = AbiCoder.defaultAbiCoder(); // Encode const encoded = coder.encode( ["address", "uint256"], ["0x1234567890123456789012345678901234567890", 100] ); // Decode const decoded = coder.decode(["address", "uint256"], encoded); ``` -------------------------------- ### Calling a Contract Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/README.md Example of calling a contract method. ```typescript import { Contract } from "ethers"; const contract = new Contract(address, abi, provider); const balance = await contract.balanceOf(userAddress); ``` -------------------------------- ### Address Computation Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/transaction.md Shows how to use computeAddress and recoverAddress. ```typescript import { computeAddress, recoverAddress } from "ethers"; // Get address from public key const addr = computeAddress(publicKey); // Recover signer from message and signature const signer = recoverAddress(messageHash, signature); ``` -------------------------------- ### Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/contract.md Create contract instance, call read-only function, listen to events, and query historical events. ```typescript import { Contract, ethers } from "ethers"; const abi = [ "function balanceOf(address) view returns (uint256)", "function transfer(address, uint256) returns (bool)", "event Transfer(address indexed from, address indexed to, uint256 value)" ]; // Create contract instance const contract = new Contract( "0x...", // contract address abi, provider ); // Call read-only function const balance = await contract.balanceOf("0x..."); // Listen to events contract.on("Transfer", (from, to, value) => { console.log(`Transfer: ${from} -> ${to}: ${value}`); }); // Query historical events const events = await contract.queryFilter("Transfer", 0, "latest"); ``` -------------------------------- ### Typed Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/abi.md Shows how to use the Typed class to specify Solidity types for contract function calls. ```typescript import { Interface, Typed } from "ethers"; const iface = new Interface(["function func(int, uint)"]); // Explicitly specify types to disambiguate overloads const data = iface.encodeFunctionData("func", [ Typed.int(-42), Typed.uint(42) ]); ``` -------------------------------- ### Example Usage - Core Address Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/address.md Demonstrates how to use core address functions for validation, checksumming, and ENS resolution. ```typescript import { getAddress, isAddress } from "ethers"; // Validate and get checksum address const addr = getAddress("0x1234567890123456789012345678901234567890"); // Returns: "0x1234567890123456789012345678901234567890" (checksummed) // Check if valid if (isAddress("0x1234567890123456789012345678901234567890")) { console.log("Valid address"); } // Resolve ENS or Addressable const resolved = await resolveAddress("vitalik.eth"); ``` -------------------------------- ### Handling CallExceptionError Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/errors.md Example of how to catch and handle a CallExceptionError in TypeScript. ```typescript try { await contract.someMethod(); } catch (e) { if (isError(e, "CALL_EXCEPTION")) { console.log("Revert reason:", e.reason); console.log("Revert data:", e.data); } } ``` -------------------------------- ### Transaction Class Example Usage Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/transaction.md Demonstrates creating Transaction objects from an object and a raw transaction, and retrieving the transaction hash. ```typescript import { Transaction } from "ethers"; // Create from object const tx = new Transaction({ to: "0x...", value: "1000000000000000000", // 1 ETH data: "0x", gasLimit: 21000, gasPrice: "20000000000" }); // Create from raw transaction const tx2 = Transaction.from("0x..."); // Get transaction hash (only for signed tx) if (tx2.signature) { console.log(tx2.hash()); } ``` -------------------------------- ### AddressLike Type Implementations Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/address.md Example implementations of the AddressLike type, including hex string, Addressable object, and ENS name. ```typescript // Hex string const addr = "0x1234567890123456789012345678901234567890"; // Addressable object const contract: Addressable = { getAddress: async () => "0x1234567890123456789012345678901234567890" }; // ENS name const ensName = "vitalik.eth"; ``` -------------------------------- ### Accessing Wordlists via Global Object Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wordlists.md Example of how to import and access specific wordlists from the global `wordlists` object. ```typescript import { wordlists } from "ethers"; const englishWordlist = wordlists.en; const spanishWordlist = wordlists.es; ``` -------------------------------- ### Wallet Creation from Private Key Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Creates a Wallet instance from a private key. ```typescript const wallet = new Wallet(privateKey, provider?); ``` -------------------------------- ### isError Function Example Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/errors.md Example usage of the isError type guard to narrow down error types. ```typescript try { // code } catch (e) { if (isError(e, "CALL_EXCEPTION")) { // e is now typed as CallExceptionError console.log(e.data); } } ``` -------------------------------- ### Network Creation Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Constructor for creating a Network instance. ```typescript const network = new Network(name: string, chainId: BigNumberish); ``` -------------------------------- ### BrowserProvider Options Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md BrowserProvider constructor. ```typescript class BrowserProvider extends JsonRpcApiProvider { constructor(ethereum?: Eip1193Provider, network?: Networkish); } ``` -------------------------------- ### Interface Creation from Human-Readable Fragments Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Creating an Interface from an array of human-readable ABI fragments. ```typescript const abi = [ "function balanceOf(address owner) view returns (uint256)", "function transfer(address to, uint256 amount) returns (bool)", "event Transfer(address indexed from, address indexed to, uint256 value)", "error InsufficientBalance()" ]; const iface = new Interface(abi); ``` -------------------------------- ### Wallet Creation from Mnemonic Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Creates a Wallet instance from a mnemonic phrase. ```typescript const wallet = Wallet.fromPhrase( mnemonic: string, path?: string, wordlist?: Wordlist ); ``` -------------------------------- ### FallbackProvider Options Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md FallbackProvider constructor. ```typescript class FallbackProvider { constructor(providers: Array, quorumPercentage?: number); } ``` -------------------------------- ### Keystore Encryption Options Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Interface for Keystore encryption options. ```typescript interface EncryptOptions { iv?: BytesLike; salt?: BytesLike; N?: number; r?: number; p?: number; } ``` -------------------------------- ### BigNumberish Type Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/types.md Represents any value that can be converted to a bigint. Examples include hex strings, numbers, or bigints. ```typescript type BigNumberish = string | number | bigint; ``` -------------------------------- ### Random Wallet Creation Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Creates a random Wallet instance. ```typescript const wallet = Wallet.create(); ``` -------------------------------- ### AbstractProvider Options Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Interface for AbstractProvider options. ```typescript interface AbstractProviderOptions { staticNetwork?: Network; polling?: boolean; pollingInterval?: number; cacheOpenLimit?: number; } ``` -------------------------------- ### Mixed Array Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Demonstrates creating an ABI array with mixed types, including function signatures, event definitions, and existing fragments. ```typescript const abi = [ "function balanceOf(address) view returns (uint256)", { type: "event", name: "Transfer", inputs: [...] }, iface.fragments[0] ]; const iface = new Interface(abi); ``` -------------------------------- ### Interface Creation from JSON String Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Creating an Interface from a JSON string ABI. ```typescript const abi = '[{"type":"function","name":"transfer",...}]'; const iface = new Interface(abi); ``` -------------------------------- ### Contract Creation Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Constructor for creating a Contract instance. ```typescript const contract = new Contract( target: string | Addressable, abi: Interface | InterfaceAbi, runner?: null | ContractRunner, _deployTx?: null | TransactionResponse ); ``` -------------------------------- ### Interface Creation Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Constructor for creating an Interface instance. ```typescript const iface = new Interface(fragments: InterfaceAbi); ``` -------------------------------- ### Interface Creation from JSON Fragments Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Creating an Interface from an array of JSON ABI fragments. ```typescript const abi = [ { type: "function", name: "transfer", inputs: [{ name: "to", type: "address" }, { name: "amount", type: "uint256" }], outputs: [{ name: "", type: "bool" }], stateMutability: "nonpayable" } ]; const iface = new Interface(abi); ``` -------------------------------- ### BrowserProvider Class Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/providers.md Connects to MetaMask or EIP-6963 compatible wallet in browser. ```typescript class BrowserProvider extends JsonRpcApiProvider { constructor(ethereum?: Eip1193Provider, network?: Networkish); static from(ethereum: any): Promise; getSigner(address?: string): Promise; } ``` -------------------------------- ### JsonRpcProvider Options Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Interface for JsonRpcProvider options. ```typescript class JsonRpcProvider extends AbstractProvider { constructor(url?: string, networkish?: Networkish, options?: JsonRpcApiProviderOptions); } interface JsonRpcApiProviderOptions { staticNetwork?: boolean; batchStallTime?: number; batchMaxCount?: number; batchMaxSize?: number; cacheOpenLimit?: number; pollingInterval?: number; maxRetries?: number; projectId?: string; projectSecret?: string; } ``` -------------------------------- ### Utility Constants and Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wallet.md Includes default path constants and functions for deriving account paths. ```typescript const defaultPath: string = "m/44'/60'/0'/0/0"; function getAccountPath(index: number): string; function getIndexedAccountPath(index: number): string; ``` -------------------------------- ### ContractFactory Creation Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Constructor for creating a ContractFactory instance. ```typescript const factory = new ContractFactory( abi: Interface | InterfaceAbi, bytecode: BytesLike, runner?: null | ContractRunner ); ``` -------------------------------- ### Fetch Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/utils.md Classes and types for handling network requests. ```typescript class FetchRequest { url: string; method: string; headers: Record; body: null | Uint8Array; constructor(url: string); static create(options: any): FetchRequest; setHeader(key: string, value: string): this; getHeader(key: string): undefined | string; static getUrl(req: FetchRequest): Promise; } class FetchResponse { readonly status: number; readonly headers: Record; readonly body: Uint8Array; readonly statusText: string; constructor(body: BytesLike, status: number, headers: Record); static create(body: BytesLike, status: number, headers?: Record): FetchResponse; text(): Promise; json(): Promise; } type FetchCancelSignal = { readonly cancelled: boolean; throwIfCancelled(): void; }; type GetUrlResponse = { statusCode: number; headers: Record>; body: Uint8Array | null; }; type FetchPreflightFunc = (req: FetchRequest) => void | Promise; type FetchProcessFunc = (req: FetchRequest, resp: FetchResponse) => FetchResponse | Promise; type FetchRetryFunc = (req: FetchRequest, resp: FetchResponse, attempt: number) => boolean | Promise; type FetchGatewayFunc = (url: string) => string; type FetchGetUrlFunc = (req: FetchRequest, signal?: FetchCancelSignal) => Promise; ``` -------------------------------- ### Solidity Hash Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/hash.md Packs values according to Solidity ABI (no padding), packs values and hashes with Keccak-256, and packs values and hashes with SHA-256. ```typescript function solidityPacked(types: Array, values: Array): string; function solidityPackedKeccak256(types: Array, values: Array): string; function solidityPackedSha256(types: Array, values: Array): string; ``` ```typescript import { solidityPackedKeccak256 } from "ethers"; const hash = solidityPackedKeccak256( ["address", "uint256"], ["0x1234567890123456789012345678901234567890", 100] ); ``` -------------------------------- ### Type Definitions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wallet.md Type definitions for Wallet related classes. ```typescript type KeystoreAccount = { address: string; privateKey: string; }; type CrowdsaleAccount = { address: string; privateKey: string; }; type EncryptOptions = { iv?: BytesLike; salt?: BytesLike; N?: number; r?: number; p?: number; }; ``` -------------------------------- ### Extra Wordlists Import Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wordlists.md How to import additional wordlists that are not part of the standard BIP-39 set. ```typescript // import { wordlistsExtra } from "ethers/wordlists"; const wordlistsExtra: Record; ``` -------------------------------- ### AbstractSigner Class Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/providers.md The `AbstractSigner` class provides a base implementation for custom signers. ```typescript class AbstractSigner implements Signer { provider: null | Provider; constructor(provider?: null | Provider); abstract getAddress(): Promise; abstract signTransaction(tx: TransactionRequest): Promise; // Implemented methods sendTransaction(tx: TransactionRequest): Promise; signMessage(message: string | Uint8Array): Promise; signTypedData(domain: TypedDataDomain, types: Record>, value: Record): Promise; // ... other methods } ``` -------------------------------- ### File Organization Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/README.md Directory structure for the ethers.js project. ```bash output/ ├── README.md # This file ├── api-reference/ # Module API reference │ ├── abi.md │ ├── address.md │ ├── contract.md │ ├── crypto.md │ ├── hash.md │ ├── providers.md │ ├── transaction.md │ ├── wallet.md │ ├── utils.md │ ├── constants.md │ └── wordlists.md ├── types.md # Type definitions ├── errors.md # Error reference └── configuration.md # Configuration options ``` -------------------------------- ### SigningKey Class Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/crypto.md The SigningKey class wraps a private key and provides signing operations. ```typescript class SigningKey { readonly privateKey: string; readonly publicKey: string; readonly compressedPublicKey: string; constructor(privateKey: BytesLike); sign(digest: BytesLike): Signature; signSync(digest: BytesLike): Signature; computeSharedSecret(otherPublicKey: string | SigningKey): string; static addPoints(p0: string, p1: string, compressed?: boolean): string; } ``` ```typescript import { SigningKey, keccak256 } from "ethers"; const key = new SigningKey("0x..."); // Sign a message hash const digest = keccak256("0xHello"); const signature = key.sign(digest); // Get public key const publicKey = key.publicKey; // Compute shared secret const secret = key.computeSharedSecret(otherPublicKey); ``` -------------------------------- ### Wallet Class Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wallet.md Represents a single Ethereum account with a private key. ```typescript class Wallet extends BaseWallet { readonly provider: null | Provider; constructor(privateKey: BytesLike | SigningKey, provider?: null | Provider); connect(provider: null | Provider): Wallet; static create(): Wallet; static fromPhrase(mnemonic: string | Mnemonic, path?: string, wordlist?: Wordlist): HDNodeWallet; static fromMnemonic(mnemonic: Mnemonic, path?: string): HDNodeWallet; static fromSeed(seed: BytesLike): HDNodeWallet; static fromEncryptedJson(json: string, password: string | Uint8Array, progress?: ProgressCallback): Promise; static fromEncryptedJsonSync(json: string, password: string | Uint8Array): Wallet; } ``` -------------------------------- ### Unit Conversion Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/utils.md Provides functions for converting between Ether (wei) and other units, and for parsing/formatting values with a specified number of decimals. ```typescript function parseEther(ether: string | bigint): bigint; function formatEther(wei: BigNumberish): string; function parseUnits(value: string, decimals: number | string): bigint; function formatUnits(value: BigNumberish, decimals: number | string): string; ``` ```typescript import { parseEther, formatEther, parseUnits, formatUnits } from "ethers"; const wei = parseEther("1.5"); // 1500000000000000000n const ether = formatEther(wei); // "1.5" const usdc = parseUnits("100", 6); // 100000000n const amount = formatUnits(usdc, 6); // "100.0" ``` -------------------------------- ### Include Ethers.js in the Browser (ESM) Source: https://github.com/ethers-io/ethers.js/blob/main/README.md Include the bundled ethers.js library in an HTML file using an ES Module script tag. ```html ``` -------------------------------- ### ParamTypeWalkFunc Type Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/types.md Callback for walking parameter types. ```typescript type ParamTypeWalkFunc = (type: string) => string; ``` -------------------------------- ### JsonRpcProvider Class Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/providers.md The `JsonRpcProvider` connects to a JSON-RPC endpoint. ```typescript class JsonRpcProvider extends AbstractProvider { readonly url: string; constructor(url?: string, networkish?: Networkish, options?: JsonRpcApiProviderOptions); getRpcUrl(): string; send(method: string, params: Array): Promise; static defaultUrl(): string; static static from(url: string): JsonRpcProvider; } ``` -------------------------------- ### NotImplementedError Interface Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/errors.md Indicates functionality that is planned but not yet implemented. ```typescript interface NotImplementedError extends EthersError<"NOT_IMPLEMENTED"> { operation: string; } ``` -------------------------------- ### FetchRequest Class Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/configuration.md Defines the properties of the FetchRequest class used for making HTTP requests. ```typescript class FetchRequest { url: string; method: string; headers: Record; body: null | Uint8Array; } ``` -------------------------------- ### getDefaultProvider Function Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/providers.md Creates a provider using Ethers-managed API keys for a given network. ```typescript function getDefaultProvider(network?: Networkish, options?: any): Provider; ``` -------------------------------- ### ParamTypeWalkAsyncFunc Type Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/types.md Async callback for walking parameter types. ```typescript type ParamTypeWalkAsyncFunc = (type: string) => Promise; ``` -------------------------------- ### Built-in Wordlist Classes Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wordlists.md TypeScript classes representing built-in BIP-39 wordlists for various languages. ```typescript class LangEn extends Wordlist; // English class LangCz extends Wordlist; // Czech class LangFr extends Wordlist; // French class LangIt extends Wordlist; // Italian class LangJa extends Wordlist; // Japanese class LangKo extends Wordlist; // Korean class LangPt extends Wordlist; // Portuguese class LangEs extends Wordlist; // Spanish class LangZh extends Wordlist; // Simplified Chinese class LangZhTw extends Wordlist; // Traditional Chinese ``` -------------------------------- ### EncryptOptions Type Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/types.md Defines options for keystore encryption. ```typescript type EncryptOptions = { iv?: BytesLike; salt?: BytesLike; N?: number; r?: number; p?: number; }; ``` -------------------------------- ### ServerError Interface Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/errors.md Server request failed. ```typescript interface ServerError extends EthersError<"SERVER_ERROR"> { request: FetchRequest | string; response?: FetchResponse; } ``` -------------------------------- ### NetworkError Interface Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/errors.md Problem connecting to network. ```typescript interface NetworkError extends EthersError<"NETWORK_ERROR"> { event: string; } ``` -------------------------------- ### UnsupportedOperationError Interface Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/errors.md Operation is not supported by this configuration or provider. ```typescript interface UnsupportedOperationError extends EthersError<"UNSUPPORTED_OPERATION"> { operation: string; } ``` -------------------------------- ### Events and Listeners Types Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/utils.md Defines types for event payloads, event emitters, and listeners, enabling a robust event handling system. ```typescript type EventPayload = Array; type EventEmitterable = { on(event: T, listener: Listener): this; once(event: T, listener: Listener): this; emit(event: T, ...args: Array): boolean; off(event: T, listener?: Listener): this; removeAllListeners(event?: T): this; }; type Listener = (...args: Array) => any; ``` -------------------------------- ### Hash Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/crypto.md Provides functions for computing Keccak-256, SHA-256, SHA-512, and RIPEMD-160 hashes. ```typescript function keccak256(data: BytesLike): string; function sha256(data: BytesLike): string; function sha512(data: BytesLike): string; function ripemd160(data: BytesLike): string; ``` -------------------------------- ### Block and Transaction Types Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/providers.md Defines the structure for Block, TransactionResponse, TransactionReceipt, and Log objects. ```typescript class Block { readonly provider: Provider; readonly number: number; readonly hash: null | string; readonly timestamp: number; readonly parentHash: string; readonly gasLimit: bigint; readonly gasUsed: bigint; readonly miner: string; // ... other properties } class TransactionResponse { readonly blockNumber: null | number; readonly blockHash: null | string; readonly hash: string; readonly from: string; readonly to: null | string; readonly gasLimit: bigint; readonly gasPrice: bigint; readonly value: bigint; readonly data: string; readonly nonce: number; // ... other properties wait(confirms?: number): Promise; } class TransactionReceipt { readonly hash: string; readonly blockNumber: number; readonly blockHash: string; readonly index: number; readonly from: string; readonly to: null | string; readonly gasUsed: bigint; readonly cumulativeGasUsed: bigint; readonly status: null | number; readonly logs: Array; // ... other properties } class Log { readonly provider: Provider; readonly blockNumber: number; readonly blockHash: string; readonly transactionHash: string; readonly transactionIndex: number; readonly address: string; readonly data: string; readonly topics: Array; readonly index: number; // ... other properties } ``` -------------------------------- ### String Constants Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/constants.md Provides string constants for the Ether symbol and message signing prefix. ```typescript const EtherSymbol: string = "Ξ"; const MessagePrefix: string = "\x19Ethereum Signed Message:\n"; ``` -------------------------------- ### KeystoreAccount Type Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/types.md Defines the structure for an account loaded from a keystore file. ```typescript type KeystoreAccount = { address: string; privateKey: string; }; ``` -------------------------------- ### Type Definitions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/utils.md Common type definitions used throughout the library. ```typescript type BytesLike = string | Uint8Array; type BigNumberish = string | number | bigint; type Numeric = number | bigint; type ErrorCode = "UNKNOWN_ERROR" | "NOT_IMPLEMENTED" | "UNSUPPORTED_OPERATION" | "NETWORK_ERROR" | "SERVER_ERROR" | "TIMEOUT" | "BAD_DATA" | "CANCELLED" | "BUFFER_OVERRUN" | "NUMERIC_FAULT" | "INVALID_ARGUMENT" | "MISSING_ARGUMENT" | "UNEXPECTED_ARGUMENT" | "CALL_EXCEPTION" | "INSUFFICIENT_FUNDS" | "NONCE_EXPIRED" | "OFFCHAIN_FAULT" | "REPLACEMENT_UNDERPRICED" | "TRANSACTION_REPLACED" | "UNCONFIGURED_NAME" | "ACTION_REJECTED"; type UnicodeNormalizationForm = "NFC" | "NFD" | "NFKC" | "NFKD"; type Utf8ErrorReason = "overlong" | "out-of-range" | "utf16-surrogate" | "unexpected-continuation" | "invalid-codepoint"; ``` -------------------------------- ### AccessList and AccessListish Types Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/types.md Defines the structure for pre-warmed account and storage slots, and its more flexible 'ish' counterpart. ```typescript type AccessList = Array<{ address: AddressLike; storageKeys: Array; }>; type AccessListish = AccessList | Array<[AddressLike, Array]>; ``` -------------------------------- ### Utility Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/providers.md Provides utility functions for transaction requests and throttle messages. ```typescript function copyRequest(req: TransactionRequest): PreparedTransactionRequest; function showThrottleMessage(message: string): void; ``` -------------------------------- ### JSON Keystore Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wallet.md Provides functions for encrypting and decrypting account data to and from keystore JSON format. ```typescript function encryptKeystoreJson(account: KeystoreAccount, password: string | Uint8Array, options?: EncryptOptions): Promise; function encryptKeystoreJsonSync(account: KeystoreAccount, password: string | Uint8Array, options?: EncryptOptions): string; function decryptKeystoreJson(json: string, password: string | Uint8Array, progress?: ProgressCallback): Promise; function decryptKeystoreJsonSync(json: string, password: string | Uint8Array): KeystoreAccount; function isKeystoreJson(json: string): boolean; ``` -------------------------------- ### HMAC and Key Derivation Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/crypto.md Provides functions for computing HMAC digests and deriving keys using PBKDF2 and Scrypt. ```typescript function computeHmac(algorithm: "sha256" | "sha512", key: BytesLike, data: BytesLike): string; function pbkdf2(password: BytesLike, salt: BytesLike, iterations: number, keylen: number, algo: "sha256" | "sha512"): string; function scrypt(password: BytesLike, salt: BytesLike, N: number, r: number, p: number, dkLen: number): Promise; function scryptSync(password: BytesLike, salt: BytesLike, N: number, r: number, p: number, dkLen: number): string; ``` -------------------------------- ### Properties and Objects Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/utils.md Functions for defining properties on objects and resolving properties that may be promises. ```typescript function defineProperties(target: T, props: Record): T; function resolveProperties(props: Record): Promise>; ``` -------------------------------- ### Optimized Wordlist Implementations Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wordlists.md TypeScript classes for optimized wordlist implementations offering improved compression. ```typescript class WordlistOwl extends Wordlist; // Optimized with OWL format class WordlistOwlA extends Wordlist; // Optimized with OWLA format ``` -------------------------------- ### Base Encoding Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/utils.md Provides functions for encoding and decoding data using Base58 and Base64. ```typescript function encodeBase58(data: BytesLike): string; function decodeBase58(value: string): string; function encodeBase64(data: BytesLike): string; function decodeBase64(value: string): string; ``` -------------------------------- ### UnknownError Interface Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/errors.md Catch-all error when the underlying problem cannot be determined. ```typescript interface UnknownError extends EthersError<"UNKNOWN_ERROR"> { [key: string]: any; } ``` -------------------------------- ### Core Address Functions Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/address.md Provides functions for validating, formatting, and resolving Ethereum addresses. ```typescript function getAddress(address: AddressLike): string; function isAddress(address: any): boolean; function isAddressable(obj: any): boolean; function resolveAddress(address: AddressLike): Promise; function getIcapAddress(address: AddressLike): string; ``` -------------------------------- ### Browser Support Export Source: https://github.com/ethers-io/ethers.js/blob/main/_autodocs/api-reference/wordlists.md Special export for accessing wordlists in browser environments, optimized for size. ```typescript // import { wordlists } from "ethers/wordlists"; // Browser-optimized wordlist access ```