Skip to content

Fn.decodeOutput

Decodes what a function returned, from the bytes a node answered a call with.

import { Effect } from "effect";
import { Abi, Address, Fn, type _ } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
// function balanceOf(address owner) view returns (uint256)
const balanceOf = Fn.view<[owner: _]>()("balanceOf", {
inputs: [Abi.address],
output: Abi.uint256,
});
const USDC = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
const USER = Address.makeUnsafe("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266");
// a read written out by hand
const balance = Effect.gen(function* () {
const data = yield* Fn.encodeInput(balanceOf, USER);
return yield* Fn.decodeOutput(balanceOf, yield* Eth.call({ to: USDC, data }, "latest"));
});

You rarely call it yourself: Call.read decodes what it reads. It is for bytes you got another way: a trace, a simulation, a multicall of your own.

A function defined with outputs decodes to an object of them.

import { Abi, Fn, type Hex } from "@ethect/core";
const getReserves = Fn.view()("getReserves", {
inputs: [],
outputs: { reserve0: Abi.uint112, reserve1: Abi.uint112, blockTimestampLast: Abi.uint32 },
});
const reserves = (data: Hex.Hex) => Fn.decodeOutput(getReserves, data);
// Effect<{ reserve0: bigint, reserve1: bigint, blockTimestampLast: number }, AbiError>

Effect<A, AbiError>

What the function returns, as its definition types it: the value of output, an object of outputs, or void. It needs no service: no node is asked.

  • Type: Fn.Fn<string, any, A, any, any>

The function, of any mutability.

The bytes a node returned for a call of the function.

  • A function that returns nothing reads nothing. The result is void, whatever the data.
  • No data where a value is expected is a failure. A node answers 0x for a call to an address that has no code, so the message says there may be no contract there. Call.read names the address.
  • The decoder is as strict as Solidity. Data that is too short, an offset past the end, a bool that is neither 0 nor 1: each is an AbiError. Bytes after the last value are ignored. See Abi.decode.
  • It does not read revert data. That is Err.decode.
Error When
AbiError the data is 0x and the function returns a value
AbiError the data is not the ABI encoding of what the function returns
AbiError an output of the function is not a Solidity type, or is named by a number