npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@morph-network/chain

v0.2.0

Published

Library-agnostic core for Morph: MorphTx classification, EIP-7702 authorization normalization, RLP rules and error codes.

Readme

@morph-network/chain

Chain-level primitives shared by the Morph Client SDK adapters (@morph-network/ethers, @morph-network/ethers5, @morph-network/viem).

This package has no dependency on any specific client library — no ethers, no viem. It only knows about Morph's wire format: the 0x7F MorphTx envelope, its three versions, EIP-7702 authorization normalization, the minimal-integer RLP rule the envelope requires, network configs, the on-chain TokenRegistry that gives a feeTokenID its meaning, and a stable error contract. Each adapter imports from here so that version inference, encoding rules, fee-token discovery, and error codes are defined exactly once and never drift between libraries.

You normally consume this package indirectly, through one of the adapters. Import it directly when you need the detection/normalization logic without a client library attached — e.g. building your own serializer, validating payloads server-side, or writing code that has to agree with all three adapters on what counts as a MorphTx.


Installation

pnpm add @morph-network/chain
# or
npm install @morph-network/chain

Requires Node >= 22.12. Ships ESM (dist/index.js) and CJS (dist/index.cjs) builds with type declarations.


Module map

| Module | Exports | |---|---| | transaction.ts | MorphTx / Alt Fee detection, version resolution, contract and entry-validation assertions (assertMorphTxInput, assertFeeFieldsValid, assertMorphTxFieldLimits, assertNodeSignableMorphTx); hasReferenceContent / isMorphFieldPresent decide whether a loose reference/memo value is real content or should be omitted from the wire; TOKEN_REGISTRY_PROXY_ADDRESS | | envelope.ts | layoutMorphTxEnvelope (field order, version byte and signing-preimage shape for V0/V1/V2), resolveSignatureYParity | | authorization.ts | EIP-7702 authorization normalization + RLP tuple builder | | rlp.ts | Minimal big-endian integer encoding for RLP integer slots (toRlpIntBytes, toRlpIntHex, canonicalRlpIntWith, isEmptyHexMarker) and toRlpAccessList | | errors.ts | MorphSdkError, MorphSdkErrorCode | | util.ts | integer() / maybeInteger() / tryBigInt() numeric coercion helpers, toCanonicalHex / toCanonicalAccessList (lowercase JSON-RPC payload hex) | | networks.ts | MORPH_MAINNET, MORPH_HOODI_TESTNET network configs (incl. tokenRegistry address), MORPH_NETWORKS, getMorphNetwork(keyOrChainId) | | feeTokens.ts | getFeeTokens(rpc), resolveFeeToken(rpc, idOrAddress), getTokenIdByAddress(rpc, address) — read the on-chain TokenRegistry (id, address, decimals, scale, isActive, priceRatio) through the minimal MorphRpcClient; ethToTokenAmount / tokenToEthAmount price a tx; opt-in offlineFallback | | feeTokenSnapshots.ts | getFeeTokenSnapshot(network), findFeeTokenSnapshot, FEE_TOKEN_SNAPSHOTS, addressEquals — bundled offline token list (not authoritative) | | rpcClient.ts | MorphRpcClient — the { request({ method, params }) } shape every chain helper accepts | | rpc.ts | getTransactionHashesByReference() — morph_getTransactionHashesByReference; getBroadcastTransaction() (retrying lookup of a just-broadcast tx; throws TRANSACTION_NOT_FOUND) | | abi/ | tokenRegistryAbi — ABI for the on-chain TokenRegistry contract |

All of the above are re-exported from the package root (packages/chain/src/index.ts).


MorphTx envelope versions

MorphTx is transaction type 0x7F (ALT_FEE_TX_TYPE). There are three wire envelopes, selected by a version byte (absent for v0):

