UNPKG

ox

Version:

Ethereum Standard Library

535 lines 14.1 kB
import * as abitype from 'abitype'; import * as AbiItem from './AbiItem.js'; import * as AbiParameters from './AbiParameters.js'; import * as Hex from './Hex.js'; /** * ABI-decodes function arguments according to the ABI Item's input types (`inputs`). * * @example * ```ts twoslash * import { AbiFunction } from 'ox' * * const approve = AbiFunction.from('function approve(address, uint256)') * * const data = AbiFunction.encodeData( * approve, * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n] * ) * // '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c' * * const input = AbiFunction.decodeData(approve, data) // [!code focus] * // @log: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n] * ``` * * @param abiFunction - The ABI Item to decode. * @param data - The data to decode. */ export function decodeData(abiFunction, data) { const { overloads } = abiFunction; if (Hex.size(data) < 4) throw new AbiItem.InvalidSelectorSizeError({ data }); if (abiFunction.inputs.length === 0) return undefined; const item = overloads ? fromAbi([abiFunction, ...overloads], data) : abiFunction; if (Hex.size(data) <= 4) return undefined; return AbiParameters.decode(item.inputs, Hex.slice(data, 4)); } /** * ABI-decodes a function's result according to the ABI Item's output types (`outputs`). * * :::tip * * This function is typically used to decode contract function return values (e.g. the response of an `eth_call` or the `input` property of a Transaction). * * See the [End-to-end Example](#end-to-end). * * ::: * * @example * ```ts twoslash * import { AbiFunction } from 'ox' * * const data = '0x000000000000000000000000000000000000000000000000000000000000002a' * * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)') * * const output = AbiFunction.decodeResult(totalSupply, data) * // @log: 42n * ``` * * @example * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}: * * ```ts twoslash * // @noErrors * import { Abi, AbiFunction } from 'ox' * * const data = '0x000000000000000000000000000000000000000000000000000000000000002a' * * const erc20Abi = Abi.from([...]) // [!code hl] * const totalSupply = AbiFunction.fromAbi(erc20Abi, 'totalSupply') // [!code hl] * * const output = AbiFunction.decodeResult(totalSupply, data) * // @log: 42n * ``` * * @example * ### End-to-end * * Below is an end-to-end example of using `AbiFunction.decodeResult` to decode the result of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2). * * ```ts twoslash * import 'ox/window' * import { Abi, AbiFunction } from 'ox' * * // 1. Extract the Function from the Contract's ABI. * const abi = Abi.from([ * // ... * { * name: 'balanceOf', * type: 'function', * inputs: [{ name: 'account', type: 'address' }], * outputs: [{ name: 'balance', type: 'uint256' }], * stateMutability: 'view', * }, * // ... * ]) * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf') * * // 2. Encode the Function Input. * const data = AbiFunction.encodeData( * balanceOf, * ['0xd2135CfB216b74109775236E36d4b433F1DF507B'] * ) * * // 3. Perform the Contract Call. * const response = await window.ethereum!.request({ * method: 'eth_call', * params: [ * { * data, * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2', * }, * ], * }) * * // 4. Decode the Function Output. // [!code focus] * const balance = AbiFunction.decodeResult(balanceOf, response) // [!code focus] * // @log: 42n * ``` * * :::note * * For simplicity, the above example uses `window.ethereum.request`, but you can use any * type of JSON-RPC interface. * * ::: * * @param abiFunction - ABI Function to decode * @param data - ABI-encoded function output * @param options - Decoding options * @returns Decoded function output */ export function decodeResult(abiFunction, data, options = {}) { const values = AbiParameters.decode(abiFunction.outputs, data, options); if (values && Object.keys(values).length === 0) return undefined; if (values && Object.keys(values).length === 1) { if (Array.isArray(values)) return values[0]; return Object.values(values)[0]; } return values; } /** * ABI-encodes function arguments (`inputs`), prefixed with the 4 byte function selector. * * :::tip * * This function is typically used to encode a contract function and its arguments for contract calls (e.g. `data` parameter of an `eth_call` or `eth_sendTransaction`). * * See the [End-to-end Example](#end-to-end). * * ::: * * @example * ```ts twoslash * import { AbiFunction } from 'ox' * * const approve = AbiFunction.from('function approve(address, uint256)') * * const data = AbiFunction.encodeData( // [!code focus] * approve, // [!code focus] * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n] // [!code focus] * ) // [!code focus] * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c' * ``` * * @example * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}: * * ```ts twoslash * // @noErrors * import { Abi, AbiFunction } from 'ox' * * const erc20Abi = Abi.from([...]) // [!code hl] * const approve = AbiFunction.fromAbi(erc20Abi, 'approve') // [!code hl] * * const data = AbiFunction.encodeData( * approve, * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n] * ) * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c' * ``` * * @example * ### End-to-end * * Below is an end-to-end example of using `AbiFunction.encodeData` to encode the input of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2). * * ```ts twoslash * import 'ox/window' * import { Abi, AbiFunction } from 'ox' * * // 1. Extract the Function from the Contract's ABI. * const abi = Abi.from([ * // ... * { * name: 'balanceOf', * type: 'function', * inputs: [{ name: 'account', type: 'address' }], * outputs: [{ name: 'balance', type: 'uint256' }], * stateMutability: 'view', * }, * // ... * ]) * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf') * * // 2. Encode the Function Input. // [!code focus] * const data = AbiFunction.encodeData( // [!code focus] * balanceOf, // [!code focus] * ['0xd2135CfB216b74109775236E36d4b433F1DF507B'] // [!code focus] * ) // [!code focus] * * // 3. Perform the Contract Call. * const response = await window.ethereum!.request({ * method: 'eth_call', * params: [ * { * data, * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2', * }, * ], * }) * * // 4. Decode the Function Output. * const balance = AbiFunction.decodeResult(balanceOf, response) * ``` * * :::note * * For simplicity, the above example uses `window.ethereum.request`, but you can use any * type of JSON-RPC interface. * * ::: * * @param abiFunction - ABI Function to encode * @param args - Function arguments * @returns ABI-encoded function name and arguments */ export function encodeData(abiFunction, ...args) { const { overloads } = abiFunction; const item = overloads ? fromAbi([abiFunction, ...overloads], abiFunction.name, { args: args[0], }) : abiFunction; const selector = getSelector(item); const data = args.length > 0 ? AbiParameters.encode(item.inputs, args[0]) : undefined; return data ? Hex.concat(selector, data) : selector; } /** * ABI-encodes a function's result (`outputs`). * * @example * ```ts twoslash * import { AbiFunction } from 'ox' * * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)') * const output = AbiFunction.decodeResult(totalSupply, '0x000000000000000000000000000000000000000000000000000000000000002a') * // 42n * * const data = AbiFunction.encodeResult(totalSupply, 42n) // [!code focus] * // @log: '0x000000000000000000000000000000000000000000000000000000000000002a' * ``` * * @param abiFunction - The ABI item to encode the function output for. * @param output - The function output to encode. * @param options - Encoding options. * @returns The encoded function output. */ export function encodeResult(abiFunction, output, options = {}) { const { as = 'Array' } = options; const values = (() => { if (abiFunction.outputs.length === 1) return [output]; if (Array.isArray(output)) return output; if (as === 'Object') return Object.values(output); return [output]; })(); return AbiParameters.encode(abiFunction.outputs, values); } /** * Formats an {@link ox#AbiFunction.AbiFunction} into a **Human Readable ABI Function**. * * @example * ```ts twoslash * import { AbiFunction } from 'ox' * * const formatted = AbiFunction.format({ * type: 'function', * name: 'approve', * stateMutability: 'nonpayable', * inputs: [ * { * name: 'spender', * type: 'address', * }, * { * name: 'amount', * type: 'uint256', * }, * ], * outputs: [{ type: 'bool' }], * }) * * formatted * // ^? * * * ``` * * @param abiFunction - The ABI Function to format. * @returns The formatted ABI Function. */ export function format(abiFunction) { return abitype.formatAbiItem(abiFunction); } /** * Parses an arbitrary **JSON ABI Function** or **Human Readable ABI Function** into a typed {@link ox#AbiFunction.AbiFunction}. * * @example * ### JSON ABIs * * ```ts twoslash * import { AbiFunction } from 'ox' * * const approve = AbiFunction.from({ * type: 'function', * name: 'approve', * stateMutability: 'nonpayable', * inputs: [ * { * name: 'spender', * type: 'address', * }, * { * name: 'amount', * type: 'uint256', * }, * ], * outputs: [{ type: 'bool' }], * }) * * approve * //^? * * * * * * * * * * * * * ``` * * @example * ### Human Readable ABIs * * A Human Readable ABI can be parsed into a typed ABI object: * * ```ts twoslash * import { AbiFunction } from 'ox' * * const approve = AbiFunction.from( * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl] * ) * * approve * //^? * * * * * * * * * * * * * * ``` * * @example * It is possible to specify `struct`s along with your definitions: * * ```ts twoslash * import { AbiFunction } from 'ox' * * const approve = AbiFunction.from([ * 'struct Foo { address spender; uint256 amount; }', // [!code hl] * 'function approve(Foo foo) returns (bool)', * ]) * * approve * //^? * * * * * * * * * * * * * ``` * * * * @param abiFunction - The ABI Function to parse. * @returns Typed ABI Function. */ export function from(abiFunction, options = {}) { return AbiItem.from(abiFunction, options); } /** * Extracts an {@link ox#AbiFunction.AbiFunction} from an {@link ox#Abi.Abi} given a name and optional arguments. * * @example * ### Extracting by Name * * ABI Functions can be extracted by their name using the `name` option: * * ```ts twoslash * import { Abi, AbiFunction } from 'ox' * * const abi = Abi.from([ * 'function foo()', * 'event Transfer(address owner, address to, uint256 tokenId)', * 'function bar(string a) returns (uint256 x)', * ]) * * const item = AbiFunction.fromAbi(abi, 'foo') // [!code focus] * // ^? * * * * * * * ``` * * @example * ### Extracting by Selector * * ABI Functions can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`. * * ```ts twoslash * import { Abi, AbiFunction } from 'ox' * * const abi = Abi.from([ * 'function foo()', * 'event Transfer(address owner, address to, uint256 tokenId)', * 'function bar(string a) returns (uint256 x)', * ]) * const item = AbiFunction.fromAbi(abi, '0x095ea7b3') // [!code focus] * // ^? * * * * * * * * * * ``` * * :::note * * Extracting via a hex selector is useful when extracting an ABI Function from an `eth_call` RPC response or * from a Transaction `input`. * * ::: * * @param abi - The ABI to extract from. * @param name - The name (or selector) of the ABI item to extract. * @param options - Extraction options. * @returns The ABI item. */ export function fromAbi(abi, name, options) { const item = AbiItem.fromAbi(abi, name, options); if (item.type !== 'function') throw new AbiItem.NotFoundError({ name, type: 'function' }); return item; } /** * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiFunction.AbiFunction}. * * Useful for computing function selectors for calldata. * * @example * ```ts twoslash * import { AbiFunction } from 'ox' * * const selector = AbiFunction.getSelector('function ownerOf(uint256 tokenId)') * // @log: '0x6352211e' * ``` * * @example * ```ts twoslash * import { AbiFunction } from 'ox' * * const selector = AbiFunction.getSelector({ * inputs: [{ type: 'uint256' }], * name: 'ownerOf', * outputs: [], * stateMutability: 'view', * type: 'function' * }) * // @log: '0x6352211e' * ``` * * @param abiItem - The ABI item to compute the selector for. * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature. */ export function getSelector(abiItem) { return AbiItem.getSelector(abiItem); } //# sourceMappingURL=AbiFunction.js.map