# Calling methods

Every JSON-RPC method is a function. Pass its params in wire order with native types, and get the decoded result back in an Effect.

Every JSON-RPC method is a function of a namespace. You pass its params in wire order, with
native types, and get the decoded result back in an `Effect`.

```ts
import { Effect } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const ADDRESS = Address.makeUnsafe("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266");

const nonce = Eth.getTransactionCount(ADDRESS, "pending");
// Effect<number, …>
```

The name is the wire name without its prefix: `eth_getTransactionCount` is
`Eth.getTransactionCount`.

## Namespaces

| Namespace | Wire prefix | Holds |
| --- | --- | --- |
| [`Eth`](https://ethect.dev/rpc/eth/) | `eth_` | what an execution client serves: state, blocks, transactions, logs, fees |
| [`Wallet`](https://ethect.dev/rpc/wallet/) | `wallet_`, `eth_`, `personal_` | what a wallet serves: accounts, chains, signing, call batches |
| [`Anvil`](https://ethect.dev/rpc/anvil/), [`Evm`](https://ethect.dev/rpc/evm/) | `anvil_`, `evm_` | control of a local test node |
| [`Debug`](https://ethect.dev/rpc/debug/) | `debug_` | encoded blocks and geth-style tracing |
| [`Txpool`](https://ethect.dev/rpc/txpool/) | `txpool_` | the node's transaction pool |
| [`Net`](https://ethect.dev/rpc/net/), [`Web3`](https://ethect.dev/rpc/web3/) | `net_`, `web3_` | network and client information |

Import them from `@ethect/core/rpc`. Naming a namespace does not bundle all of it: see
[Bundle size](https://ethect.dev/getting-started/installation/#bundle-size).

```ts
import { Debug, Eth, Wallet } from "@ethect/core/rpc";
```

## Params

Params are positional, in the order the JSON-RPC method takes them. Their types are native:
you never write hex for a number.

```ts
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const FROM = Address.makeUnsafe("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266");
const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");

const estimate = Eth.estimateGas({
  from: FROM, // an Address
  to: TO,
  value: 10n ** 18n, // wei, a bigint
  nonce: 0, // a counter, a number
});
```

| A param that is | Is typed | Written |
| --- | --- | --- |
| an address | [`Address.Address`](https://ethect.dev/reference/primitives/address/) | `Address.makeUnsafe("0x…")` |
| wei, gas, a block number, a timestamp | `bigint` | `1_000_000n` |
| a chain id, a nonce, an index, a count | `number` | `1` |
| a hash, calldata, any other bytes | `` `0x${string}` `` | `"0xa9059cbb…"` |
| a transaction type, a block tag | a string literal | `"eip1559"`, `"latest"` |

An address is the one value you cannot write as a bare literal. `Address.makeUnsafe` checks
one you wrote, when the file loads. [`Address.make`](https://ethect.dev/reference/primitives/address/#make) checks
one you were given, as an effect. Both return the lowercase form the library uses everywhere.
See [Values on the wire](https://ethect.dev/rpc/guides/values/).

## Naming a block

A method that reads state takes a block as its last param: a number, a tag, or an object that
names the block by hash.

```ts
import { Effect } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const ADDRESS = Address.makeUnsafe("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266");

const balances = Effect.all([
  Eth.getBalance(ADDRESS, "latest"),
  Eth.getBalance(ADDRESS, "finalized"),
  Eth.getBalance(ADDRESS, 19_000_000n),
  Eth.getBalance(ADDRESS, { blockHash: `0x${"ab".repeat(32)}` }),
]);
```

The param is optional, and it has no default. Left out, it is not sent and the node decides,
which for anvil is the latest block. Some clients require it, so pass it.

The four forms are the [`BlockId`](https://ethect.dev/rpc/types/block-id/) type. A few methods, such as
[`Eth.getBlockByNumber`](https://ethect.dev/rpc/eth/get-block-by-number/), take only a number or a tag.

## Results

A result is decoded before you see it: quantities are `bigint` or `number`, addresses are
lowercase, a transaction's `type` is a name.

```ts
import { Effect } from "effect";
import { Eth } from "@ethect/core/rpc";

const describe = (hash: `0x${string}`) =>
  Effect.gen(function* () {
    const transaction = yield* Eth.getTransactionByHash(hash);
    if (transaction === null) return "unknown transaction";
    const { type } = transaction;
    if (type === "eip1559") return `tip ${transaction.maxPriorityFeePerGas}`;
    if (type === "legacy") return `gas price ${transaction.gasPrice}`;
    return `a ${type} transaction`;
  });
```

- **Not found is `null`, not an error.** A block, a transaction or a receipt the node does not
  have comes back as `null`, and TypeScript makes you check.
- **A union is narrowed by its tag.** Testing `transaction.type` gives you the fields of that
  type of transaction.
- **Unknown fields are dropped.** What a chain adds to the standard shape is not in the
  result. [Define the method](https://ethect.dev/rpc/guides/custom-methods/) with a wider schema to read it.

## A result that depends on a param

A few methods return a different type for a different argument. `Eth.getBlockByNumber` returns
transaction hashes with `false` and whole transactions with `true`.

```ts
import { Effect } from "effect";
import { Eth } from "@ethect/core/rpc";

const sizes = Effect.gen(function* () {
  const light = yield* Eth.getBlockByNumber("latest", false); // Block.Block | null
  const full = yield* Eth.getBlockByNumber("latest", true); // Block.Full | null
  return [light?.transactions[0], full?.transactions[0]?.from];
  // a hash, and the sender of the first transaction
});
```

The flag is a literal in the type, so the result type follows it. See
[`Method.overload`](https://ethect.dev/rpc/method/overload/).

## Several calls

Steps in `Effect.gen` run one after the other. `Effect.all` with a `concurrency` runs them
together.

```ts
import { Effect } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const account = (address: Address.Address) =>
  Effect.all(
    {
      balance: Eth.getBalance(address, "latest"),
      nonce: Eth.getTransactionCount(address, "latest"),
      code: Eth.getCode(address, "latest"),
    },
    { concurrency: "unbounded" },
  );
// Effect<{ balance: bigint; nonce: number; code: `0x${string}` }, …>
```

Over HTTP with [batching](https://ethect.dev/rpc/guides/batching/), the three calls are one request. Over a socket
they travel on the one connection at the same time.

## Calling a contract

[`Eth.call`](https://ethect.dev/rpc/eth/call/) takes calldata as hex and returns the return data as hex. Here
both are written by hand.

```ts
import { Effect } from "effect";
import { Address, Hash, Hex } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const balanceOf = (token: Address.Address, owner: Address.Address) =>
  Effect.gen(function* () {
    // balanceOf(address): the selector, then the address padded to 32 bytes
    const selector = Hash.keccak256Utf8("balanceOf(address)").slice(0, 10);
    const data = Hex.concat(
      selector as Hex.Hex,
      `0x${owner.slice(2).padStart(64, "0")}`,
    );
    const returned = yield* Eth.call({ to: token, data }, "latest");
    return BigInt(returned); // a uint256
  });
```

This works for a function with fixed-size arguments and one number as its result. For
anything else, let the library encode: [`Fn.encodeInput`](https://ethect.dev/reference/fn/encode-input/) builds
the calldata, and [`Fn.decodeOutput`](https://ethect.dev/reference/fn/decode-output/) reads the answer.

A read through a contract does both, merges with the reads beside it, and types a revert:
see [Read and write a contract](https://ethect.dev/guides/contracts/).

## A method without a definition

Defining a method is one line, and it is typed in both directions.

```ts
import { Schema } from "effect";
import { Method } from "@ethect/core/rpc";

/** The node's automine setting. */
const getAutomine = Method.make()("anvil_getAutomine", [], Schema.Boolean);

getAutomine(); // Effect<boolean, …>
```

See [Custom methods](https://ethect.dev/rpc/guides/custom-methods/).

## Next steps

- [`Eth`](https://ethect.dev/rpc/eth/): every method of the namespace, by group.
- [Batching](https://ethect.dev/rpc/guides/batching/): how concurrent calls become one request.
- [Errors](https://ethect.dev/reference/errors/): the three errors a method fails with, and how to handle each.
- [Values on the wire](https://ethect.dev/rpc/guides/values/): which numbers are `bigint`, and how fields that
  can be missing are typed.
