### Install Ox with bun Source: https://github.com/wevm/ox/blob/main/site/pages/index.md Install the Ox library using bun. ```bash bun i ox ``` -------------------------------- ### Install Ox with pnpm Source: https://github.com/wevm/ox/blob/main/site/pages/index.md Install the Ox library using pnpm. ```bash pnpm i ox ``` -------------------------------- ### Install Ox with npm Source: https://github.com/wevm/ox/blob/main/site/pages/index.md Install the Ox library using npm. ```bash npm i ox ``` -------------------------------- ### Build Ox from Source Source: https://github.com/wevm/ox/blob/main/site/pages/installation.md Clone the Ox repository, install dependencies, build, and link the project locally. ```bash gh repo clone wevm/ox cd ox pnpm install pnpm build pnpm link --global ``` -------------------------------- ### Install Ox canary with yarn Source: https://github.com/wevm/ox/blob/main/site/pages/installation.md Install the latest unreleased version of Ox using the 'canary' tag with yarn. ```bash yarn add ox@canary ``` -------------------------------- ### Install Ox canary with npm Source: https://github.com/wevm/ox/blob/main/site/pages/installation.md Install the latest unreleased version of Ox using the 'canary' tag with npm. ```bash npm install ox@canary ``` -------------------------------- ### Install Ox canary with bun Source: https://github.com/wevm/ox/blob/main/site/pages/installation.md Install the latest unreleased version of Ox using the 'canary' tag with bun. ```bash bun add ox@canary ``` -------------------------------- ### Install Ox with yarn Source: https://github.com/wevm/ox/blob/main/site/pages/installation.md Use this command to install Ox with the yarn package manager. ```bash yarn add ox ``` -------------------------------- ### Install Ox canary with pnpm Source: https://github.com/wevm/ox/blob/main/site/pages/installation.md Install the latest unreleased version of Ox using the 'canary' tag with pnpm. ```bash pnpm add ox@canary ``` -------------------------------- ### Example Usage of Hex and Rlp Modules Source: https://github.com/wevm/ox/blob/main/site/pages/index.md Demonstrates using the Hex and Rlp modules from Ox to encode data. ```typescript import { Hex, Rlp } from 'ox' const rlp = Rlp.fromHex([Hex.fromString('hello'), Hex.fromString('world')]) ``` -------------------------------- ### Sign SIWE Message with Wallet Source: https://github.com/wevm/ox/blob/main/site/pages/guides/siwe.md Sign the created SIWE message using a browser wallet via JSON-RPC. This example uses `window.ethereum` for demonstration, but EIP-6963 is recommended for production. ```typescript import 'ox/window' //--- import { Hex, Provider, Siwe } from 'ox' async function onClick() { const data = { address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', chainId: 1, domain: 'example.com', nonce: '65ed4681d4efe0270b923ff5f4b097b1c95974dc33aeebecd5724c42fd86dfd25dc70b27ef836b2aa22e68f19ebcccc1', uri: 'https://example.com/path', version: '1', } as const satisfies Siwe.Message const message = Siwe.createMessage(data) const provider = Provider.from(window.ethereum) // [!code focus] const signature = await provider.request({ method: 'personal_sign', params: [Hex.fromString(message), data.address], }) // [!code focus] } ``` -------------------------------- ### Construct, Sign, and Broadcast Transaction Envelope Source: https://github.com/wevm/ox/blob/main/src/README.md This example demonstrates how to construct an EIP-1559 transaction envelope, sign it using secp256k1, serialize it, and broadcast it to the network using a provider. Ox's APIs are stateless and unopinionated, designed for higher-level abstractions. ```typescript import { Provider, Secp256k1, TxEnvelopeEip1559, Value } from 'ox' // 1. Construct a transaction envelope. const envelope = TxEnvelopeEip1559.from({ chainId: 1, gas: 21000n, nonce: 0n, maxFeePerGas: Value.fromGwei('10'), maxPriorityFeePerGas: Value.fromGwei('1'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: Value.fromEther('1'), }) // 2. Get the signing payload for the envelope. const payload = TxEnvelopeEip1559.getSignPayload(envelope) // 3. Sign the payload with your private key using secp256k1. const signature = Secp256k1.sign({ payload, privateKey: '0x...' }) // 4. Serialize the envelope with the signature. const serialized = TxEnvelopeEip1559.serialize(envelope, { signature }) // 5. Broadcast the envelope to the network. const provider = Provider.from(window.ethereum) const hash = await provider.request({ method: 'eth_sendRawTransaction', params: [serialized], }) ``` -------------------------------- ### Handle Incoming JSON-RPC Requests Source: https://github.com/wevm/ox/blob/main/site/pages/guides/json-rpc.md Use `RpcResponse.from` to create JSON-RPC responses for incoming requests, suitable for building API handlers or EIP-1193 Provider request handlers. This example shows handling `eth_accounts` and `eth_chainId`. ```typescript // @noErrors import { RpcRequest, RpcResponse, RpcSchema } from 'ox' const accounts = ['0x...', '0x...'] as const async function handleRequest(request: RpcRequest.RpcRequest) { if (request.method === 'eth_accounts') return RpcResponse.from({ result: accounts }, { request }) if (request.method === 'eth_chainId') return RpcResponse.from({ result: '0x1' }, { request }) if (request.method === 'eth_getBlock') // ^| return await fetch('https://1.rpc.thirdweb.com', { body: JSON.stringify(request), method: 'POST', headers: { 'Content-Type': 'application/json', }, }) .then((res) => res.json()) .then((res) => RpcResponse.from(res)) ``` -------------------------------- ### Perform eth_call using RpcTransport Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Execute a contract read-only function call (eth_call) using an RpcTransport. This example uses a HTTP transport to query an address's balance. ```typescript import { AbiFunction, RpcTransport, TransactionRequest, Value } from 'ox' const balanceOf = AbiFunction.from('function balanceOf(address) returns (uint256)') const data = AbiFunction.encodeData( balanceOf, ['0xcb98643b8786950f0461f3b0edf99d88f274574d'] ) const transport = RpcTransport.fromHttp('https://1.rpc.thirdweb.com') const result = await transport.request({ // [!code focus] method: 'eth_call', // [!code focus] params: [{ // [!code focus] data, // [!code focus] to: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // [!code focus] }], // [!code focus] }) // [!code focus] ``` -------------------------------- ### Instantiate EIP-1193 Provider from window.ethereum Source: https://github.com/wevm/ox/blob/main/site/pages/guides/eip-1193.md Instantiate an EIP-1193 provider using `Provider.from` with the `window.ethereum` object. This is commonly used for browser extension wallets. ```typescript import 'ox/window' import { Provider } from 'ox' const provider = Provider.from(window.ethereum) const blockNumber = await provider.request({ method: 'eth_blockNumber' }) ``` -------------------------------- ### Get Size of Bytes and Hex Source: https://github.com/wevm/ox/blob/main/site/pages/guides/bytes-hex.md Retrieve the number of bytes in a Hex string or Bytes array. Useful for understanding data length. ```typescript import { Bytes, Hex } from 'ox' Hex.size('0xdeadbeefdeadbeefdeadbeefdeadbeef') // @log: 16 Bytes.size(Bytes.from([0xde, 0xad, 0xbe, 0xef])) // @log: 4 ``` -------------------------------- ### Create Uncompressed and Compressed Public Keys Source: https://github.com/wevm/ox/blob/main/site/pages/guides/ecdsa.md Illustrates creating PublicKey objects from their components, including uncompressed (with x, y, and prefix) and compressed (with x and prefix) formats. ```typescript import { PublicKey } from 'ox' // Uncompressed const publicKey = PublicKey.from({ prefix: 4, x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n, y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n, }) // Compressed const publicKey_2 = PublicKey.from({ prefix: 2, x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n, }) ``` -------------------------------- ### Recover Public Key with Secp256k1 and P256 Source: https://github.com/wevm/ox/blob/main/site/pages/guides/ecdsa.md Demonstrates recovering a public key from a signature and payload using both Secp256k1 and P256 algorithms. Ensure the 'ox' library is imported. ```typescript import { Secp256k1, P256, WebCryptoP256 } from 'ox' const payload = '0xdeadbeef' // secp256k1 { const privateKey = Secp256k1.randomPrivateKey() const signature = Secp256k1.sign({ payload, privateKey }) const publicKey = Secp256k1.recoverPublicKey({ payload, signature }) } // P256 { const privateKey = P256.randomPrivateKey() const signature = P256.sign({ payload, privateKey }) const publicKey = P256.recoverPublicKey({ payload, signature }) } ``` -------------------------------- ### Entrypoint Imports from 'ox/{Module}' Source: https://github.com/wevm/ox/blob/main/site/pages/imports.md Import modules via their specific entrypoint (e.g., 'ox/Hex'). Use this approach if your bundler does not support Deep Scope Analysis. This method also ensures tree-shakability. ```typescript // @noErrors import * as Hex from 'ox/Hex' import * as Rlp from 'ox/Rlp' const rlp = Rlp.fromHex([Hex.fromString('hello'), Hex.fromString('world')]) ``` -------------------------------- ### Instantiate EIP-1193 Provider with Event Emitter Source: https://github.com/wevm/ox/blob/main/site/pages/guides/eip-1193.md Create an EIP-1193 provider with event emitter capabilities using `Provider.createEmitter`. This is useful for wallets that inject an EIP-1193 provider into the webpage. ```typescript // @noErrors import { Provider, RpcRequest, RpcResponse } from 'ox' // 1. Instantiate a Provider Emitter. const emitter = Provider.createEmitter() // [!code ++] const store = RpcRequest.createStore() const provider = Provider.from({ // 2. Pass the Emitter to the Provider. ...emitter, // [!code ++] async request(args) { return await fetch('https://1.rpc.thirdweb.com', { body: JSON.stringify(store.prepare(args)), method: 'POST', headers: { 'Content-Type': 'application/json', }, }) .then((res) => res.json()) .then(RpcResponse.parse) }, }) // 3. Emit Provider Events. emitter.emit('accountsChanged', ['0x...']) // [!code ++] ``` -------------------------------- ### Instantiate Hex and Bytes Source: https://github.com/wevm/ox/blob/main/site/pages/guides/bytes-hex.md Create Hex and Bytes instances from string and array literals respectively. Use this for initial data representation. ```typescript import { Bytes, Hex } from 'ox' const hex = Hex.from('0xdeadbeef') // '0xdeadbeef' const bytes = Bytes.from([0xde, 0xad, 0xbe, 0xef]) // Uint8Array [0xde, 0xad, 0xbe, 0xef] ``` -------------------------------- ### Import Ox via CDN Source: https://github.com/wevm/ox/blob/main/site/pages/installation.md Import Ox using an ESM-compatible CDN like esm.sh by adding a script tag to your HTML. ```html ``` -------------------------------- ### Define Contract Constructor Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Define a contract constructor using AbiConstructor.from. This is the first step in preparing to deploy a contract with arguments. ```typescript import { AbiConstructor } from 'ox'; const bytecode = '0x...' const constructor = AbiConstructor.from('constructor(address)') ``` -------------------------------- ### Prepare SIWE Message Data Source: https://github.com/wevm/ox/blob/main/site/pages/guides/siwe.md Gather necessary information like address, chainId, domain, nonce, URI, and version to prepare the data for creating a SIWE message on the client. ```typescript function onClick() { const data = { address: '', // e.g. Wagmi `useAccount()`/`getAccount()` chainId: 1, domain: window.location.host, nonce: '', // e.g. `await getNonceFromServer()` uri: window.location.origin, version: '1', } as const } ``` -------------------------------- ### Instantiate Hex and Bytes from Primitives Source: https://github.com/wevm/ox/blob/main/site/pages/guides/bytes-hex.md Create Hex and Bytes from boolean, number, and string types. Use when converting primitive JavaScript values to byte representations. ```typescript import { Bytes, Hex } from 'ox' const bool = Hex.fromBoolean(true) // @log: '0x01' const bigint = Hex.fromNumber(420n) // @log: '0x01a4' const number = Bytes.fromNumber(420) // @log: Uint8Array [1, 164] const string = Hex.fromString('hello') // @log: '0x68656c6c6f' ``` -------------------------------- ### Create SIWE Message Source: https://github.com/wevm/ox/blob/main/site/pages/guides/siwe.md Use `Siwe.createMessage` to construct the SIWE message object from the prepared data on the client. ```typescript import { Siwe } from 'ox' function onClick() { const data = { address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', chainId: 1, domain: 'example.com', nonce: '65ed4681d4efe0270b923ff5f4b097b1c95974dc33aeebecd5724c42fd86dfd25dc70b27ef836b2aa22e68f19ebcccc1', uri: 'https://example.com/path', version: '1', } as const satisfies Siwe.Message const message = Siwe.createMessage(data) // [!code focus] } ``` -------------------------------- ### Serialize Public Keys to Hex and Bytes Source: https://github.com/wevm/ox/blob/main/site/pages/guides/ecdsa.md Demonstrates converting an Ox PublicKey object into its hexadecimal or byte array representation using `toHex` and `toBytes` functions. ```typescript import { PublicKey } from 'ox' const publicKey = PublicKey.from({ x: 49782753348462494199823712700004552394425719014458918871452329774910450607807n, y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n, }) const serialized = PublicKey.toHex(publicKey) const serialized_bytes = PublicKey.toBytes(publicKey) ``` -------------------------------- ### Sign Typed Data using eth_signTypedData_v4 Source: https://github.com/wevm/ox/blob/main/site/pages/guides/signed-data.md Use this snippet to sign typed data with a wallet. Ensure you have imported the necessary modules from 'ox' and have a provider connected to the user's Ethereum window object. The `payload` should be a serialized EIP-712 typed data structure. ```typescript // @noErrors import 'ox/window' import { Hex, Provider, Secp256k1, TypedData } from 'ox' const provider = Provider.from(window.ethereum) const [address] = await provider.request({ method: 'eth_requestAccounts' }) const payload = TypedData.serialize({ /* ... */ }) // [!code focus] const signature = await provider.request({ // [!code focus] method: 'eth_signTypedData_v4', // [!code focus] params: [address, payload], // [!code focus] }) // [!code focus] ``` -------------------------------- ### Derive Private Key with Custom Path Source: https://github.com/wevm/ox/blob/main/site/pages/guides/mnemonics.md Derive a private key from a mnemonic phrase using a custom derivation path. You can specify the path using `Mnemonic.path` or as a string. ```typescript import { Mnemonic } from 'ox' const mnemonic = Mnemonic.random(Mnemonic.english) const path = Mnemonic.path({ account: 1, index: 2 }) // `m/44'/60'/1/0/2` const privateKey = Mnemonic.toPrivateKey(mnemonic, { path }) // or, we can pass the path as a string const privateKey_2 = Mnemonic.toPrivateKey(mnemonic, { path: 'm/44/60/1/0/2' }) ``` -------------------------------- ### Derive Public Key and Address from Mnemonic Source: https://github.com/wevm/ox/blob/main/site/pages/guides/mnemonics.md Derive a public key from a mnemonic's private key using `Secp256k1.getPublicKey`, and then derive an Ethereum address using `Address.fromPublicKey`. ```typescript import { Address, Mnemonic, Secp256k1 } from 'ox' const mnemonic = Mnemonic.random(Mnemonic.english) const privateKey = Mnemonic.toPrivateKey(mnemonic) const publicKey = Secp256k1.getPublicKey({ privateKey }) const address = Address.fromPublicKey(publicKey) ``` -------------------------------- ### Convert Between Hex and Bytes Source: https://github.com/wevm/ox/blob/main/site/pages/guides/bytes-hex.md Instantiate Hex from Bytes and vice versa. Useful when data needs to be in a different format for processing. ```typescript import { Bytes, Hex } from 'ox' // --- const hex = Hex.from(Bytes.from([0xde, 0xad, 0xbe, 0xef])) // @log: '0xdeadbeef' const bytes = Bytes.from(Hex.from('0xdeadbeef')) // @log: Uint8Array [0xde, 0xad, 0xbe, 0xef] ``` -------------------------------- ### Instantiate EIP-1193 Provider with RPC Transport Source: https://github.com/wevm/ox/blob/main/site/pages/guides/eip-1193.md Create an EIP-1193 compliant provider using Ox's `RpcTransport` from an HTTP RPC endpoint. This allows using any HTTP RPC endpoint as a provider. ```typescript import { Provider, RpcTransport } from 'ox' const transport = RpcTransport.fromHttp('https://1.rpc.thirdweb.com') const provider = Provider.from(transport) ``` -------------------------------- ### Register a WebAuthn Credential Source: https://github.com/wevm/ox/blob/main/site/pages/guides/webauthn.md Register a new WebAuthn credential using `WebAuthnP256.createCredential`. This function initiates the process of creating a new cryptographic key pair on a user's authenticator. ```typescript import { WebAuthnP256 } from 'ox' const credential = await WebAuthnP256.createCredential({ name: 'Example' }) // [!code focus] // ^? ``` -------------------------------- ### Generate Private Keys with Signers Source: https://github.com/wevm/ox/blob/main/site/pages/guides/ecdsa.md Generate private keys using Secp256k1, P256, or WebCryptoP256. Note that WebCryptoP256 private keys are non-extractable by default. ```typescript import { P256, Secp256k1, WebCryptoP256 } from 'ox' // Generate a private key on the secp256k1 curve. const privateKey = Secp256k1.randomPrivateKey() // Generate a private key on the P256 curve. const privateKey_2 = P256.randomPrivateKey() // Generate a private key on the P256 curve using the Web Crypto API. const keypair = await WebCryptoP256.createKeyPair() ``` -------------------------------- ### Send JSON-RPC Request with Manual ID Management Source: https://github.com/wevm/ox/blob/main/site/pages/guides/json-rpc.md Use `RpcRequest.from` to create a JSON-RPC request and manage the `id` manually. This offers more control over the request identifier. ```typescript // @noErrors import { RpcRequest } from 'ox' const request = RpcRequest.from({ id: 0, method: 'eth_getBlockByNumber', params: ['latest', false], }) const response = await fetch('https://1.rpc.thirdweb.com', { body: JSON.stringify(request), method: 'POST', headers: { 'Content-Type': 'application/json', }, }).then((res) => res.json()) ``` -------------------------------- ### Serialize and Deserialize an EIP-1559 Transaction Envelope Source: https://github.com/wevm/ox/blob/main/site/pages/guides/transaction-envelopes.md Illustrates how to serialize a Transaction Envelope into RLP-encoded format using `.serialize` and deserialize it back using `.deserialize`. ```typescript import { TxEnvelopeEip1559, Secp256k1, Value } from 'ox' // Construct the Envelope. const envelope = TxEnvelopeEip1559.from({ chainId: 1, maxFeePerGas: Value.fromGwei('10'), maxPriorityFeePerGas: Value.fromGwei('1'), nonce: 69n, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: Value.fromEther('1.5'), }) // Serialize the Envelope. // [!code focus] const serialized = TxEnvelopeEip1559.serialize(envelope) // [!code focus] // ^? // Deserialize the Envelope. // [!code focus] const deserialized = TxEnvelopeEip1559.deserialize(serialized) // [!code focus] // ^? ``` -------------------------------- ### Derive Private Key from Mnemonic Source: https://github.com/wevm/ox/blob/main/site/pages/guides/mnemonics.md Derive a private key from a mnemonic phrase using `Mnemonic.toPrivateKey`. This uses the default Ethereum derivation path. ```typescript import { Mnemonic } from 'ox' const mnemonic = Mnemonic.random(Mnemonic.english) const privateKey = Mnemonic.toPrivateKey(mnemonic) ``` -------------------------------- ### Create ECDSA Signatures with and without yParity Source: https://github.com/wevm/ox/blob/main/site/pages/guides/ecdsa.md Shows how to create Signature objects from r, s, and optionally yParity components. The yParity (recovery bit) may not be present in all signature types. ```typescript import { Signature } from 'ox' // Signature with a recovery bit (yParity) const signature = Signature.from({ r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n, s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n, yParity: 0, }) // Signature without a recovery bit (yParity) const signature_2 = Signature.from({ r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n, s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n, }) ``` -------------------------------- ### Verify a WebAuthn Signature Source: https://github.com/wevm/ox/blob/main/site/pages/guides/webauthn.md Verify a WebAuthn signature using `WebAuthnP256.verify`. This function requires the signature, the original challenge, the public key associated with the credential, and the metadata returned during the signing process. ```typescript import { WebAuthnP256 } from 'ox' const credential = await WebAuthnP256.createCredential({ name: 'Example', }) const { metadata, signature } = await WebAuthnP256.sign({ credentialId: credential.id, challenge: '0xdeadbeef', }) const verified = await WebAuthnP256.verify({ // [!code focus] metadata, // [!code focus] challenge: '0xdeadbeef', // [!code focus] publicKey: credential.publicKey, // [!code focus] signature, // [!code focus] }) // [!code focus] ``` -------------------------------- ### Sign a Payload with WebAuthn Source: https://github.com/wevm/ox/blob/main/site/pages/guides/webauthn.md Sign a challenge (payload) using an existing WebAuthn credential with `WebAuthnP256.sign`. This returns the authenticator's metadata and the resulting signature. The metadata is crucial for signature verification. ```typescript import { WebAuthnP256 } from 'ox' const credential = await WebAuthnP256.createCredential({ name: 'Example' }) const { metadata, signature } = await WebAuthnP256.sign({ // [!code focus] challenge: '0xdeadbeef', // [!code focus] credentialId: credential.id, // [!code focus] }) // [!code focus] metadata // [!code focus] // ^? signature // [!code focus] // ^? ``` -------------------------------- ### Generate Nonce for SIWE Source: https://github.com/wevm/ox/blob/main/site/pages/guides/siwe.md Use `Siwe.generateNonce` to create a random nonce on the server to prevent replay attacks. This nonce should be stored for later validation. ```typescript import { Siwe } from 'ox' function handler() { const nonce = Siwe.generateNonce() return nonce } ``` -------------------------------- ### Encode Constructor Arguments Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Encode constructor arguments for contract deployment using AbiConstructor.encode. This function combines the bytecode with the provided arguments into transaction calldata. ```typescript import { AbiConstructor } from 'ox'; const bytecode = '0x...' const constructor = AbiConstructor.from('constructor(address)') const data = AbiConstructor.encode(constructor, { bytecode, args: ['0x9f1fdab6458c5fc642fa0f4c5af7473c46837357'], }) ``` -------------------------------- ### Encode Data with RLP Source: https://github.com/wevm/ox/blob/main/site/pages/guides/rlp.md Use Rlp.fromHex or Rlp.fromBytes to serialize arbitrary data into RLP-encoded format. This is useful for preparing data for Ethereum transactions or other protocol-level operations. ```typescript import { Hex, Rlp } from 'ox' const rlp = Rlp.fromHex([ Hex.fromString('hello'), Hex.fromNumber(1337), [Hex.fromString('foo'), Hex.fromString('bar')], ]) // @log: 0xd28568656c6c6f820539c883666f6f83626172 ``` -------------------------------- ### Extract Constructor from JSON ABI Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Extract a contract constructor from a JSON ABI using AbiConstructor.fromAbi. This is an alternative to defining the constructor signature directly. ```typescript const erc20Abi = [...] const constructor = AbiConstructor.fromAbi(abi) ``` -------------------------------- ### Derive Ethereum Address from Public Key Source: https://github.com/wevm/ox/blob/main/site/pages/guides/ecdsa.md Derive an Ethereum address from a public key using the Address.fromPublicKey function. ```typescript import { Address, Secp256k1 } from 'ox' const privateKey = Secp256k1.randomPrivateKey() const publicKey = Secp256k1.getPublicKey({ privateKey }) const address = Address.fromPublicKey(publicKey) ``` -------------------------------- ### Estimate Gas with eth_estimateGas Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Estimate the gas required for a transaction using eth_estimateGas. This is useful for understanding transaction costs without executing them. ```typescript // @noErrors import { AbiFunction, RpcTransport, Value } from 'ox' const approve = AbiFunction.from('function approve(address, uint256) returns (bool)') const data = AbiFunction.encodeData( approve, ['0xcb98643b8786950f0461f3b0edf99d88f274574d', Value.fromEther('100')] ) const transport = RpcTransport.fromHttp('https://1.rpc.thirdweb.com') // ---cut--- const gas = await transport.request({ method: 'eth_estimateGas', // [!code ++] params: [{ data, to: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', }], }) ``` -------------------------------- ### Construct an EIP-1559 Transaction Envelope Source: https://github.com/wevm/ox/blob/main/site/pages/guides/transaction-envelopes.md Demonstrates how to construct an EIP-1559 Transaction Envelope using the `TxEnvelopeEip1559.from` function. EIP-1559 Transactions are the most commonly used type. ```typescript import { TxEnvelopeEip1559, Value } from 'ox' const envelope = TxEnvelopeEip1559.from({ chainId: 1, maxFeePerGas: Value.fromGwei('10'), maxPriorityFeePerGas: Value.fromGwei('1'), nonce: 69n, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: Value.fromEther('1.5'), }) ``` -------------------------------- ### Sign Personal Message via Wallet RPC Source: https://github.com/wevm/ox/blob/main/site/pages/guides/signed-data.md Signs a Personal Message using the `personal_sign` RPC method exposed by most Ethereum wallets. Requires a provider connected to the wallet. ```typescript import 'ox/window' import { Hex, Provider } from 'ox' const provider = Provider.from(window.ethereum) const [address] = await provider.request({ method: 'eth_requestAccounts' }) const signature = await provider.request({ method: 'personal_sign', params: [Hex.fromString('hello world'), address], }) ``` -------------------------------- ### Simulate Transaction with eth_call Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Simulate a transaction using eth_call to retrieve and decode the function call result. This method does not broadcast the transaction. ```typescript // @noErrors import { AbiFunction, RpcTransport, Value } from 'ox' const approve = AbiFunction.from('function approve(address, uint256) returns (bool)') const data = AbiFunction.encodeData( approve, ['0xcb98643b8786950f0461f3b0edf99d88f274574d', Value.fromEther('100')] ) const transport = RpcTransport.fromHttp('https://1.rpc.thirdweb.com') // ---cut--- const result = await transport.request({ method: 'eth_call', // [!code ++] params: [{ data, to: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', }], }) const success = AbiFunction.decodeResult(approve, result) // [!code ++] ``` -------------------------------- ### Encode ABI Parameters with Ox Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Use AbiParameters.encode to convert input data into an ABI-encoded bytecode format for the EVM. This is fundamental for smart contract interactions. ```typescript import { AbiParameters } from 'ox'; const encoded = AbiParameters.encode( [{ type: 'address' }, { type: 'uint32[]' }], ['0xcb98643b8786950F0461f3B0edf99D88F274574D', [1, 2, 3]] ) console.log(encoded) ``` -------------------------------- ### Sign an EIP-1559 Transaction Envelope Source: https://github.com/wevm/ox/blob/main/site/pages/guides/transaction-envelopes.md Shows how to sign an EIP-1559 Transaction Envelope by passing the result of `.getSignPayload` to the `Secp256k1.sign` function and then attaching the signature. ```typescript import { TxEnvelopeEip1559, Secp256k1, Value } from 'ox' // Construct the Envelope. const envelope = TxEnvelopeEip1559.from({ chainId: 1, maxFeePerGas: Value.fromGwei('10'), maxPriorityFeePerGas: Value.fromGwei('1'), nonce: 69n, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: Value.fromEther('1.5'), }) // Sign over the Envelope. // [!code focus] const signature = Secp256k1.sign({ // [!code focus] payload: TxEnvelopeEip1559.getSignPayload(envelope), // [!code focus] privateKey: '0x...', // [!code focus] }) // [!code focus] // Attach the Signature to the Envelope. // [!code focus] const signed = TxEnvelopeEip1559.from(envelope, { signature }) // [!code focus] // ^? ``` -------------------------------- ### Trimming Leading Empty Bytes from Hex and Bytes Source: https://github.com/wevm/ox/blob/main/site/pages/guides/bytes-hex.md Use Hex.trimLeft and Bytes.trimLeft to remove leading zero bytes from Hex strings and Bytes arrays respectively. Ensure the Ox library is imported. ```typescript import { Bytes, Hex } from 'ox' Hex.trimLeft('0x00000000000000000000000000000000000000000000000000000000000000dead') // @log: '0xdead' Bytes.trimLeft(Bytes.from([0x00, 0x00, 0xde, 0xad])) // @log: Uint8Array [0xde, 0xad] ``` -------------------------------- ### Encode ABI Parameters with Human-Readable Types Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Encode ABI parameters by providing human-readable types using AbiParameters.from. This offers a more convenient way to specify parameter types. ```typescript import { AbiParameters } from 'ox'; const encoded = AbiParameters.encode( AbiParameters.from(['address', 'uint32[]']), ['0xcb98643b8786950F0461f3B0edf99D88F274574D', [1, 2, 3]] ) ``` -------------------------------- ### Pad Bytes and Hex Source: https://github.com/wevm/ox/blob/main/site/pages/guides/bytes-hex.md Add leading or trailing zero bytes to Hex strings or Bytes arrays to reach a specific length (defaulting to 32 bytes). Use for fixed-size data requirements. ```typescript import { Bytes, Hex } from 'ox' Hex.padLeft(Hex.from('0xdead')) // @log: '0x00000000000000000000000000000000000000000000000000000000000000dead' Bytes.padLeft(Bytes.from([0xde, 0xad]), 4) // @log: Uint8Array [0x00, 0x00, 0xde, 0xad] Hex.padRight(Hex.from('0xdead')) // @log: '0xdead000000000000000000000000000000000000000000000000000000000000' Bytes.padRight(Bytes.from([0xde, 0xad]), 4) // @log: Uint8Array [0xde, 0xad, 0x00, 0x00] ``` -------------------------------- ### Serialize ECDSA Signatures to Hex and Bytes Source: https://github.com/wevm/ox/blob/main/site/pages/guides/ecdsa.md Demonstrates converting an Ox Signature object into its hexadecimal or byte array representation using `toHex` and `toBytes` functions. ```typescript import { Signature } from 'ox' const signature = Signature.from({ r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n, s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n, yParity: 0, }) const serialized = Signature.toHex(signature) const serialized_bytes = Signature.toBytes(signature) ``` -------------------------------- ### Send JSON-RPC Request with Auto-Incrementing ID Source: https://github.com/wevm/ox/blob/main/site/pages/guides/json-rpc.md Use `RpcRequest.createStore` to manage JSON-RPC request IDs automatically. This is useful for sending requests to an Ethereum Node. ```typescript import { RpcRequest } from 'ox' // 1. Create a request store. const store = RpcRequest.createStore() // 2. Prepare a request. const request = store.prepare({ method: 'eth_getBlockByNumber', params: ['latest', false], }) // @log: { id: 0, jsonrpc: '2.0', method: 'eth_getBlockByNumber', params: ['latest', false] } // 3. Send the request to an Ethereum Node. const response = await fetch('https://1.rpc.thirdweb.com', { body: JSON.stringify(request), method: 'POST', headers: { 'Content-Type': 'application/json', }, }).then((res) => res.json()) ``` -------------------------------- ### Define approve Function Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Define a state-modifying contract function using AbiFunction.from. This is the first step in preparing a transaction. ```typescript import { AbiFunction } from 'ox'; const approve = AbiFunction.from('function approve(address, uint256) returns (bool)') ``` -------------------------------- ### Decode ABI Parameters with Ox Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Use AbiParameters.decode to convert ABI-encoded data back into its original values. This is essential for interpreting contract responses. ```typescript import { AbiParameters } from 'ox'; const encoded = AbiParameters.encode( [{ type: 'address' }, { type: 'uint32[]' }], ['0xcb98643b8786950F0461f3B0edf99D88F274574D', [1, 2, 3]] ) const decoded = AbiParameters.decode( [{ type: 'address' }, { type: 'uint32[]' }], encoded ) console.log(decoded) ``` -------------------------------- ### Derive AES-GCM Key from Password Source: https://github.com/wevm/ox/blob/main/site/pages/guides/encryption.md Generates a secure encryption key from a password using PBKDF2. Supports custom salt and iteration count for enhanced security. ```typescript import { AesGcm } from 'ox' const key = await AesGcm.getKey({ password: 'qwerty' }) ``` -------------------------------- ### Decode Logs using AbiEvent.decode Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Decode blockchain event logs using AbiEvent.decode. This snippet takes raw logs obtained from eth_getLogs and decodes them into structured JavaScript objects. ```typescript import { AbiEvent, RpcTransport } from 'ox'; const transfer = AbiEvent.from( 'event Transfer(address indexed from, address indexed to, uint256 value)', ) const { topics } = AbiEvent.encode(transfer, { from: '0x9f1fdab6458c5fc642fa0f4c5af7473c46837357', }) const transport = RpcTransport.fromHttp('https://1.rpc.thirdweb.com') const logs = await transport.request({ method: 'eth_getLogs', params: [{ topics }], }) const decoded = logs.map(log => AbiEvent.decode(transfer, log)) ``` -------------------------------- ### Generate a Random Mnemonic Source: https://github.com/wevm/ox/blob/main/site/pages/guides/mnemonics.md Generate a random mnemonic phrase using `Mnemonic.random`. You can specify the language, with English being the default. ```typescript import { Mnemonic } from 'ox' const mnemonic = Mnemonic.random(Mnemonic.english) ``` -------------------------------- ### Extract Public Keys from Private Keys Source: https://github.com/wevm/ox/blob/main/site/pages/guides/ecdsa.md Extract public keys from generated private keys using Secp256k1 or P256 signers. ```typescript import { Secp256k1, P256 } from 'ox' { const privateKey = Secp256k1.randomPrivateKey() const publicKey = Secp256k1.getPublicKey({ privateKey }) } { const privateKey = P256.randomPrivateKey() const publicKey = P256.getPublicKey({ privateKey }) } ``` -------------------------------- ### Verify Signatures with ECDSA Signers Source: https://github.com/wevm/ox/blob/main/site/pages/guides/ecdsa.md Verify signatures against a payload and public key using the `verify` function of Secp256k1, P256, or WebCryptoP256. For WebCryptoP256, signing and verification are asynchronous. ```typescript import { Secp256k1, P256, WebCryptoP256 } from 'ox' const payload = '0xdeadbeef' // secp256k1 { const privateKey = Secp256k1.randomPrivateKey() const publicKey = Secp256k1.getPublicKey({ privateKey }) const signature = Secp256k1.sign({ payload, privateKey }) const verified = Secp256k1.verify({ payload, publicKey, signature }) } // P256 { const privateKey = P256.randomPrivateKey() const publicKey = P256.getPublicKey({ privateKey }) const signature = P256.sign({ payload, privateKey }) const verified = P256.verify({ payload, publicKey, signature }) } // WebCrypto-P256 { const { privateKey, publicKey } = await WebCryptoP256.createKeyPair() const signature = await WebCryptoP256.sign({ payload, privateKey }) const verified = await WebCryptoP256.verify({ payload, publicKey, signature }) } ``` -------------------------------- ### Define balanceOf Function Source: https://github.com/wevm/ox/blob/main/site/pages/guides/abi.md Define a contract function using AbiFunction.from. This is useful for interacting with known contract functions without needing a full ABI. ```typescript import { AbiFunction } from 'ox'; const balanceOf = AbiFunction.from( 'function balanceOf(address) returns (uint256)' ) ```