### KZG, PeerDAS, and Verkle Proofs Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Demonstrates the creation and verification of KZG EIP-4844 proofs and PeerDAS support from EIP-7594 using the micro-eth-signer library. Includes examples for computing and verifying scalar proofs and blob proofs. ```ts import * as verkle from 'micro-eth-signer/verkle.js'; import { KZG } from 'micro-eth-signer/kzg.js'; // 400kb, 4-sec init import { trustedSetup } from '@paulmillr/trusted-setups/small-kzg.js'; // 800kb, instant init // import { trustedSetup } from '@paulmillr/trusted-setups/fast-kzg.js'; // PeerDAS EIP-7594 // import { trustedSetup } from '@paulmillr/trusted-setups/small-peerdas.js'; // import { trustedSetup } from '@paulmillr/trusted-setups/fast-peerdas.js'; // More KZG & Verkle examples in // https://github.com/ethereumjs/ethereumjs-monorepo const kzg = new KZG(trustedSetup); // Example blob and scalar const blob = '0x1234567890abcdef'; // Add actual blob data const z = '0x1'; // Add actual scalar // Compute and verify proof const [proof, y] = kzg.computeProof(blob, z); console.log('Proof:', proof); console.log('Y:', y); const commitment = '0x1234567890abcdef'; // Add actual commitment const z = '0x1'; // Add actual scalar // const y = '0x2'; // Add actual y value const proof = '0x3'; // Add actual proof const isValid = kzg.verifyProof(commitment, z, y, proof); console.log('Is valid:', isValid); // Compute and verify blob proof const blob = '0x1234567890abcdef'; // Add actual blob data const commitment = '0x1'; // Add actual commitment const proof = kzg.computeBlobProof(blob, commitment); console.log('Blob proof:', proof); const isValidB = kzg.verifyBlobProof(blob, commitment, proof); ``` -------------------------------- ### RLP Encoding and Decoding Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Demonstrates the use of the RLP (Recursive Length Prefix) encoding and decoding functionality provided by the library. RLP is commonly used in Ethereum for encoding data structures. The example shows a basic encode-decode cycle. ```ts import { RLP } from 'micro-eth-signer/rlp.js'; // More RLP examples in test/rlp.test.js RLP.decode(RLP.encode('dog')); ``` -------------------------------- ### Initializing Web3Provider Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Shows how to initialize a Web3Provider using a custom fetch function and RPC URL. This is essential for interacting with Ethereum nodes. ```js // Requests are made with fetch(), a built-in method import { jsonrpc } from 'micro-ftch'; import { Web3Provider } from 'micro-eth-signer/net.js'; const RPC_URL = 'http://localhost:8545'; const prov = new Web3Provider(jsonrpc(fetch, RPC_URL)); // Example using mewapi RPC const RPC_URL_2 = 'https://nodes.mewapi.io/rpc/eth'; const prov2 = new Web3Provider( jsonrpc(fetch, RPC_URL_2, { Origin: 'https://www.myetherwallet.com' }) ); ``` -------------------------------- ### Web3Provider API Methods Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Lists various methods available on the Web3Provider for interacting with the Ethereum network, including fetching block details, transaction information, token balances, and logs. ```APIDOC Web3Provider Methods: blockInfo(block: number): Promise; // {baseFeePerGas, hash, timestamp...} height(): Promise; internalTransactions(address: string, opts?: TraceOpts): Promise; ethLogsSingle(topics: Topics, opts: LogOpts): Promise; ethLogs(topics: Topics, opts?: LogOpts): Promise; tokenTransfers(address: string, opts?: LogOpts): Promise<[Log[], Log[]]>; wethTransfers(address: string, opts?: LogOpts): Promise<[Log[]]>; txInfo(txHash: string, opts?: TxInfoOpts): Promise<{ type: "legacy" | "eip2930" | "eip1559" | "eip4844"; info: any; receipt: any; raw: string | undefined }>; tokenInfo(address: string): Promise; transfers(address: string, opts?: TraceOpts & LogOpts): Promise; allowances(address: string, opts?: LogOpts): Promise; tokenBalances(address: string, tokens: string[]): Promise>; ``` -------------------------------- ### Sending Whole Balance Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Demonstrates how to use the `setWholeAmount` method to send the entire account balance in an unsigned transaction. It explains the logic behind calculating the amount and setting priority fees. ```ts const CURRENT_BALANCE = '1.7182050000017'; // in eth const txSendingWholeBalance = unsignedTx.setWholeAmount(weieth.decode(CURRENT_BALANCE)); ``` -------------------------------- ### micro-eth-signer API Reference Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md This section provides API documentation for the micro-eth-signer library, covering core functionalities such as wallet creation, transaction handling, address manipulation, and message signing. It details methods, parameters, and return values for each function. ```APIDOC addr: random(): { privateKey: string, address: string } Generates a new random Ethereum wallet using CSPRNG. Returns an object containing the privateKey and address. addChecksum(address: string): string Adds EIP-55 checksum to an Ethereum address. isValid(address: string): boolean Checks if an address is a valid Ethereum address (checksummed or not). fromPrivateKey(privateKey: string): string Derives the public address from a private key. fromPublicKey(publicKey: string): string Derives the public address from a public key. Transaction: prepare(params: { to?: string, value?: bigint, gasLimit?: bigint, maxFeePerGas?: bigint, maxPriorityFeePerGas?: bigint, nonce?: bigint, data?: string | Uint8Array, chainId?: number }): Transaction Prepares an unsigned transaction object with the given parameters. signBy(privateKey: string | Uint8Array, options?: { extraEntropy?: boolean }): SignedTransaction Signs the transaction with the provided private key. Supports hedged signatures with `extraEntropy`. setWholeAmount(amount: bigint): Transaction Sets the transaction value to send the entire account balance minus gas fees. SignedTransaction: toHex(): string Returns the signed transaction as a hex string. fee: bigint The calculated fee for the transaction. weigwei: decode(value: string): bigint Decodes a string value from Gwei to Wei. weieth: decode(value: string): bigint Decodes a string value from Ether to Wei. typed: personal: sign(message: string, privateKey: string): string Signs a personal message using EIP-191. verify(signature: string, message: string, address: string): boolean Verifies a personal message signature against a given address. ``` -------------------------------- ### ABI Parsing Input/Output Formats Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Explains the different ways values are parsed for ABI encoding and decoding based on the structure of inputs and outputs. It covers cases with no inputs, single inputs, all named inputs, unnamed inputs, and applies similarly to outputs. ```javascript // no inputs {} -> encodeInput(); // single input {inputs: [{type: 'uint'}]} -> encodeInput(bigint); // all inputs named {inputs: [{type: 'uint', name: 'lol'}, {type: 'address', name: 'wut'}]} -> encodeInput({lol: bigint, wut: string}) // at least one input is unnamed {inputs: [{type: 'uint', name: 'lol'}, {type: 'address'}]} -> encodeInput([bigint, string]) // Same applies for output! ``` -------------------------------- ### Fetching Block Information and Address Data Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Demonstrates fetching current block details and an address's unspent transaction outputs using the Web3Provider. It highlights the use of `prov.height()` and `prov.unspent()`. ```ts const addr = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045'; const block = await prov.blockInfo(await prov.height()); console.log('current block', block.number, block.timestamp, block.baseFeePerGas); console.log('info for addr', addr, await prov.unspent(addr)); ``` -------------------------------- ### Swap Tokens with Uniswap V3 Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Demonstrates how to swap tokens using Uniswap V3 with specified slippage and expiration. It imports necessary functions and classes from the micro-eth-signer library, defines tokens and addresses, and executes the swap, logging transaction details. ```typescript import { tokenFromSymbol } from 'micro-eth-signer/abi.js'; import { UniswapV3 } from 'micro-eth-signer/net.js'; // or UniswapV2 const USDT = tokenFromSymbol('USDT'); const BAT = tokenFromSymbol('BAT'); const u3 = new UniswapV3(prov); // or new UniswapV2(provider) const fromAddress = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045'; const toAddress = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045'; const swap = await u3.swap(USDT, BAT, '12.12', { slippagePercent: 0.5, ttl: 30 * 60 }); const swapData = await swap.tx(fromAddress, toAddress); console.log(swapData.amount, swapData.expectedAmount, swapData.allowance); ``` -------------------------------- ### Fetching Chainlink Oracle Prices Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Demonstrates how to use the Chainlink class to fetch cryptocurrency prices (e.g., BTC, BAT) in USD from a Chainlink oracle. ```ts import { Chainlink } from 'micro-eth-signer/net.js'; const link = new Chainlink(prov); const btc = await link.coinPrice('BTC'); const bat = await link.tokenPrice('BAT'); console.log({ btc, bat }); // BTC 19188.68870991, BAT 0.39728989 in USD ``` -------------------------------- ### Prepare and Sign Ethereum Transactions Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Prepares an Ethereum transaction with specified parameters like recipient, value, and gas fees, and then signs it using a private key. Supports various transaction types including legacy, EIP2930, EIP1559, EIP4844, and EIP7702. Hedged signatures are also supported for enhanced security. ```ts import { Transaction, weigwei, weieth } from 'micro-eth-signer'; const tx = Transaction.prepare({ to: '0xdf90dea0e0bf5ca6d2a7f0cb86874ba6714f463e', value: weieth.decode('1.1'), // 1.1eth in wei maxFeePerGas: weigwei.decode('100'), // 100gwei in wei (priority fee is 1 gwei) nonce: 0n, }); // Uses `random` from example above. Alternatively, pass 0x hex string or Uint8Array const signedTx = tx.signBy(random.privateKey); console.log('signed tx', signedTx, signedTx.toHex()); console.log('fee', signedTx.fee); // Hedged signatures, with extra noise / security const signedTx2 = tx.signBy(random.privateKey, { extraEntropy: true }); // Send whole account balance. See Security section for caveats const CURRENT_BALANCE = '1.7182050000017'; // in eth const txSendingWholeBalance = unsignedTx.setWholeAmount(weieth.decode(CURRENT_BALANCE)); ``` -------------------------------- ### Type-Safe ABI Parsing with `as const` Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Illustrates how to achieve type-safe ABI parsing in TypeScript by using the `as const` assertion. It shows how to define a contract interface and how the `createContract` function generates corresponding TypeScript types for encoding and decoding functions based on input and output parameters. ```typescript import { createContract } from 'micro-eth-signer/abi.js'; const PAIR_CONTRACT = [ { type: 'function', name: 'getReserves', outputs: [ { name: 'reserve0', type: 'uint112' }, { name: 'reserve1', type: 'uint112' }, { name: 'blockTimestampLast', type: 'uint32' }, ], }, ] as const; const contract = createContract(PAIR_CONTRACT); // Would create following typescript type: { getReserves: { encodeInput: () => Uint8Array; decodeOutput: (b: Uint8Array) => { reserve0: bigint; reserve1: bigint; blockTimestampLast: bigint; }; } } ``` -------------------------------- ### Create Random Wallet Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Generates a new Ethereum wallet with a private key and public address using a cryptographically secure pseudo-random number generator (CSPRNG). ```ts import { addr } from 'micro-eth-signer'; const random = addr.random(); // Secure: uses CSPRNG console.log(random.privateKey, random.address); // '0x17ed046e6c4c21df770547fad9a157fd17b48b35fe9984f2ff1e3c6a62700bae' // '0x26d930712fd2f612a107A70fd0Ad79b777cD87f6' ``` -------------------------------- ### EIP-712 Typed Data Signing Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Demonstrates how to define, sign, and verify EIP-712 compliant typed data using micro-eth-signer. It includes defining types, domain, message, signing with a private key, and verifying the signature. ```ts import * as typed from 'micro-eth-signer/typed-data.js'; const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; // Define the domain const domain: typed.EIP712Domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', salt: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', }; // Define the message const message = { from: { name: 'Alice', wallet: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; // Create the typed data const typedData: typed.TypedData = { types, primaryType: 'Mail', domain, message, }; // Sign the typed data const privateKey = '0x4c0883a69102937d6231471b5dbb6204fe512961708279f1d7b1b8e7e8b1b1e1'; const signature = typed.signTyped(typedData, privateKey); console.log('Signature:', signature); // Verify the signature const address = '0xYourEthereumAddress'; const isValid = typed.verifyTyped(signature, typedData, address); // Recover the public key const publicKey = typed.recoverPublicKeyTyped(signature, typedData); ``` -------------------------------- ### Resolving ENS Address Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Shows how to use the ENS class to resolve an Ethereum Name Service (ENS) domain name (e.g., 'vitalik.eth') to its corresponding Ethereum address. ```ts import { ENS } from 'micro-eth-signer/net.js'; const ens = new ENS(prov); const vitalikAddr = await ens.nameToAddress('vitalik.eth'); ``` -------------------------------- ### SSZ (Simple Serialize) Usage Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Shows how to import and use the SSZ (Simple Serialize) functionality from the library. SSZ is a serialization standard used in various blockchain protocols, including Ethereum's consensus layer. It supports stable containers as per EIP-7495. ```ts import * as ssz from 'micro-eth-signer/ssz.js'; // More SSZ examples in test/ssz.test.js ``` -------------------------------- ### Decode Ethereum Event Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Decodes an Ethereum event from its raw components (address, topics, and data) and provides a human-readable hint. This is useful for understanding event logs emitted by smart contracts. It requires the contract address, topics array, and data string. ```ts import { decodeEvent } from 'micro-eth-signer/abi.js'; const to = '0x0d8775f648430679a709e98d2b0cb6250d2887ef'; const topics = [ '0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925', '0x000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa96045', '0x000000000000000000000000e592427a0aece92de3edee1f18e0157c05861564', ]; const data = '0x00000000000000000000000000000000000000000000003635c9adc5dea00000'; const einfo = decodeEvent(to, topics, data); console.log(einfo); ``` -------------------------------- ### Address Manipulation and Validation Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Provides utilities for address manipulation, including deriving addresses from private keys and public keys, adding checksums to addresses, and validating address formats. It supports both checksummed and non-checksummed addresses. ```ts import { addr } from 'micro-eth-signer'; const priv = '0x0687640ee33ef844baba3329db9e16130bd1735cbae3657bd64aed25e9a5c377'; const pub = '030fba7ba5cfbf8b00dd6f3024153fc44ddda93727da58c99326eb0edd08195cdb'; const nonChecksummedAddress = '0x0089d53f703f7e0843953d48133f74ce247184c2'; const checksummedAddress = addr.addChecksum(nonChecksummedAddress); console.log( checksummedAddress, // 0x0089d53F703f7E0843953D48133f74cE247184c2 addr.isValid(checksummedAddress), // true addr.isValid(nonChecksummedAddress), // also true addr.fromPrivateKey(priv), addr.fromPublicKey(pub) ); ``` -------------------------------- ### EIP-191 Personal Message Signing and Verification Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Implements the EIP-191 standard for signing and verifying personal messages. It allows users to sign arbitrary messages with their private key and verify the authenticity of a signature using the signer's public address. ```ts import * as typed from 'micro-eth-signer/typed-data.js'; // Example message const message = 'Hello, Ethereum!'; const privateKey = '0x4c0883a69102937d6231471b5dbb6204fe512961708279f1d7b1b8e7e8b1b1e1'; // Sign the message const signature = typed.personal.sign(message, privateKey); console.log('Signature:', signature); // Verify the signature const address = '0xYourEthereumAddress'; const isValid = typed.personal.verify(signature, message, address); console.log('Is valid:', isValid); ``` -------------------------------- ### Decode Ethereum Transaction Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Decodes an Ethereum transaction and provides human-readable hints. It handles ERC-20 transfers and other common transaction types. Requires the transaction hash as input. ```ts import { decodeTx } from 'micro-eth-signer/abi.js'; const tx = '0xf8a901851d1a94a20082c12a94dac17f958d2ee523a2206206994597c13d831ec780b844a9059cbb000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec7000000000000000000000000000000000000000000000000000000054259870025a066fcb560b50e577f6dc8c8b2e3019f760da78b4c04021382ba490c572a303a42a0078f5af8ac7e11caba9b7dc7a64f7bdc3b4ce1a6ab0a1246771d7cc3524a7200'; // Decode tx information deepStrictEqual(decodeTx(tx), { name: 'transfer', signature: 'transfer(address,uint256)', value: { to: '0xdac17f958d2ee523a2206206994597c13d831ec7', value: 22588000000n, }, hint: 'Transfer 22588 USDT to 0xdac17f958d2ee523a2206206994597c13d831ec7', }); ``` -------------------------------- ### Decode Transaction Data with Custom Contracts Source: https://github.com/paulmillr/micro-eth-signer/blob/main/README.md Decodes transaction data, allowing for custom contract definitions to provide richer hints. This is useful for interacting with non-standard or custom ERC-20 tokens. It takes the recipient address, transaction data, value, and an optional custom contract map. ```ts import { decodeData } from 'micro-eth-signer/abi.js'; const to = '0x7a250d5630b4cf539739df2c5dacb4c659f2488d'; const data = '7ff36ab5000000000000000000000000000000000000000000000000ab54a98ceb1f0ad30000000000000000000000000000000000000000000000000000000000000080000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa96045000000000000000000000000000000000000000000000000000000006fd9c6ea0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000106d3c66d22d2dd0446df23d7f5960752994d600'; const value = 100000000000000000n; deepStrictEqual(decodeData(to, data, value, { customContracts }), { name: 'swapExactETHForTokens', signature: 'swapExactETHForTokens(uint256,address[],address,uint256)', value: { amountOutMin: 12345678901234567891n, path: [ '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', '0x106d3c66d22d2dd0446df23d7f5960752994d600', ], to: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', deadline: 1876543210n, }, }); // With custom tokens/contracts const customContracts = { '0x106d3c66d22d2dd0446df23d7f5960752994d600': { abi: 'ERC20', symbol: 'LABRA', decimals: 9 }, }; deepStrictEqual(decodeData(to, data, value, { customContracts }), { name: 'swapExactETHForTokens', signature: 'swapExactETHForTokens(uint256,address[],address,uint256)', value: { amountOutMin: 12345678901234567891n, path: [ '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', '0x106d3c66d22d2dd0446df23d7f5960752994d600', ], to: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', deadline: 1876543210n, }, hint: 'Swap 0.1 ETH for at least 12345678901.234567891 LABRA.Expires at Tue, 19 Jun 2029 06:00:10 GMT', }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.