@morph-network/ethers5
v0.2.0
Published
Morph (MorphTx / Alt Fee / EIP-7702) support for ethers v5.
Maintainers
Readme
@morph-network/ethers5
Morph Client SDK adapter for ethers v5 — a drop-in signer wrapper that adds
MorphTx (0x7F) support, including Alt Fee gas payment and EIP-7702
delegation (MorphTx v2), on top of an ordinary ethers v5 Signer.
ethers v5.8.0 has no native EIP-7702 support at all. This package is the only one of the three adapters that has to implement authorization signing from scratch rather than delegate to the underlying library — see MorphTx v2 below.
Installation
pnpm add @morph-network/ethers5 ethers@^5
# or
npm install @morph-network/ethers5 ethers@^5The peer dependency is the regular ethers package, major version 5
(^5.0.0; tested against 5.8.0). Import ethers normally in your own code.
@morph-network/chain is a peer dependency (>=0.2.0 <0.3.0) and is
where the version-resolution, authorization-normalization and error-code logic
shared across all three adapters actually lives.
Using this alongside ethers v6 (read this if you also use @morph-network/ethers)
Both adapters declare a peer dependency named ethers — this one needs v5,
@morph-network/ethers needs v6. A package manager binds a peer by package
name, so one name cannot satisfy both majors at once. If your app lists v6 as
ethers (which @morph-network/ethers needs) and installs v5 under an alias:
// ✗ this breaks @morph-network/ethers5
{ "ethers": "6.17.0", "ethers5": "npm:[email protected]" }…this package's ethers peer resolves to v6. Aliasing the other way
("ethers": "^5.8.0", "ethers6": "npm:ethers@^6.14.4") just moves the problem
to @morph-network/ethers, which then gets v5. There is no alias arrangement
that satisfies both.
Put the ethers v5 consumer in its own workspace (or app) that depends on plain
ethers v5, and import this adapter from there:
// apps/legacy-wallet/package.json
{ "dependencies": { "ethers": "^5.8.0", "@morph-network/ethers5": "..." } }The SDK detects the mismatch at import time and throws
MorphSdkError with code === "PEER_VERSION_MISMATCH" naming the loaded
version, instead of failing deep inside a bundler's dependency optimizer with
Package subpath './lib/utils.js' is not defined by "exports".
The check probes the loaded module's API surface (providers.Web3Provider and
utils.RLP.encode — both v5-only in that form), not its version string, so a
fork or a relabelled build that still behaves like v5 works. PEER_ETHERS_VERSION
is exported if you want to log the version that was actually validated.
Quick start
MorphSigner.from() wraps any ethers v5 Signer (a Wallet, or a
provider-backed signer such as Web3Provider.getSigner()) in a transparent
Proxy. Every property/method you don't override passes straight through to
the wrapped signer, so existing code keeps working unchanged:
import { Wallet, providers, utils } from "ethers";
import { MorphSigner } from "@morph-network/ethers5";
const provider = new providers.JsonRpcProvider(rpcUrl);
const wallet = new Wallet(privateKey, provider);
const signer = MorphSigner.from(wallet);
// Ordinary transaction — MorphTx fields are absent, so this is identical to
// calling `wallet.sendTransaction()` directly.
await signer.sendTransaction({ to, value: utils.parseEther("0.1") });MorphSigner detects whether a transaction request is a MorphTx (via
isMorphTransaction, equivalent to @morph-network/chain's isMorphTx) on
every call and only takes over signTransaction / sendTransaction /
estimateGas / populateTransaction when it is. Non-MorphTx requests are
passed to the inner signer unchanged (with any stray Alt Fee fields stripped
first), so this wrapper is safe to use as your signer unconditionally.
Alt Fee transactions (v0 / v1)
Set feeTokenID to pay gas with an AltFee token instead of ETH;
feeTokenID = 0 (or omitted) means ETH pays gas and is not an Alt Fee
transaction, but is still a valid MorphTx. v1 and v2 accept either ETH or an
AltFee token; v0 accepts an AltFee token only (nodes reject a zero token id
in v0). v0 is never inferred — inference follows the node (v1 baseline), so
an ERC20 payer without an explicit version signs as v1. Pass
morphTxVersion: 0 for the legacy v0 bytes — but only with a local signer: a
Web3Provider delegates signing to the wallet/node, which has no version field
and always infers v1, so the browser path throws NODE_SIGNING_MISMATCH rather
than return bytes other than the ones requested.
const signed = await signer.signTransaction({
to,
gasLimit: 21_000,
gasPrice: 1_000_000_000,
feeTokenID: 1, // AltFee token id; 0 or omitted = ETH pays gas (v1/v2 only)
feeLimit: 1_000_000n, // only valid when feeTokenID > 0
});Adding reference and/or memo upgrades the envelope to v1 automatically — no
version flag to set. reference must be exactly 32 bytes or omitted; memo
is capped at 64 bytes. Prefer omitting reference over passing "0x": geth
accepts the empty string, reth's Option<B256> does not:
const signed = await signer.signTransaction({
to,
gasLimit: 21_000,
gasPrice: 1_000_000_000,
feeTokenID: 1,
feeLimit: 1_000_000n,
reference: "0x9fb1bdfedbbe3bd552cf6d68a2d9f95d128c0d492df343bef9babc382cd77c1a",
memo: "0x",
});sendTransaction and populateTransaction understand the same fields. A
Web3-provider signer (a browser wallet) is routed through raw
eth_signTransaction / eth_sendTransaction RPC calls, while a Wallet signs
locally and submits through eth_sendRawTransaction — ethers v5 has no concept
of a 0x7F transaction type to delegate to.
MorphTx v2 (Alt Fee + EIP-7702)
MorphTx v2 carries an EIP-7702 authorization list inside a MorphTx envelope.
Version is inferred — pass a non-empty authorizationList and the
transaction signs as v2 (0x7f02).
import { Wallet } from "ethers";
import { MorphSigner, signAuthorization } from "@morph-network/ethers5";
const wallet = new Wallet(privateKey);
const signer = MorphSigner.from(wallet);
// ethers v5 has NO EIP-7702 support — this package provides it.
const auth = await signAuthorization({
signer: wallet,
contractAddress, // delegation target
chainId,
nonce, // nonce of the authorizing account
});
const signed = await signer.signTransaction({
to,
gasLimit: 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: [auth],
});
signed.startsWith("0x7f02"); // trueWhy authorization signing is implemented here
ethers v5.8.0 predates EIP-7702 entirely: it has no signAuthorization, no
populateAuthorization, and no authorization tuple type. This package
therefore implements the signing domain itself:
authHash = keccak256(0x05 || RLP([chainId, address, nonce]))That is exactly EIP-7702's domain — not a Morph-specific variant. chainId = 0
means "valid on any chain"; address = 0x0…0 means "clear the delegation".
nonce is the nonce of the authorizing account, not of the transaction
sender.
The implementation is cross-validated against viem's reference: same key,
same parameters, identical yParity / r / s, and it reproduces the
official devnet vector's documented authorization hash
((53077, 0x7a2088…814f, 3) → a fixed, pinned digest).
hashAuthorization({ address, chainId, nonce }) is also exported directly, in
case you need the raw digest without signing (e.g. to verify a signature
produced elsewhere).
Authorization input shapes
Three shapes are accepted and all normalize to the same value:
{ address, chainId, nonce, yParity, r, s } // flat
{ address, chainId, nonce, signature: { yParity, r, s } } // nested
{ address, chainId, nonce, v, r, s } // viem stylesignAuthorization returns the flat shape (a MorphAuthorization), ready to
drop straight into authorizationList.
Rules worth knowing
- An empty
authorizationListdoes not upgrade the version.[]is indistinguishable from "no authorization" on an unsigned transaction, so it stays v1. An already-formed v2 marks itself withmorphTxVersion: 2, and only then is[]meaningful. - An authorization list with no other Morph field is a plain
0x04. The SDK throws (AUTH_LIST_REQUIRES_MORPH_FIELDS) and tells you so rather than wrapping a standard EIP-7702 transaction in a MorphTx envelope. - Non-empty authorization + empty
tois rejected (AUTH_LIST_CANNOT_CREATE) — nodes reject MorphTx contract creation with an authorization list. feeTokenID = 0forbidsfeeLimit(FEE_LIMIT_WITHOUT_TOKEN) — the node reportsillegal extra parameters.- Routing uses
isMorphTransaction, notisAltFeeTx. A transaction paying gas with ETH (feeTokenID = 0) is a valid MorphTx but is not an Alt Fee transaction; routing onisAltFeeTxwould throwinvalid object keyhere. - v2 needs a Celadon-activated node to broadcast. Signing works offline.
- A signer that cannot sign
0x7fcannot send a MorphTx. A signer with neither a private key nor aWeb3Provider-backed wallet (for example a plain JSON-RPC signer) cannot produce a MorphTx payload.sendTransactionthrowsUNSUPPORTED_SIGNERfor it, matchingsignTransaction, instead of silently sending a plain transaction that pays gas in ETH. Use aWalletor a browser wallet.
Every rejection throws a MorphSdkError (re-exported from
@morph-network/chain) carrying a stable .code you can branch on instead of
matching message text — see that package's README for the full list of
error codes.
ethers v5-specific traps this package handles for you
Both are covered by the test suite, so they are handled rather than documented as caller homework:
allowedTransactionKeysis a hard allowlist.authorizationListandmorphTxVersionmust be in it orcheckTransactionthrowsinvalid transaction key.hexStripZeros("0x01")returns"0x1"— an odd-length hex string thatarrayifyrejects. Integer slots are built as byte arrays instead, which also makes zero encode as the empty string rather than a0x00byte.
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 use the same rule as every other integer and 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.
Gas field name: gasLimit, not gas
Like ethers v5 itself, this package reads gasLimit. @morph-network/viem
reads gas, and its parseAltFeeTransaction returns an object spelled that
way. Passing a parsed viem object straight in here does not throw — a missing
gas limit is a legal empty RLP integer, so the gas slot is silently encoded as
zero:
const parsed = parseViem(raw); // { gas: 200_000n, ... }
serializeAltFeeTransaction(parsed); // ✗ gas = 0
serializeAltFeeTransaction({ ...parsed, gasLimit: parsed.gas }); // ✓Field names are not renamed between libraries on purpose: each adapter consumes its own library's shape, so a mismatch stays visible at the call site. Map explicitly at every cross-package boundary.
API reference
| Export | What it does |
| --- | --- |
| MorphSigner.from(signer) | Wraps an ethers v5 Signer in a Proxy that intercepts signTransaction, sendTransaction, estimateGas, populateTransaction and checkTransaction for MorphTx requests, passing everything else straight through. |
| signAuthorization({ signer, contractAddress, chainId?, nonce }) | Signs an EIP-7702 authorization tuple with an ethers v5 Wallet (a signer exposing a private signing key — provider-backed signers aren't supported here, since there is no RPC method to sign just an authorization). chainId defaults to the signer's connected chain; when the signer has no provider (or getNetwork() fails) it throws MISSING_CHAIN_ID instead of falling back to 0, which would mean "valid on every chain". Pass chainId: 0 explicitly if that is what you want. |
| hashAuthorization({ address, chainId, nonce }) | Computes the EIP-7702 authorization digest without signing. |
| serializeAltFeeTransaction(tx, signature?) | Low-level RLP serializer for the 0x7F envelope (v0/v1/v2); normally called indirectly via MorphSigner. |
| isMorphTransaction, allowedTransactionKeys | ethers5-flavored wrapper of @morph-network/chain's isMorphTx routing predicate, and the signer's transaction-key allowlist. |
| canonicalRlpIntV5(value), trim(...) | Serializer helpers: minimal-integer RLP encoding for a single quantity, and hex trimming. |
| getSignerSource(signer), SIGNER_SOURCE | Classify a signer as wallet-backed vs. provider-backed (decides raw-RLP signing vs. eth_signTransaction). |
| Types | TransactionRequest, TransactionResponse, UnsignedTransaction, MorphTxContext, SerializableAltFeeTransaction, SignAuthorizationParams. |
| getRpcProvider, getRpcTransaction, assertRpcProvider | Build the raw JSON-RPC transaction payload (eth_sendTransaction / eth_signTransaction / eth_estimateGas shape) for a MorphTx, including chainId / nonce and the version-gated reference / memo / authorizationList fields, and assert that a given provider can issue raw RPC calls. Fields the caller leaves out are omitted rather than defaulted to 0. |
| PEER_ETHERS_VERSION | The ethers version this instance validated at import (e.g. "ethers/5.8.0"), for diagnostics. |
| re-exported from @morph-network/chain | isAltFeeTx, isMorphTx, normalizeAuthorization(List), resolveMorphTxVersion, MorphSdkError, MorphSdkErrorCode, MorphAuthorization, the fee token helpers (getFeeTokens, resolveFeeToken, getTokenIdByAddress, ethToTokenAmount, tokenToEthAmount, isRegistryFeeToken, getFeeTokenSnapshot, findFeeTokenSnapshot, addressEquals), the network constants, and the rest of the shared primitives. |
Reading fee tokens through ethers v5
feeLimit is denominated in the token's smallest unit, so never copy an ETH
estimate into it. Read the registry and convert:
import { providers, Wallet } from "ethers";
import {
MorphSigner,
getFeeTokens,
ethToTokenAmount,
isRegistryFeeToken,
} from "@morph-network/ethers5";
const provider = new providers.JsonRpcProvider(rpcUrl);
const signer = MorphSigner.from(new Wallet(privateKey, provider));
const rpc = { request: ({ method, params }) => provider.send(method, params ?? []) };
const tokens = await getFeeTokens(rpc, { network: "hoodi-testnet", activeOnly: true });
const usdt = tokens.find((t) => t.id === 4)!;
if (!isRegistryFeeToken(usdt)) throw new Error("need live scale/priceRatio");
const gasLimit = 200_000;
const maxFeePerGas = 2_000_000_000;
await signer.sendTransaction({
to, gasLimit, maxFeePerGas, maxPriorityFeePerGas: 1_000_000_000,
feeTokenID: usdt.id,
feeLimit: ethToTokenAmount(usdt, BigInt(gasLimit) * BigInt(maxFeePerGas)),
});Key tokens on id/address, never on symbol — Hoodi has two USDC. The
registry has no symbol/name; those come from the bundled snapshot or the
token's own ERC20 metadata. See @morph-network/chain's "Fee tokens" section.
See @morph-network/chain for the full MorphTx version model,
error codes, and RLP encoding rules shared by all three adapters.