| Version | Envelope | Signed fields (on top of the 11 base fields) | When | |---|---|---|---| | v0 | 0x7F \|\| RLP([base11, yParity, r, s]) | — | Plain Alt Fee (feeTokenID > 0), no extension fields | | v1 | 0x7F \|\| 0x01 \|\| RLP([base11, reference, memo, yParity, r, s]) | reference, memo | Needs an on-chain memo / business reference; lowest version for ETH-paid gas | | v2 | 0x7F \|\| 0x02 \|\| RLP([base11, reference, memo, authorizationList, yParity, r, s]) | reference, memo, authorizationList | Alt Fee + EIP-7702 delegation |

Gas payment by envelope version:

  • v1 / v2 accept either ETH (feeTokenID = 0) or an AltFee token (feeTokenID > 0).
  • v0 accepts an AltFee token only. The node requires feeTokenID > 0 and rejects a zero token id in all three places it looks — encoding (invalid FeeTokenID for v0 morph tx), decoding (invalid fee token id, expected non-zero) and validation (illegal extra parameters of version 0 MorphTx). reth mirrors this in its decoder and validate_version. So an ETH-paying MorphTx is always v1 or v2.

assertMorphTxInput therefore refuses to serialize an explicit morphTxVersion: 0 without a positive token id (ALT_FEE_CONTRACT_VIOLATION). A feeTokenID = 0 transaction is still a perfectly good MorphTx, just not an "Alt Fee" one, and never a v0.

resolveMorphTxVersion(fields): 0 | 1 | 2

Infers the version from the fields present:

  1. An explicit morphTxVersion marker wins, but it's checked for contradictions: v0/v1 combined with a non-empty authorizationList throws AUTH_LIST_REQUIRES_V2.
  2. A non-empty authorizationList selects v2 — but only if some other Morph field (feeTokenID > 0, non-empty reference, or non-empty memo) is also present. An authorization list with no other Morph field is a standard EIP-7702 0x04 transaction, not a MorphTx, and this throws AUTH_LIST_REQUIRES_MORPH_FIELDS rather than silently wrapping it.
  3. A non-empty reference or memo selects v1. An all-zero 32-byte reference counts as absent here (matching geth / reth classification), so { feeTokenID: 1, reference: 0x00…00 } still infers v1, not v0 — v0 is never inferred at all. The bytes are preserved on the wire regardless.
  4. Otherwise v1. v0 is never inferred.

Every contradictory or ambiguous combination throws instead of guessing — silently downgrading a v2 intent to v1 would discard the authorization list, which is exactly the failure this module exists to prevent.

v0 is explicit only, matching the node

Step 4 follows the node exactly:

  • geth InferUnsignedMorphTxVersion (core/types/morph_tx.go): "otherwise MorphTx defaults to v1 (legacy v0 construction is folded into v1)".
  • reth TxMorph::inferred_version: "V1 is the baseline … the request layer never produces V0 anymore". Its own tests pin inferred_version(false) == V1.

So { feeTokenID: 1 } (an ERC20 payer with no reference/memo) is v1, the same as the node. Producing v0 requires morphTxVersion: 0.

Matching the node keeps bytes and hashes identical between a locally signed transaction and one the node assembles for eth_fillTransaction / eth_signTransaction, so the two can be cross-checked. It also removes a fork-gate asymmetry: the 0x7F type itself needs Emerald, v1 needs Jade and v2 needs Celadon, so v0 has no gate of its own to dodge — inferring it bought nothing while making the SDK's bytes diverge from the node's.

v0 remains fully supported: it parses, re-serializes byte-for-byte, and is produced on request.

v0 is local-signing only. The node's transaction RPCs carry no version field, so eth_sendTransaction / eth_signTransaction always infer v1 for a request without an authorization list. Asking a wallet or a viem JSON-RPC account for v0 therefore yields v1 bytes with a different signature and hash. assertNodeSignableMorphTx refuses that combination by name rather than letting it through — send v0 with eth_sendRawTransaction instead.

import { resolveMorphTxVersion } from "@morph-network/chain";

