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/viem

v0.2.0

Published

Morph (MorphTx / Alt Fee / EIP-7702) support for viem.

Readme

@morph-network/viem

Morph Client SDK integration for viem.

This package is a viem extension / adapter layer: it adds Morph's custom transaction type (MorphTx, 0x7F) — Alt Fee (ERC20-denominated gas) and, as of v2, EIP-7702 authorization lists — on top of viem's own chain/serializer plumbing, without forking or patching viem.


✨ Features

  • 🔌 Ready-made viem chains (morphMainnet, morphHoodiTestnet) with Morph's transaction formatter and serializer already wired in — walletClient.signTransaction() just works.
  • 🧾 Full MorphTx envelope support: v0 (bare Alt Fee), v1 (+ reference/memo), v2 (+ EIP-7702 authorizationList).
  • 🔎 parseAltFeeTransaction / recoverAddress round-trip MorphTx bytes back into typed, normalized objects.
  • 🛠 No viem fork, no monkey-patching, no global side effects — a defineChain config plus a handful of typed functions.
  • 🧠 Re-exports everything from @morph-network/chain (networks, shared validation, RLP helpers, error codes), so one import is enough.

📦 Installation

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

viem (^2.24.0 — the first release with walletClient.signAuthorization; tested against 2.44.1) and @morph-network/chain (>=0.2.0 <0.3.0) are peer dependencies; chain is installed automatically by npm 7+ / pnpm.


Chains

import { morphMainnet, morphHoodiTestnet } from "@morph-network/viem";

| Export | Chain ID | RPC | WS | Explorer | |---|---|---|---|---| | morphMainnet | 2818 | https://rpc-bgw.morph.network | wss://rpc-bgw.morph.network | Morph Explorer | | morphHoodiTestnet | 2910 | https://rpc-hoodi-bgw.morph.network | wss://rpc-hoodi-bgw.morph.network | Morph Hoodi Explorer |

Both are plain viem chains built with defineChain, with formatters.transactionRequest.format and serializers.transaction pointed at this package's MorphTx-aware implementations. Use them with createWalletClient / createPublicClient exactly like any other viem chain — MorphTx fields (feeTokenID, feeLimit, reference, memo, authorizationList) are simply additional, optional properties on the transaction request.

They also carry rpcUrls.default.webSocket, blockExplorers.default (name + URL) and a contracts.tokenRegistry entry, all filled from the shared MorphNetwork configs so the two never drift:

morphHoodiTestnet.contracts.tokenRegistry.address;
// 0x5300000000000000000000000000000000000021  (same predeploy on every network)

Fee tokens

feeTokenID is a registry id, not a token address, and feeLimit is in the token's smallest unit. Read the registry through the client and convert with the registry's own pricing instead of hand-rolling either:

