### Quick Start with Viem Source: https://github.com/shazow/whatsabi/blob/main/README.md Shows how to use WhatsABI with the Viem library for contract ABI retrieval. It requires 'viem' and '@shazow/whatsabi'. The example initializes a Viem client and then uses WhatsABI's autoload function. ```typescript import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' import { whatsabi } from "@shazow/whatsabi"; const client = createPublicClient({ chain: mainnet, transport: http() }) const result = await whatsabi.autoload(address, { provider: client }); ``` -------------------------------- ### Quick Start with Ethers.js Source: https://github.com/shazow/whatsabi/blob/main/README.md Demonstrates how to quickly get the ABI for a given contract address using WhatsABI with Ethers.js. It requires the 'ethers' library and the '@shazow/whatsabi' package. The function returns the contract's ABI. ```typescript import { ethers } from "ethers"; import { whatsabi } from "@shazow/whatsabi"; // Works with any provider (or client) library like Ethers.js, Viem, or Web3.js! const provider = ethers.getDefaultProvider(); const address = "0x00000000006c3852cbEf3e08E8dF289169EdE581"; // Or your fav contract address // Quick-start: const result = await whatsabi.autoload(address, { provider }); console.log(result.abi); // -> [ ... ] ``` -------------------------------- ### Auto-following Resolved Proxies Source: https://github.com/shazow/whatsabi/blob/main/README.md A concise example demonstrating how to use whatsabi.autoload with the `followProxies: true` option to automatically resolve to the implementation address of a proxy contract and retrieve its ABI. It also shows how to access the resolved address. ```typescript const { abi, address } = await whatsabi.autoload( "0x4f8AD938eBA0CD19155a835f617317a6E788c868", { provider, followProxies: true, }, }); console.log("Resolved to:", address); // -> "0x964f84048f0d9bb24b82413413299c0a1d61ea9f" ``` -------------------------------- ### Advanced autoload with custom loaders and env settings Source: https://github.com/shazow/whatsabi/blob/main/README.md Demonstrates advanced usage of whatsabi.autoload with optional loaders, signature lookups, and environment-specific settings like chain ID and API keys. It also shows how to configure progress and error hooks. The function can return detailed contract metadata. ```typescript ... let result = await whatsabi.autoload(address, { provider: provider, // * Optional loaders: // abiLoader: whatsabi.loaders.defaultABILoader, // signatureLoader: whatsabi.loaders.defaultSignatureLookup, // There is a handy helper for adding the default loaders but with your own settings ... whatsabi.loaders.defaultsWithEnv({ CHAIN_ID: 42161, ETHERSCAN_API_KEY: "MYSECRETAPIKEY", }), // * Optional hooks: // onProgress: (phase: string) => { ... } // onError: (phase: string, context: any) => { ... } onProgress: (phase) => console.log("autoload progress", phase), onError: (phase, context) => console.log("autoload error", phase, context), // * Optional overrides: // addressResolver: (name: string) => Promise // * Optional settings: // followProxies: false, // enableExperimentalMetadata: false, }); console.log(result.abi); ``` -------------------------------- ### Internal Mechanics of autoload Source: https://github.com/shazow/whatsabi/blob/main/README.md Explains the internal steps taken by the whatsabi.autoload function. It covers fetching bytecode, extracting selectors, generating ABI from bytecode, and using signature lookup databases for function and event signatures. Dependencies include the provider object and the whatsabi library. ```typescript const code = await provider.getCode(address); // Load the bytecode // Get just the callable selectors const selectors = whatsabi.selectorsFromBytecode(code); console.log(selectors); // -> ["0x06fdde03", "0x46423aa7", "0x55944a42", ...] // Get an ABI-like list of interfaces const abi = whatsabi.abiFromBytecode(code); console.log(abi); // -> [ // {"type": "event", "hash": "0x721c20121297512b72821b97f5326877ea8ecf4bb9948fea5bfcb6453074d37f"}, // {"type": "function", "payable": true, "selector": "0x06fdde03", ...}, // {"type": "function", "payable": true, "selector": "0x46423aa7", ...}, // ... // We also have a suite of database loaders for convenience const signatureLookup = new whatsabi.loaders.OpenChainSignatureLookup(); console.log(await signatureLookup.loadFunctions("0x06fdde03")); // -> ["name()"]); console.log(await signatureLookup.loadFunctions("0x46423aa7")); // -> ["getOrderStatus(bytes32)"]); // We also have event loaders! console.log(await signatureLookup.loadEvents("0x721c20121297512b72821b97f5326877ea8ecf4bb9948fea5bfcb6453074d37f")); // -> ["CounterIncremented(uint256,address)"] // There are more fancy loaders in whatsabi.loaders.*, take a look! // Here's a multiloader with an Etherscan API key, it can be used with autoload below. // Each source will be attempted until a result is found. const loader = new whatsabi.loaders.MultiABILoader([ new whatsabi.loaders.SourcifyABILoader(), new whatsabi.loaders.EtherscanV2ABILoader({ apiKey: "...", // Replace the value with your Etherscan API key }), new whatsabi.loaders.BlockscoutABILoader({ apiKey: "...", // Replace the value with your Blockscout API key }), ]); const { abi, name, /* ... other metadata */ } = await loader.getContract(address)); ``` -------------------------------- ### Multi-Source ABI Loader with Fallback Providers - TypeScript Source: https://context7.com/shazow/whatsabi/llms.txt Creates a MultiABILoader instance that chains multiple ABI providers (Sourcify, Etherscan, Blockscout) with fallback support. The loader fetches verified ABIs and contract metadata including source code and compiler information from blockchain explorers and verification databases. ```typescript import { whatsabi } from "@shazow/whatsabi"; // Create a multi-source ABI loader with API keys const abiLoader = new whatsabi.loaders.MultiABILoader([ new whatsabi.loaders.SourcifyABILoader({ chainId: 1 }), new whatsabi.loaders.EtherscanV2ABILoader({ apiKey: "YOUR_ETHERSCAN_API_KEY", chainId: 1, }), new whatsabi.loaders.BlockscoutABILoader({ apiKey: "YOUR_BLOCKSCOUT_API_KEY", baseURL: "https://eth.blockscout.com/api", }), ]); // Load verified ABI from databases const address = "0x1F98431c8aD98523631AE4a59f267346ea31F984"; const abi = await abiLoader.loadABI(address); console.log("Verified ABI loaded:", abi.length > 0); // Get full contract metadata including source code const contract = await abiLoader.getContract(address); console.log("Contract name:", contract.name); console.log("Compiler version:", contract.compilerVersion); console.log("EVM version:", contract.evmVersion); if (contract.getSources) { const sources = await contract.getSources(); sources.forEach(s => { console.log(`File: ${s.path}`); console.log(`Content preview: ${s.content.substring(0, 100)}...`); }); } // Convenient defaults with environment variables const { abiLoader: defaultLoader, signatureLookup } = whatsabi.loaders.defaultsWithEnv({ CHAIN_ID: 1, ETHERSCAN_API_KEY: process.env.ETHERSCAN_API_KEY, }); const result = await whatsabi.autoload(address, { provider, abiLoader: defaultLoader, signatureLookup: signatureLookup, }); ``` -------------------------------- ### Multi-Library Web3 Provider Compatibility Source: https://context7.com/shazow/whatsabi/llms.txt Wrapper utilities enabling WhatsABI to work with different Web3 provider libraries (Ethers.js, Viem, Web3.js) through a unified interface. Demonstrates autoload function with multiple provider types and bytecode caching for reducing redundant RPC calls. ```typescript import { ethers } from "ethers"; import { createPublicClient, http } from "viem"; import { mainnet } from "viem/chains"; import { whatsabi } from "@shazow/whatsabi"; // Works with Ethers.js v6 const ethersProvider = ethers.getDefaultProvider(); const result1 = await whatsabi.autoload(address, { provider: ethersProvider }); // Works with Viem const viemClient = createPublicClient({ chain: mainnet, transport: http() }); const result2 = await whatsabi.autoload(address, { provider: viemClient }); // Works with Web3.js import Web3 from "web3"; const web3 = new Web3("https://eth.llamarpc.com"); const result3 = await whatsabi.autoload(address, { provider: web3 }); // Cache bytecode to avoid redundant RPC calls const cachedCodeProvider = whatsabi.providers.WithCachedCode(ethersProvider, { [address]: "0x6080604052...", // Pre-loaded bytecode }); const result4 = await whatsabi.autoload(address, { provider: cachedCodeProvider, }); ``` -------------------------------- ### WhatsABI Autoload ABI with Proxy Resolution (TypeScript) Source: https://context7.com/shazow/whatsabi/llms.txt The `autoload` function in WhatsABI provides a convenient way to load a contract's ABI. It attempts database lookups, analyzes bytecode, resolves signatures, and automatically detects and follows proxy patterns. It can return the ABI, the resolved implementation address, and a function to follow proxies if detected. It requires an Ethereum provider and accepts options for proxy following and experimental metadata. ```typescript import { ethers } from "ethers"; import { whatsabi } from "@shazow/whatsabi"; const provider = ethers.getDefaultProvider(); const address = "0x00000000006c3852cbEf3e08E8dF289169EdE581"; // Basic usage - returns ABI with proxy detection const result = await whatsabi.autoload(address, { provider }); console.log(result.abi); // Output: [ // { type: "function", selector: "0x06fdde03", name: "name", ... }, // { type: "function", selector: "0x46423aa7", name: "getOrderStatus", ... }, // { type: "event", hash: "0x721c2012...", name: "OrderFulfilled", ... } // ] // With automatic proxy following const resolved = await whatsabi.autoload(address, { provider, followProxies: true, enableExperimentalMetadata: true, }); console.log("Resolved address:", resolved.address); console.log("ABI from implementation:", resolved.abi); // Manually follow proxies if detected if (result.followProxies) { console.log("Proxies detected:", result.proxies); const implementation = await result.followProxies(); console.log("Implementation ABI:", implementation.abi); } ``` -------------------------------- ### Proxy Detection and Resolution Source: https://github.com/shazow/whatsabi/blob/main/README.md Illustrates how WhatsABI can detect and automatically follow smart contract proxies. If proxies are detected, the result object will contain proxy information, and a `followProxies` method can be called to resolve to the implementation address and fetch its ABI. ```typescript // We can even detect and resolve proxies! if (result.followProxies) { console.log("Proxies detected:", result.proxies); result = await result.followProxies(); console.log(result.abi); } ``` -------------------------------- ### WhatsABI Generate ABI from Bytecode Analysis (TypeScript) Source: https://context7.com/shazow/whatsabi/llms.txt The `abiFromBytecode` function performs static analysis on EVM bytecode to construct an ABI structure. It uses disassembly and pattern matching to identify function selectors, modifiers, and event hashes. The resulting ABI includes details like `type`, `selector`, `payable`, and `stateMutability`, but function names and argument types require a separate signature lookup. ```typescript import { whatsabi } from "@shazow/whatsabi"; const provider = ethers.getDefaultProvider(); const code = await provider.getCode("0x00000000006c3852cbEf3e08E8dF289169EdE581"); // Generate ABI structure from bytecode const abi = whatsabi.abiFromBytecode(code); console.log(abi); // Output: [ // { type: "function", selector: "0x06fdde03", payable: false, stateMutability: "view" }, // { type: "function", selector: "0x46423aa7", payable: false }, // { type: "event", hash: "0x721c20121297512b72821b97f5326877ea8ecf4bb9948fea5bfcb6453074d37f" }, // ... // ] // Note: Names and arguments are not available without signature lookup // Use with signatureLookup to enrich the results ``` -------------------------------- ### Multi-Source Signature Lookup for Function and Event Resolution - TypeScript Source: https://context7.com/shazow/whatsabi/llms.txt Creates a MultiSignatureLookup instance that queries multiple signature databases (OpenChain, 4Byte) to resolve function selectors to signatures and event hashes to event signatures. Returns human-readable function and event names for blockchain analysis. ```typescript import { whatsabi } from "@shazow/whatsabi"; // Create signature lookup with multiple sources const signatureLookup = new whatsabi.loaders.MultiSignatureLookup([ new whatsabi.loaders.OpenChainSignatureLookup(), new whatsabi.loaders.FourByteSignatureLookup(), ]); // Look up function signatures by selector const functionSigs = await signatureLookup.loadFunctions("0x06fdde03"); console.log(functionSigs); // Output: ["name()"] const orderStatusSigs = await signatureLookup.loadFunctions("0x46423aa7"); console.log(orderStatusSigs); // Output: ["getOrderStatus(bytes32)"] // Look up event signatures by hash const eventSigs = await signatureLookup.loadEvents( "0x721c20121297512b72821b97f5326877ea8ecf4bb9948fea5bfcb6453074d37f" ); console.log(eventSigs); // Output: ["CounterIncremented(uint256,address)"] // Use with autoload for automatic enrichment const result = await whatsabi.autoload(address, { provider, signatureLookup, }); // result.abi will have 'name' and 'sig' fields populated ``` -------------------------------- ### WhatsABI Extract Selectors from Bytecode (TypeScript) Source: https://context7.com/shazow/whatsabi/llms.txt The `selectorsFromBytecode` function analyzes raw EVM bytecode to extract all callable function selectors. It does this by examining JUMPI instructions within the bytecode's dispatcher, eliminating the need for verified source code. The output is an array of 4-byte hexadecimal strings representing the function selectors. ```typescript import { whatsabi } from "@shazow/whatsabi"; const provider = ethers.getDefaultProvider(); const address = "0x00000000006c3852cbEf3e08E8dF289169EdE581"; const bytecode = await provider.getCode(address); // Extract just the selectors const selectors = whatsabi.selectorsFromBytecode(bytecode); console.log(selectors); // Output: ["0x06fdde03", "0x46423aa7", "0x55944a42", "0x6e9960c3", ...] // These are the function signatures (4-byte identifiers) // that can be called on the contract ``` -------------------------------- ### Proxy Detection and Resolution with Multi-Standard Support - TypeScript Source: https://context7.com/shazow/whatsabi/llms.txt Detects and resolves various proxy patterns including EIP-1967, Diamond, and other standards by analyzing storage slots and bytecode. Supports both automatic proxy resolution via autoload and manual resolver instantiation for specific proxy types. ```typescript import { whatsabi } from "@shazow/whatsabi"; import { ethers } from "ethers"; const provider = ethers.getDefaultProvider(); const proxyAddress = "0x4f8AD938eBA0CD19155a835f617317a6E788c868"; // Automatic proxy detection and resolution const result = await whatsabi.autoload(proxyAddress, { provider, followProxies: true, }); if (result.address !== proxyAddress) { console.log(`Proxy resolved: ${proxyAddress} -> ${result.address}`); } // Manual proxy resolution for specific proxy types const bytecode = await provider.getCode(proxyAddress); const program = whatsabi.disasm(bytecode); console.log("Detected proxies:", program.proxies); // Output: [EIP1967ProxyResolver, DiamondProxyResolver, ...] for (const resolver of program.proxies) { console.log(`Proxy type: ${resolver.name}`); const implementationAddress = await resolver.resolve(provider, proxyAddress); console.log(`Implementation: ${implementationAddress}`); } // Diamond proxy resolution with selector-specific facets const diamondProxy = "0x32400084c286cf3e17e7b677ea9583e60a000324"; const diamondResult = await whatsabi.autoload(diamondProxy, { provider, abiLoader: false, signatureLookup: false, }); if (diamondResult.proxies[0] instanceof whatsabi.proxies.DiamondProxyResolver) { const diamondResolver = diamondResult.proxies[0]; // Get all facets and their selectors const facets = await diamondResolver.facets(provider, diamondProxy); console.log("Diamond facets:", facets); // Output: { // "0x1234...": ["0xabcd1234", "0xefgh5678"], // "0x5678...": ["0xijkl9012"], // } // Resolve specific selector to its facet const selector = "0x6e9960c3"; const facetAddress = await diamondResolver.resolve(provider, diamondProxy, selector); console.log(`Facet for ${selector}: ${facetAddress}`); } ``` -------------------------------- ### Extract Function Selectors from Standard ABI Source: https://context7.com/shazow/whatsabi/llms.txt Converts a standard JSON ABI format into a selector-to-signature mapping for efficient function lookup and validation. Takes an array of ABI function objects and returns an object mapping function selectors (4-byte hex strings) to their full function signatures. ```typescript import { whatsabi } from "@shazow/whatsabi"; // Standard ABI input const abi = [ { type: "function", name: "transfer", inputs: [ { name: "recipient", type: "address" }, { name: "amount", type: "uint256" } ], outputs: [{ name: "", type: "bool" }], stateMutability: "nonpayable", }, { type: "function", name: "balanceOf", inputs: [{ name: "account", type: "address" }], outputs: [{ name: "", type: "uint256" }], stateMutability: "view", }, ]; // Generate selector mapping const selectors = whatsabi.selectorsFromABI(abi); console.log(selectors); // Output: { // "0xa9059cbb": "transfer(address,uint256)", // "0x70a08231": "balanceOf(address)" // } // Use for validation or reverse lookup const selector = "0xa9059cbb"; if (selectors[selector]) { console.log(`Selector ${selector} is ${selectors[selector]}`); } ``` -------------------------------- ### Detect ERC Standard Interfaces with WhatsABI Source: https://context7.com/shazow/whatsabi/llms.txt Identifies implemented standard interfaces (ERC-20, ERC-721, ERC-1155, etc.) by matching function selectors against known interface definitions. Supports automatic detection from loaded ABIs, custom interface definitions, and direct selector matching. Returns an array of detected interface names. ```typescript import { whatsabi } from "@shazow/whatsabi"; const provider = ethers.getDefaultProvider(); const address = "0x1F98431c8aD98523631AE4a59f267346ea31F984"; // Load ABI and detect interfaces const result = await whatsabi.autoload(address, { provider }); const detectedInterfaces = whatsabi.interfaces.abiToInterfaces(result.abi); console.log("Detected interfaces:", detectedInterfaces); // Output: ["IERC20", "IERC20Metadata", "IAccessControl"] // Create custom interface index with additional interfaces const customInterfaces = { ...whatsabi.interfaces.defaultKnownInterfaces, "MyCustomInterface": [ "function customFunction(uint256) returns (bool)", "function anotherFunction(address)", ], }; const interfaceIndex = whatsabi.interfaces.createInterfaceIndex(customInterfaces); const detected = whatsabi.interfaces.abiToInterfaces(result.abi, interfaceIndex); console.log("Detected with custom interfaces:", detected); // Check from just selectors const selectors = ["0x06fdde03", "0x95d89b41", "0x313ce567"]; const interfacesFromSelectors = whatsabi.interfaces.abiToInterfaces(selectors); // Output: ["IERC20Metadata"] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.