resolveMorphTxVersion({ feeTokenID: 1 });                                  // 1
resolveMorphTxVersion({ feeTokenID: 0 });                                  // 1
resolveMorphTxVersion({ feeTokenID: 1, reference: REF32 });                // 1
resolveMorphTxVersion({ feeTokenID: 1, morphTxVersion: 0 });               // 0 (explicit only)
resolveMorphTxVersion({ feeTokenID: 1, authorizationList: [auth] });       // 2
resolveMorphTxVersion({ authorizationList: [auth] });                     // throws AUTH_LIST_REQUIRES_MORPH_FIELDS

REF32 above is a 32-byte hex value. Inference only looks at whether reference carries content, but the serializer enforces the node's size rule: reference must be omitted or exactly 32 bytes, otherwise INVALID_REFERENCE_LENGTH (assertMorphTxFieldLimits). A short placeholder such as "0xdead" infers v1 here but cannot be signed.

"0x" is geth-only. geth's Reference.UnmarshalJSON special-cases the empty string and treats it as a zero reference; reth decodes the field as Option<B256> and rejects anything that is not 32 bytes. Passing "0x" therefore works against geth but fails against reth — omit the field instead. The SDK treats "0x" as "no reference" (hasReferenceContent / isMorphFieldPresent both return false), so it infers and serializes the same as omitting it.

authorizationList: [] never upgrades the version on an unsigned transaction — it's indistinguishable from "no authorization list at all". It only becomes meaningful once a transaction is already formed as v2, marked locally by morphTxVersion: 2 (which is a client-side-only marker and must never be serialized into a JSON-RPC payload — the node doesn't know about it and rejects unexpected fields).

Detection predicates

  • isMorphTx(tx): boolean — "is this a 0x7F envelope at all?" True for an explicit type: 0x7f / "altFee", or for any transaction carrying a Morph-only field (feeTokenID > 0, non-empty reference/memo, or an explicit morphTxVersion). This is the routing predicate every adapter uses to decide whether to serialize via the MorphTx path. Deliberately does not treat a bare authorization list as a MorphTx signal — see point 2 above.
  • isAltFeeTx(tx): boolean — "is gas paid with an ERC20?" (feeTokenID > 0). Independent of isMorphTx: feeTokenID = 0 returns false here even though it's still a valid MorphTx. Throws on a negative/unparseable feeTokenID, or on a missing feeTokenID when type is explicitly 0x7f. Do not use this for routing — a feeTokenID = 0 MorphTx would incorrectly fall through to each library's native transaction path, silently dropping reference/memo/authorizationList.
  • hasAuthList(tx): boolean — true iff authorizationList is present and non-empty.
  • assertAltFeeTx(tx) — throws unless isAltFeeTx(tx) is true.
  • assertFeeLimitWithoutToken(fields) — throws FEE_LIMIT_WITHOUT_TOKEN if feeLimit is set while feeTokenID is 0 or absent (the node reports illegal extra parameters).
  • assertAuthListCannotCreate(fields) — throws AUTH_LIST_CANNOT_CREATE if a non-empty authorizationList is combined with an empty to (nodes reject MorphTx contract creation when an authorization list is present).
  • altFeeTypeToQuantityType(type) — maps the in-memory discriminator "altFee" to the JSON-RPC quantity 0x7f (127); passes any other value through unchanged.

EIP-7702 authorization normalization

authorization.ts accepts three different authorization shapes and normalizes all of them onto one canonical in-memory form, so every adapter — and every pair of adapters handing authorizations to each other — agrees on the same bytes.

import { normalizeAuthorization, normalizeAuthorizationList, toRlpAuthTuples } from "@morph-network/chain";

// 1. flat
normalizeAuthorization({ address, chainId, nonce, yParity, r, s });

// 2. nested — ethers6's native `wallet.authorize()` / `authorizationify()` shape
normalizeAuthorization({ address, chainId, nonce, signature: { yParity, r, s } });