import { getFeeTokens, ethToTokenAmount, isRegistryFeeToken } from "@morph-network/viem";
import { createPublicClient, createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { morphHoodiTestnet } from "@morph-network/viem";

const publicClient = createPublicClient({ chain: morphHoodiTestnet, transport: http() });
const walletClient = createWalletClient({
  account: privateKeyToAccount(privateKey),   // a local account signs v0/v1/v2 offline
  chain: morphHoodiTestnet,
  transport: http(),
});

const rpc = {
  request: <T>(args: { method: string; params?: unknown }) =>
    publicClient.request(args as never) as Promise<T>,
};
const tokens = await getFeeTokens(rpc, { network: "hoodi-testnet", activeOnly: true });
const usdt = tokens.find((t) => t.id === 4);
if (usdt == null) throw new Error("USDT (#4) is not listed as an active fee token");
if (!isRegistryFeeToken(usdt)) throw new Error("need live scale/priceRatio");

const gas = 200_000n;
const maxFeePerGas = 2_000_000_000n;
const feeLimit = ethToTokenAmount(usdt, gas * maxFeePerGas);   // rounds up, like the node

await walletClient.signTransaction({
  to, gas, maxFeePerGas, maxPriorityFeePerGas: 1_000_000_000n,
  feeTokenID: usdt.id,
  feeLimit,
});

Key tokens on id/address, never on symbol: Hoodi has two USDC (#7 USDC.e, #11 USDC) and mainnet has two BGB and two USDC. Unknown ids and feeTokenID: 0 (ETH pays gas, not a registry token) throw FEE_TOKEN_NOT_FOUND. See @morph-network/chain's "Fee tokens" section for offlineFallback and the snapshot caveats.


Quick start

A plain transaction behaves exactly like stock viem — MorphTx fields are opt-in:

import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { morphHoodiTestnet } from "@morph-network/viem";

const account = privateKeyToAccount(privateKey);
const client = createWalletClient({
  account,
  chain: morphHoodiTestnet,
  transport: http(),
});

// No Morph fields -> ordinary EIP-1559 transaction.
const signed = await client.signTransaction({
  to,
  value: 0n,
  gas: 21_000n,
  maxFeePerGas: 2_000_000_000n,
  maxPriorityFeePerGas: 1_000_000_000n,
});

MorphTx envelope versions

MorphTx is transaction type 0x7F. It has three wire envelopes, picked automatically by resolveMorphTxVersion based on which fields are set.

Gas payment by envelope version: v1 and v2 accept either ETH (feeTokenID = 0) or an AltFee token (feeTokenID > 0); v0 accepts an AltFee token only — the node rejects a zero token id in v0.

v0 is never inferred. Inference follows the node (geth InferUnsignedMorphTxVersion, reth TxMorph::inferred_version): v1 is the baseline, a non-empty authorizationList selects v2, and v0 requires an explicit morphTxVersion: 0.

v0 is local-signing only. A JSON-RPC account (account: "0x…", or any account whose signTransaction is not available) makes viem call eth_sendTransaction / eth_signTransaction, and the node has no version field: it infers v1. The chain formatter therefore rejects an explicit morphTxVersion: 0 there with NODE_SIGNING_MISMATCH, as it does for the other shapes the node would rebuild differently (a MorphTx declared only by type, or a formed v2 with an empty authorization list). Sign v0 with a local account and broadcast it via eth_sendRawTransaction. estimateGas / call / fillTransaction are not gated: they never produce signed bytes.

reference must be exactly 32 bytes or omitted (the node's ReferenceLength); anything else throws INVALID_REFERENCE_LENGTH before a signature is produced. Prefer omitting it over passing "0x": geth accepts the empty string, reth's Option<B256> does not.

| Version | Envelope | Extra fields | When | |---|---|---|---| | v0 | 0x7F \|\| RLP(base11 + sig) | — | AltFee token only (feeTokenID > 0) | | v1 | 0x7F \|\| 0x01 \|\| RLP(...) | reference, memo | + a memo / correlation id; lowest version for ETH-paid gas | | v2 | 0x7F \|\| 0x02 \|\| RLP(...) | reference, memo, authorizationList | + EIP-7702 delegation |

const signed = await client.signTransaction({
  to,
  gas: 200_000n,
  maxFeePerGas: 2_000_000_000n,
  maxPriorityFeePerGas: 1_000_000_000n,
  feeTokenID: 1,              // an AltFee token pays gas; 0 means ETH pays gas (v1/v2 only)
  feeLimit: 1_000_000n,       // only valid when feeTokenID > 0
  reference: "0x9fb1bdfedbbe3bd552cf6d68a2d9f95d128c0d492df343bef9babc382cd77c1a", // v1+, exactly 32 bytes
  memo: "0x48656c6c6f",       // v1+, up to 64 bytes
});

signed.startsWith("0x7f01"); // true — reference/memo pushed this to v1

MorphTx v2 (Alt Fee + EIP-7702)

A MorphTx envelope carrying an EIP-7702 authorization list. Version is inferred: give the transaction a non-empty authorizationList and it signs as v2 (0x7f02).

import { createWalletClient, http } from "viem";
import { morphHoodiTestnet } from "@morph-network/viem";

const client = createWalletClient({ account, chain: morphHoodiTestnet, transport: http() });

// The authorization's `nonce` is the one of the AUTHORIZING account, not the
// transaction's nonce.
const authorization = await client.signAuthorization({
  contractAddress,   // delegation target
  chainId,
  nonce,
});

const signed = await client.signTransaction({
  to,
  gas: 200_000n,
  maxFeePerGas: 2_000_000_000n,
  maxPriorityFeePerGas: 1_000_000_000n,
  feeTokenID: 1,              // an AltFee token pays gas; 0 means ETH pays gas (v1/v2 only)
  feeLimit: 1_000_000n,       // only valid when feeTokenID > 0
  reference: "0x9fb1bdfedbbe3bd552cf6d68a2d9f95d128c0d492df343bef9babc382cd77c1a", // exactly 32 bytes
  authorizationList: [authorization],
});

signed.startsWith("0x7f02"); // true

client.signAuthorization is viem's own EIP-7702 method — this package does not re-implement it (contrast @morph-network/ethers5, where ethers v5 has no EIP-7702 support at all). For symmetry with the other adapters it also exports a thin helper, signAuthorization({ account, contractAddress, chainId, nonce }), which calls the local account's signAuthorization and returns the flat canonical MorphAuthorization.

Parsing and recovery

import { parseAltFeeTransaction, recoverAddress } from "@morph-network/viem";

const tx = parseAltFeeTransaction(signed);
tx.morphTxVersion;      // 2
tx.authorizationList;   // always defined on v2 (may be [])
tx.feeTokenID;          // 0 means ETH pays the gas

const signer = await recoverAddress({ serializedTransaction: signed });

recoverAddress reads the payload's shape to pick the candidate reading; only the ambiguous row below also depends on whether you passed a signature:

| 0x7f payload | Meaning | Works without a hint | |---|---|---| | 0x7f01… / 0x7f02… | signed v1 / v2 | yes | | 11 fields | v0 signing preimage | needs a signature | | 15 fields | v2 signing preimage | needs a signature | | 14 fields, slot 11 ≠ 0x01 | signed v0 | yes | | 14 fields, slot 11 = 0x01, slot 12 empty | v1 signing preimage | needs a signature | | 14 fields, slot 11 = 0x01, slot 12 not 0 or 32 bytes | signed v0 | yes | | 14 fields, slot 11 = 0x01, slot 12 = 32 bytes | ambiguous | only without an external signature — see below |

A 14-field body with 0x01 in slot 11 and a 32-byte slot 12 is byte-identical whether it is a signed v0 with yParity=1 or a v1 preimage with a full-width reference. Nothing in the bytes separates them. If you also pass an external signature, the two readings recover different addresses, so recoverAddress throws AMBIGUOUS_ALT_FEE_PAYLOAD instead of guessing and you must say which one you mean. Without an external signature only the signed reading can work, so the embedded signature is used (if that reading cannot produce an address either, the same error is thrown):

// `preimage`: the unsigned v1 payload you built; `signedV0`: a signed v0 payload.
// `signature`: the signature you want to check against that payload.
recoverAddress({ serializedTransaction: preimage, signature, assume: "v1-unsigned" });
recoverAddress({ serializedTransaction: signedV0, signature, assume: "signed" });

Known limitation. With no external signature and no assume, a v1 preimage with a full-width reference is read as a signed v0, so its reference / memo are taken as r / s. That usually fails with AMBIGUOUS_ALT_FEE_PAYLOAD, but for some values it can instead yield an address that belongs to no signer. The bytes cannot rule this out, and a default that always threw would reject every ordinary signed v0 whose yParity is 1. Pass assume whenever the payload might be a v1 preimage.

Do not authorize on recoverAddress alone for untrusted payloads. For a payload you did not build yourself, the recovered address only proves the bytes were read one particular way; the same bytes can be a different transaction under the other reading. Pass assume explicitly, or verify the parsed fields (not just the signer) before acting on the result. When a payload is read as a signed v0 (assume: "signed", or any shape the table marks signed), its last three slots are the signature and an external signature replaces them, so only the first 11 fields are covered. When it is read as a v1 preimage, the whole payload is hashed and reference / memo are covered too.

parseTransaction is the general entry point — it dispatches to parseAltFeeTransaction for 0x7f-prefixed bytes and to viem's own parseTransaction for everything else.

Parsing an unsigned payload is ambiguous at certain field counts (a signed v0 and an unsigned v1 both RLP-encode to 14 fields with no envelope byte), so parseAltFeeTransaction takes an optional hint:

parseAltFeeTransaction(preimage, { assume: "v1-unsigned" });
parseAltFeeTransaction(preimage, { assume: "v2-unsigned" }); // the v2 signing preimage (15 fields)

Signed v1/v2 payloads carry an explicit 0x01/0x02 envelope byte, so they are never ambiguous and never need a hint.

The parsed object is a viem object — not a cross-adapter DTO

parseAltFeeTransaction returns a viem transaction: gas is gas, exactly as viem spells it everywhere else. @morph-network/ethers and @morph-network/ethers5 read gasLimit, following ethers' convention. The two names are not interchangeable, and feeding a parsed object straight into another adapter's serializer silently encodes gas as zero — the serializer does not throw, because a missing gas limit is a legal empty RLP integer:

const parsed = parseAltFeeTransaction(raw);   // { gas: 200_000n, ... }
serializeEthers(parsed);                      // ✗ gas slot becomes 0x (gas = 0)

serializeEthers({ ...parsed, gasLimit: parsed.gas });   // ✓
// or, equivalently, drop the viem spelling:
const { gas, ...rest } = parsed;
serializeEthers({ ...rest, gasLimit: gas });

The reverse direction is just as silent: ethers-shaped input with only gasLimit serializes to a zero gas limit in this package. There is deliberately no automatic renaming inside the serializers — each adapter consumes its own library's request shape, so that a misspelled field fails visibly in your code rather than being guessed at here. Pass an explicit mapping at every cross-package boundary, and check the round trip:

parseAltFeeTransaction(serializeEthers({ ...parsed, gasLimit: parsed.gas }));
// gas is preserved

Authorization input shapes

Three shapes are accepted by authorizationList and all normalize to the same value — this package re-exports the normalizer from @morph-network/chain:

{ address, chainId, nonce, yParity, r, s }                  // flat
{ address, chainId, nonce, signature: { yParity, r, s } }   // nested (ethers6)
{ address, chainId, nonce, v, r, s }                         // viem's SignedAuthorization

Rules worth knowing

  • An empty authorizationList does not upgrade the version. [] is indistinguishable from "no authorization" on an unsigned transaction, so it stays v1. An already-formed v2 marks itself with morphTxVersion: 2, and only then is [] meaningful.
  • An authorization list with no other Morph field is a plain 0x04. The SDK throws and tells you so rather than wrapping a standard EIP-7702 transaction in a MorphTx envelope.
  • Non-empty authorization + empty to is rejected — nodes reject MorphTx contract creation with an authorization list.
  • feeTokenID = 0 forbids feeLimit — the node reports illegal extra parameters.
  • Routing uses isMorphTx, not isAltFeeTx. isAltFeeTx only answers "is gas paid with an ERC20?" — a transaction paying gas with ETH (feeTokenID = 0) is a valid MorphTx but not an Alt Fee transaction, and routing on the wrong predicate used to mean such transactions fell through to viem's native 0x04 path, silently dropping reference/memo.
  • v2 needs a Celadon-activated node to broadcast. Signing works offline against any node.

Encoding

Every RLP integer slot — including chainId / nonce / yParity / r / s inside each authorization — is encoded as a minimal big-endian integer: zero is the empty string (0x80), leading zeros are stripped. Authorization r/s are not written as fixed 32 bytes; a zero signature on the wire is 0x80, and geth rejects a padded one as a non-canonical integer.

address / data / reference / memo are byte strings and keep their leading zeros.


API reference

chains

| Export | Description | |---|---| | morphMainnet, morphHoodiTestnet | Pre-configured viem Chain objects. | | formatTransactionRequest(tx) | The pure MorphTx-aware JSON-RPC payload builder: routes on isMorphTx and never emits morphTxVersion. Call this when you want the payload; it applies no node-signing guard. | | formatChainTransactionRequest(tx, action?) | What the chains register as formatters.transactionRequest.format. Wraps the builder with viem's key probe and the node-signing guard (sendTransaction / signTransaction only). | | isAltFeeTransactionRequest(tx) | Type guard — tx.feeTokenID > 0. | | AltFeeTransactionRequest, TransactionRequest | Types: a viem TransactionRequest intersected with MorphTx fields. |

serializer

| Export | Description | |---|---| | serializeTransaction(tx, signature?) | Drop-in replacement for viem's serializer; routes MorphTx (isMorphTx) to serializeAltFeeTransaction, everything else to viem's own. Used as serializers.transaction on both chains. | | serializeAltFeeTransaction(tx, signature?) | Encodes a MorphTx to its v0/v1/v2 wire bytes. Validates fee fields, rejects an authorization list on contract creation, and picks the envelope via resolveMorphTxVersion. | | canonicalRlpInt(value) | Minimal-integer RLP encoding for a single quantity. | | AltFeeTransaction, SerializeTransactionFn, RlpIntLike | Supporting types. |

authorization

| Export | Description | |---|---| | signAuthorization({ account, contractAddress, chainId, nonce }) | Signs an EIP-7702 authorization with a viem local account and returns a normalized MorphAuthorization. | | SignAuthorizationParams, AuthorizationSigner | Supporting types. |

parser

| Export | Description | |---|---| | parseTransaction(serialized, options?) | General entry point; dispatches on the leading type byte. | | parseAltFeeTransaction(serialized, options?) | Decodes MorphTx bytes (any version, signed or not) into a typed, normalized object. options.assume resolves field-count ambiguity for unsigned payloads ("signed" / "v1-unsigned" / "v2-unsigned"). | | parseSignature(fields) | Extract { r, s, v, yParity } from the trailing three RLP fields of a signed payload. | | ParseAltFeeTransactionOptions, AltFeeTransactionSerializable, AltFeeValues, TransactionSerializedAltFee, TransactionType, AltFeeTransactionType | Supporting types. |

recover

| Export | Description | |---|---| | recoverAddress(parameters) | Recovers the signer address from a serialized transaction or a raw hash+signature. For 0x7f payloads it classifies the body by field count (see above); parameters.assume ("signed" / "v1-unsigned") resolves the one 14-field shape that is genuinely ambiguous. Delegates to viem's recoverTransactionAddress for everything else. | | RecoverTransactionAddressParameters | Supporting type. |

Re-exported from @morph-network/chain

@morph-network/viem re-exports the whole shared package, including:

  • isMorphTx, isAltFeeTx, hasAuthList, resolveMorphTxVersion, assertAuthListCannotCreate, assertFeeLimitWithoutToken
  • normalizeAuthorization, normalizeAuthorizationList, toRlpAuthTuples, MorphAuthorization
  • MorphSdkError, MorphSdkErrorCode
  • MORPH_MAINNET, MORPH_HOODI_TESTNET, MORPH_NETWORKS, getMorphNetwork, network types
  • Fee token discovery: getFeeTokens, resolveFeeToken, getTokenIdByAddress, ethToTokenAmount / tokenToEthAmount, isRegistryFeeToken, getFeeTokenSnapshot / findFeeTokenSnapshot, addressEquals, tokenRegistryAbi
  • toRlpIntHex and other RLP helpers

See @morph-network/chain for the full list and for the error codes thrown across all three adapters.


Error handling

Every rejection (bad authorization shape, version/field contradictions, malformed fee fields, invalid serialized bytes, ...) throws a MorphSdkError with a stable .code from MorphSdkErrorCode, so callers can branch on the failure instead of matching message text:

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

try {
  // `await` matters: without it a rejected promise never reaches `catch`.
  await client.signTransaction({ ...fields, authorizationList: [auth] });
} catch (err) {
  if (err instanceof MorphSdkError && err.code === MorphSdkErrorCode.AUTH_LIST_CANNOT_CREATE) {
    // non-empty authorization list on a contract-creation tx
  }
}