// 3. viem's SignedAuthorization (flat, bigint/hex fields, or `v` instead of `yParity`)
normalizeAuthorization({ address, chainId, nonce, v: 27, r, s });

normalizeAuthorization returns a MorphAuthorization:

interface MorphAuthorization {
  address: `0x${string}`;   // lowercased, 20 bytes
  chainId: bigint;          // 0 means "valid on any chain"
  nonce: bigint;
  yParity: 0 | 1;
  r: `0x${string}`;         // canonical 32-byte hex (left-padded)
  s: `0x${string}`;         // canonical 32-byte hex (left-padded), EIP-2 low-s
}

Validation performed during normalization:

  • address must be exactly 20 bytes (INVALID_AUTH_ADDRESS).
  • chainId / nonce must be non-negative integers (INVALID_AUTH_INTEGER).
  • yParity must resolve to 0 or 1 — accepts a top-level yParity, signature.yParity, or signature.v (27/28 or 0/1), checked in that precedence order (INVALID_AUTH_YPARITY).
  • r / s must be at most 32 bytes (INVALID_AUTH_SIGNATURE_COMPONENT).
  • s must satisfy EIP-2 (s <= secp256k1n/2) — a high-s signature is rejected, not flipped (AUTH_S_HIGH), because silently normalizing it would rewrite a signature the caller handed in without telling them.

normalizeAuthorizationList maps the above over a list; undefined stays undefined ("field absent"), [] stays [] ("explicitly empty") — that distinction matters to resolveMorphTxVersion. Order and duplicates are preserved: the node applies authorizations sequentially and nonce increments depend on it.

Why the canonical form is 32-byte hex, but the wire form isn't

r/s in MorphAuthorization are canonical 32-byte, left-padded hex — a stable, comparable in-memory form, convenient for assertions and equality checks. That is not what goes on the wire. toRlpAuthTuples re-derives the minimal RLP form before encoding:

toRlpAuthTuples(authorizationList): `0x${string}`[][]
// [[chainId, address, nonce, yParity, r, s], ...] — RLP-ready tuples

Every slot except address goes through {@link toRlpIntHex} (minimal big-endian integer): a zero signature encodes as 0x80 (empty string), not 32 zero bytes — geth rejects a padded zero as a non-canonical integer. address is a byte string and is passed through untouched; integer-minimizing it would strip leading zeros and change which address the delegation points to.

This is also why each adapter's library-native authorization encoder is bypassed. ethers6's authorizationify() and viem's serializeAuthorizationList() both encode internally and would reintroduce per-library drift; toRlpAuthTuples is the one place this six-slot rule is written down, verified to produce byte-identical output across all three libraries.


RLP integer encoding (rlp.ts)

Every RLP integer slot in a MorphTx — chainId, nonce, gas, value, signature components, and all six slots inside each authorization tuple — must be a minimal big-endian byte string: no leading zero bytes, and zero itself is the empty string (rendered by RLP as 0x80). geth rejects anything else with rlp: non-canonical integer (leading zero bytes).

This matters because every client library's own "number to bytes" helper gets zero wrong in a way that produces exactly that error:

ethers.toBeHex(0n)                      // "0x00" -> RLP 0xc100, WRONG
viem.toHex(0n) / viem.numberToHex(0n)   // "0x0"  -> RLP 0xc100, WRONG
ethers5.BigNumber.from(0).toHexString() // "0x00" -> RLP 0xc100, WRONG
import { toRlpIntBytes, toRlpIntHex } from "@morph-network/chain";

toRlpIntBytes(0n);        // Uint8Array(0) []      -> encodes as 0x80
toRlpIntHex(0n);           // "0x"
toRlpIntHex(256n);         // "0x0100" (two bytes; no leading zero byte)
toRlpIntHex(1n);           // "0x01"
toRlpIntBytes(-1n);        // throws RangeError — RLP has no negative representation

Takes bigint only, on purpose — callers normalize their own loose input (number | bigint | hex string) via integer() (see below) first, rather than this module re-implementing each library's inconsistent coercion rules.

The counterpart rule — byte-string slots (address, data, reference, memo, access-list entries) keep their leading zeros and must not be passed through this module — is deliberately not implemented here; doing so would corrupt them.


Errors (errors.ts)

Every rejection path in the SDK throws a MorphSdkError carrying a stable code, so callers can branch on error.code instead of matching message text:

import { MorphSdkError, MorphSdkErrorCode } from "@morph-network/chain";

try {
  resolveMorphTxVersion({ authorizationList: [auth] });
} catch (err) {
  if (err instanceof MorphSdkError && err.code === MorphSdkErrorCode.AUTH_LIST_REQUIRES_MORPH_FIELDS) {
    // this is a plain EIP-7702 0x04 transaction, not a MorphTx
  }
}

| Code | Thrown when | |---|---| | AUTH_LIST_REQUIRES_V2 | Explicit morphTxVersion of 0/1 combined with a non-empty authorizationList | | AUTH_LIST_REQUIRES_MORPH_FIELDS | Non-empty authorizationList with no other Morph field — belongs on 0x04, not MorphTx | | AUTH_LIST_CANNOT_CREATE | Non-empty authorizationList with an empty to (contract creation) | | FEE_LIMIT_WITHOUT_TOKEN | feeLimit set while feeTokenID is 0/absent | | INVALID_REFERENCE_LENGTH | reference is not 0 or 32 bytes | | MEMO_TOO_LONG | memo exceeds 64 bytes | | INVALID_HEX_FIELD | reference / memo is not a valid 0x hex string (including an odd number of hex digits in memo) | | INVALID_FEE_TOKEN_ID | feeTokenID does not fit the node's uint16 | | UNSUPPORTED_MORPH_TX_VERSION | Unknown envelope byte or in-memory version marker | | INVALID_AUTH_ADDRESS | Authorization address is not 20 bytes | | INVALID_AUTH_INTEGER | Authorization chainId/nonce is not a non-negative integer | | INVALID_AUTH_YPARITY | Authorization yParity is neither 0 nor 1 | | INVALID_AUTH_SIGNATURE_COMPONENT | Authorization r/s exceeds 32 bytes | | AUTH_S_HIGH | Authorization s violates EIP-2 (high-s) | | INVALID_SERIALIZED_TX | Serialized 0x7f payload has an impossible field count / envelope combination, or fails the node's decode rules | | AMBIGUOUS_ALT_FEE_PAYLOAD | A 14-field 0x7f payload whose slot 11 is 0x01 and slot 12 is 32 bytes can be a signed v0 (yParity=1) or a v1 preimage, and assume was not passed. Thrown with an external signature, or without one when the signed-v0 reading fails. Other 14-field shapes resolve on their own | | ALT_FEE_CONTRACT_VIOLATION | type: 0x7f field combination violates the Alt Fee contract | | INVALID_INTEGER_INPUT | A numeric input could not be parsed into a bigint / number | | INTEGER_OVERFLOW | A bigint exceeds the safe number range | | NEGATIVE_RLP_INTEGER | An RLP integer slot was given a negative value | | MISSING_CHAIN_ID | A MorphTx was serialized without chainId | | INVALID_RPC_RESPONSE | An RPC response did not match the shape the SDK requires | | MISSING_PROVIDER | A MorphTx send/sign/populate path was called without a provider | | PROVIDER_UNSUPPORTED | The supplied provider cannot issue raw JSON-RPC calls | | UNSUPPORTED_SIGNER | Alt Fee signTransaction was called on a signer that cannot sign raw RLP (not a wallet, not browser-provider-backed) | | NODE_SIGNING_MISMATCH | A node-signed request (eth_sendTransaction / eth_signTransaction through a browser wallet or a viem JSON-RPC account) would be rebuilt by the node as a different transaction — including an explicit v0, which the node always signs as v1 (see assertNodeSignableMorphTx) | | TRANSACTION_NOT_FOUND | The node accepted a raw broadcast but cannot return the transaction by hash | | PEER_VERSION_MISMATCH | The host resolved an adapter's ethers peer to a major version that adapter cannot drive (see @morph-network/ethers5's README, "Using this alongside ethers v6") | | FEE_TOKEN_NOT_FOUND | The TokenRegistry has no entry for the requested fee token id or address — also thrown for feeTokenID = 0 (ETH pays gas, not a registry token), for an invalid token address, and when pricing a snapshot entry that carries no scale/priceRatio (see "Fee tokens") |

Message text is kept in one table so it mirrors the node's own error strings where one exists, and so the three adapters never drift from each other. MorphSdkError also carries an optional .cause (the lower-level error it wraps, when any).


Numeric helpers (util.ts)

import { integer, maybeInteger, type IntegerLike } from "@morph-network/chain";

integer(5).bigint();        // 5n
integer("0x1f4").number();  // 500
integer(5n).hex();           // "0x5"

maybeInteger(undefined);     // undefined
maybeInteger(5);             // { bigint, number, hex } wrapper

IntegerLike = number | bigint | `0x${string}` . integer() coerces any of them to a wrapper exposing .bigint() / .number() / .hex(); it throws on an unsafe number (not representable exactly as a JS number) and on anything that isn't a recognizable numeric shape. .number() additionally throws on overflow outside Number.MAX_SAFE_INTEGER.


Networks (networks.ts)

import { MORPH_MAINNET, MORPH_HOODI_TESTNET, type MorphNetwork } from "@morph-network/chain";

| Constant | chainId | RPC | WS | Explorer | |---|---|---|---|---| | MORPH_MAINNET | 2818 | https://rpc-bgw.morph.network | wss://rpc-bgw.morph.network | https://explorer.morph.network | | MORPH_HOODI_TESTNET | 2910 | https://rpc-hoodi-bgw.morph.network | wss://rpc-hoodi-bgw.morph.network | https://explorer-hoodi.morph.network |

Each is a plain MorphNetwork object (key, rpcUrl, wsUrl, chainId, name, nativeCurrency, blockExplorerUrl, blockExplorerName, tokenRegistry) — framework-agnostic; the viem adapter wraps these into defineChain configs (morphMainnet / morphHoodiTestnet, which also get rpcUrls.default.webSocket, blockExplorers.default and contracts.tokenRegistry), and the ethers adapters read chainId/rpcUrl directly.

tokenRegistry is the same predeploy address on every Morph network (0x5300000000000000000000000000000000000021, also exported as TOKEN_REGISTRY_PROXY_ADDRESS) — but the registry's contents are per-network, so a feeTokenID does not name the same token on mainnet and Hoodi (id 1 is USDT on mainnet and DYDX on Hoodi). Always pass the matching network when reading fee tokens.

MORPH_NETWORKS is the full list, and getMorphNetwork(keyOrChainId) looks one up by either spelling, returning undefined for a chain that is not Morph.


Capabilities detection: none

There is no capability probe. morph_getCapabilities is not implemented by either Morph node — morph-go-ethereum's morph_ namespace exposes only getBlockByHash / getBlockByNumber / getSkippedTransaction(Hashes) / getBlockTraceByNumberOrHash / getTxBlockTraceOnTopOfBlock / estimateL1DataFee / diskRoot, and morph-reth's exposes only getTransactionHashesByReference. A probe could therefore only ever return a constant "unsupported", so detectMorphCapabilities, normalizeCapabilities, fallbackCapabilities and MORPH_GET_CAPABILITIES were removed in 0.2.0.

Gate on what actually decides support instead:

  • MorphTx type / v1: Emerald, then Jade. v2: Celadon. A transaction broadcast before the fork is rejected by the node with MorphTx version 2 is not yet active.
  • Which tokens can pay gas is chain state, not a node feature: read it with getFeeTokens(rpc, { network }) (see "Fee tokens").

The MorphRpcClient shape those helpers take now lives in rpcClient.ts.


Reference lookups (rpc.ts)

import { getTransactionHashesByReference } from "@morph-network/chain";

const hits = await getTransactionHashesByReference(rpcClient, {
  // Same size rule as the envelope field: exactly 32 bytes.
  reference: "0x9fb1bdfedbbe3bd552cf6d68a2d9f95d128c0d492df343bef9babc382cd77c1a",
  limit: "0x10",
});
// [{ transactionHash, blockNumber, blockTimestamp, transactionIndex }, ...]

Thin wrapper around the node's morph_getTransactionHashesByReference method — looks up transactions by the reference field carried in a v1/v2 MorphTx envelope. Takes the minimal MorphRpcClient shape, plus optional offset/limit pagination.

Field names match the node's wire format, including blockTimestamp: geth tags it json:"blockTimestamp" in rpc.ReferenceTransactionResult, and morph-reth derives the same name from block_timestamp under #[serde(rename_all = "camelCase")].


TokenRegistry ABI (abi/)

import { tokenRegistryAbi } from "@morph-network/chain";
import { TOKEN_REGISTRY_PROXY_ADDRESS } from "@morph-network/chain"; // from transaction.ts

tokenRegistryAbi is the full ABI for the on-chain TokenRegistry contract (deployed at the well-known proxy address TOKEN_REGISTRY_PROXY_ADDRESS = 0x5300000000000000000000000000000000000021), which tracks which ERC20 tokens are registered as Alt Fee tokens, their feeTokenID, price, and scale. Notable read methods: getTokenInfo, getTokenIdByAddress, getTokenPrice, getTokenScale, isTokenSupported, isTokenActive, getSupportedTokenList, getSupportedIDList. Pair it with any of the three adapters' providers/clients to read fee-token metadata before building an Alt Fee transaction (e.g. to resolve a feeTokenID from a token address, or to show a user the ERC20 cost of gas).


Relationship to the adapters

This package defines what a MorphTx is; it does not know how to sign one. Each adapter builds a concrete transaction/signing flow on top of it:

All three depend on this package as a peer dependency and re-export its primitives (errors, authorization normalizers, RLP helpers, network configs) from their own package root, so you rarely need to install @morph-network/chain directly unless you're working below the adapter layer.


Testing

pnpm --filter @morph-network/chain test

test/transaction.test.ts and test/authorization.test.ts cover the full version-resolution truth table and every authorization normalization/error path; test/rlp.test.ts covers the minimal-integer encoding rule, including the zero and all-leading-zero-byte edge cases that motivated this module; test/util.test.ts covers the numeric coercion helpers; test/envelope.test.ts, test/transaction-guards.test.ts and test/rpc.test.ts cover the shared envelope layout, entry validation and RPC helpers; test/feeTokens.test.ts covers registry decoding, metadata sourcing, snapshot fallback and every FEE_TOKEN_NOT_FOUND path, and test/precision.test.ts pins the ethToTokenAmount / tokenToEthAmount arithmetic above 2^53 (a double rounding there would silently misprice a fee). Cross-adapter byte-for-byte agreement and the V0/V1/V2 wire vectors are pinned by the repo-level tests/ suite (pnpm test at the repo root).


Fee tokens

feeTokenID is only a number; the TokenRegistry says what it means. These helpers take any { request({ method, params }) } object, so they work with viem, ethers or a raw EIP-1193 provider:

import {
  getFeeTokens,
  resolveFeeToken,
  getTokenIdByAddress,
  MORPH_HOODI_TESTNET,
} from "@morph-network/chain";

const rpc = { request: <T>(args: { method: string; params?: unknown }) => publicClient.request(args) as Promise<T> };  // viem
// const rpc = { request: <T>({ method, params }: { method: string; params?: unknown }) => provider.send(method, params ?? []) as Promise<T> }; // ethers

const tokens = await getFeeTokens(rpc, { network: "hoodi-testnet", activeOnly: true });
// [{ source: "registry", id: 4, address, decimals: 6, scale, isActive: true, priceRatio, symbol: "USDT" }, ...]

const usdt = await resolveFeeToken(rpc, 4, { network: "hoodi-testnet" });   // by id
await resolveFeeToken(rpc, usdt.address);                                    // by address
await getTokenIdByAddress(rpc, usdt.address);                                // 4 (undefined when unknown)

Options (FeeTokenQueryOptions / GetFeeTokensOptions):

| Option | Default | Meaning | |---|---|---| | network | — | "mainnet" / "hoodi-testnet" (or a MorphNetwork). Selects the registry address, and the snapshot used for symbols and for the offline fallback | | registry | the network's, else the standard proxy | Override the TokenRegistry address (custom deployment / fork) | | blockTag | "latest" | Block the reads are pinned to | | offlineFallback | false | On a transport failure, answer from the bundled snapshot instead of throwing. Needs network. A contract revert is never masked | | activeOnly | false | getFeeTokens only: drop tokens the registry has deactivated | | fetchMetadata | true | getFeeTokens / resolveFeeToken only: read ERC20 symbol()/name() for tokens missing from the snapshot |

The registry address comes from network.tokenRegistry, so passing network is enough; registry exists for a fork or a non-standard deployment.

Sizing feeLimit: ETH gas cost → token amount

feeLimit is denominated in the token's smallest unit, so a value copied from an ETH estimate is wrong by orders of magnitude. Convert with the registry's own pricing instead of hand-rolling the arithmetic:

import { ethToTokenAmount, tokenToEthAmount, isRegistryFeeToken } from "@morph-network/chain";

const gasCostWei = gasLimit * maxFeePerGas;              // what the tx costs in ETH
if (!isRegistryFeeToken(usdt)) throw new Error("need live scale/priceRatio");

const feeLimit = ethToTokenAmount(usdt, gasCostWei);     // rounds UP, like the node
const backToEth = tokenToEthAmount(usdt, feeLimit);      // for display only

ethToTokenAmount computes ceil(ethAmount * scale / priceRatio) and is verified wei-for-wei against the registry's calculateTokenAmount on both mainnet and Hoodi. Rounding up matters: a floor would leave the fee one unit short and the node would reject the transaction. tokenToEthAmount rounds down and is for display only — it is not a guarantee of what the node charges.

Both work in exact bigint arithmetic (no Number() on the way), and reject:

  • a negative amount (NEGATIVE_RLP_INTEGER);
  • an entry with no scale/priceRatio — i.e. anything whose source is "snapshot" — with FEE_TOKEN_NOT_FOUND. Read the registry before pricing;
  • a non-positive scale or priceRatio (INVALID_RPC_RESPONSE), which a misconfigured registry entry could otherwise turn into a divide-by-zero.

isRegistryFeeToken(token) narrows a FeeToken to the live variant, so the scale/priceRatio fields are typed as present rather than optional.

  • The registry has no symbol/name: they come from the bundled snapshot when id and address match, else from the token's ERC20 symbol()/name() (best effort; fetchMetadata: false skips it). Key on id or address, never on symbol — Hoodi has two tokens named "USDC".
  • Addresses from the registry are lowercase; compare with addressEquals.
  • Unknown ids/addresses (and feeTokenID 0, which means ETH) throw FEE_TOKEN_NOT_FOUND. A node outage throws the underlying error unless you pass offlineFallback: true together with network, in which case entries come from the snapshot with source: "snapshot" and no live fields.
  • Both networks ship a snapshot taken from their registry, but the registry stays authoritative (tokens are added, deactivated and re-priced on chain). Mainnet has two BGB and two USDC: key on id or address, never on symbol.