@morph-network/ethers
v0.2.0
Published
Morph (MorphTx / Alt Fee / EIP-7702) support for ethers v6.
Maintainers
Readme
@morph-network/ethers
Morph Client SDK adapter for ethers v6. A thin wrapper around ethers.Signer
that adds support for Morph's 0x7F MorphTx transaction type (Alt Fee + v1
reference/memo + v2 EIP-7702 authorization lists) — without forking or
monkey-patching ethers itself. Anything that is not a MorphTx is passed
straight through to the wrapped signer untouched.
Installation
pnpm add ethers @morph-network/ethers
# or
npm install ethers @morph-network/ethersethers (^6.14.4) is a required peer — EIP-7702 (wallet.authorize()) first
shipped in 6.14.0, and 6.14.1–6.14.4 fix 7702 JSON-RPC/serialization bugs;
6.16.0 is what this package is tested against;
@morph-network/chain (>=0.2.0 <0.3.0) is a peer dependency too
and is installed automatically by npm 7+ / pnpm — it holds the
library-agnostic MorphTx/EIP-7702 primitives shared by this package, the
ethers5 adapter, and the viem adapter.
Quick start
Wrap any ethers.Signer (a Wallet, an HDNodeWallet, a BrowserProvider
signer, …) with MorphSigner.from(). The result is a proxy: every method you
already use (signMessage, getAddress, connect, …) is forwarded to the
original signer unchanged, while signTransaction / sendTransaction /
estimateGas / populateTransaction gain MorphTx awareness.
import { JsonRpcProvider, Wallet } from "ethers";
import { MorphSigner } from "@morph-network/ethers";
const wallet = new Wallet(privateKey, new JsonRpcProvider(rpcUrl));
const signer = MorphSigner.from(wallet);
// A transaction with no Morph fields is routed straight to ethers, unmodified.
await signer.sendTransaction({ to, value: 1_000_000_000_000_000n });Routing is based on isMorphTx, not on isAltFeeTx — a transaction that pays
gas with ETH (feeTokenID: 0) is still a MorphTx and must take the MorphTx
path (losing reference/memo otherwise); see "Rules worth knowing" below.
Alt Fee transactions (v0 / v1)
Set feeTokenID to pay gas with an AltFee token instead of ETH, and optionally
reference / memo to attach an application-level tag to the transaction
(reference must be exactly 32 bytes — see below).
The envelope version is inferred automatically — no version field to set by
hand:
const signed = await signer.signTransaction({
to,
gasLimit: 200_000n,
maxFeePerGas: 2_000_000_000n,
maxPriorityFeePerGas: 1_000_000_000n,
feeTokenID: 1, // an AltFee token (by token id) pays gas; 0 or omitted means ETH pays gas
feeLimit: 1_000_000n, // only valid when feeTokenID > 0
reference: "0x9fb1bdfedbbe3bd552cf6d68a2d9f95d128c0d492df343bef9babc382cd77c1a", // optional; exactly 32 bytes, bumps the envelope to v1 if set
});| You set... | Envelope | Wire prefix |
|---|---|---|
| neither reference/memo nor authorizationList (any feeTokenID) | v1 | 0x7f01 |
| non-empty reference and/or memo | v1 | 0x7f01 |
| non-empty authorizationList | v2 | 0x7f02 |
| morphTxVersion: 0 explicitly | v0 | 0x7f |
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
— nodes reject a zero token id in v0 at encode, decode and validation time.
v0 is never inferred. Version inference follows the node (geth
InferUnsignedMorphTxVersion, reth TxMorph::inferred_version), where v1 is
the baseline, so { feeTokenID: 1 } signs as v1. Pass morphTxVersion: 0 to
produce the legacy v0 bytes.
v0 requires a local signer. A BrowserProvider sends the request to the
wallet/node, which has no version field and always infers v1, so
signTransaction / sendTransaction throw NODE_SIGNING_MISMATCH for an
explicit morphTxVersion: 0 instead of returning different bytes than asked
for. Sign v0 with a private-key Wallet (or serialize it yourself) and submit
the raw transaction.
reference is a byte string, not a free-form tag: it must be omitted or
exactly 32 bytes, otherwise the SDK throws INVALID_REFERENCE_LENGTH and
the node rejects the payload too. memo is capped at 64 bytes. (Pass no
reference rather than "0x": geth accepts the empty string, reth's
Option<B256> does not.)
With a BrowserProvider signer, signTransaction/sendTransaction are
dispatched via eth_signTransaction/eth_sendTransaction (the wallet/node
signs); with a private-key Wallet, this package signs the RLP preimage
itself and submits the raw transaction via eth_sendRawTransaction.
MorphTx v2 (Alt Fee + EIP-7702)
MorphTx v2 carries an EIP-7702 authorization list inside an Alt Fee
transaction. Version is inferred — pass a non-empty authorizationList and the
transaction signs as v2 (0x7f02).
import { JsonRpcProvider, Wallet } from "ethers";
import { MorphSigner } from "@morph-network/ethers";
const wallet = new Wallet(privateKey, new JsonRpcProvider(rpcUrl));
const signer = MorphSigner.from(wallet);
// Use `authorize()` — it signs AND returns the tuple.
// (`populateAuthorization()` only fills in chainId/nonce; it does not sign.)
const auth = await wallet.authorize({
address: 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"); // trueAuthorization input shapes
Three shapes are accepted and all normalize to the same value:
// 1. flat
{ address, chainId, nonce, yParity, r, s }
// 2. nested (ethers6's native shape)
{ address, chainId, nonce, signature: { yParity, r, s } }
// 3. viem's SignedAuthorization (flat, bigint/hex fields)The nested shape is required when handing entries to ethers itself.
authorizationify() reads authorization.signature; given a flat
{ yParity, r, s } it does not complain — it silently zeroes all three, which
produces a well-formed transaction that authorizes nothing. This adapter
normalizes before ethers sees the entries, so all three shapes are safe here.
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 (what a node returns after filling) marks itself withmorphTxVersion: 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
tois rejected — nodes reject MorphTx contract creation with an authorization list. feeTokenID = 0forbidsfeeLimit— the node reportsillegal extra parameters.- Routing uses
isMorphTx, notisAltFeeTx. A transaction paying gas with ETH (feeTokenID = 0) is a valid MorphTx but is not an Alt Fee transaction. - 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 aBrowserProvider-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 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
This package reads gasLimit, like every other ethers transaction request.
@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 }); // ✓The serializers do not rename fields between libraries on purpose: each adapter consumes its own library's shape, so a mismatch stays visible at the call site instead of being silently guessed. Map explicitly at every cross-package boundary.
API reference
MorphSigner
class MorphSigner {
static from<T extends Signer>(signer: T): T & MorphSigner;
signTransaction(tx: TransactionRequest): Promise<string>;
sendTransaction(tx: TransactionRequest): Promise<TransactionResponse>;
estimateGas(tx: TransactionRequest): Promise<bigint>;
populateTransaction(tx: TransactionRequest): Promise<TransactionRequest>;
}from() returns a Proxy over the wrapped signer: any property/method not
defined on MorphSigner is forwarded to the original signer, so the result is
safe to use anywhere an ethers.Signer is expected. TransactionRequest and
TransactionResponse are both exported types — extending ethers' own types
with Morph's fields (feeTokenID, feeLimit, reference, memo,
authorizationList, morphTxVersion) — so you can annotate your own
variables with them instead of relying on inference.
signAuthorization
function signAuthorization(params: {
signer: Pick<Wallet, "authorize">;
contractAddress: string; // 0x0…0 clears the delegation
chainId?: number | bigint; // defaults to the signer's connected chain; 0 = any chain
nonce: number | bigint; // nonce of the authorizing account
}): Promise<MorphAuthorization>;Wraps wallet.authorize() and returns the flat canonical MorphAuthorization,
ready for authorizationList.
Serialization helpers
function serializeAltFeeTransaction(transaction: SerializableAltFeeTransaction, signature?: Signature): string;
function canonicalRlpInt(value: bigint | number | string | undefined | null): string;
function trim(hexOrBytes: string, opts?: { dir?: "left" | "right" }): string;serializeAltFeeTransaction is the low-level RLP encoder behind
MorphSigner; most callers only need MorphSigner, but it's exported for
building the signing preimage directly (e.g. with a remote signer that only
signs hashes).
RPC / request helpers
function getRpcProvider(provider?: Provider | null): JsonRpcProvider | BrowserProvider;
function getRpcTransaction(tx: TransactionRequest): JsonRpcTransactionRequest;
function copyRequest(req: TransactionRequest): PreparedTransactionRequest;
function toEthersRequest(tx: TransactionRequest): EthersTransactionRequest;Exported for callers building a raw JSON-RPC call (or a custom signer) without
going through MorphSigner: getRpcTransaction builds the
eth_sendTransaction / eth_signTransaction / eth_estimateGas payload
shape for a MorphTx (including chainId / nonce, omitted when absent rather
than defaulted to 0), toEthersRequest strips the Morph-only fields (including the in-memory
morphTxVersion marker) to give a plain ethers request, and copyRequest
returns a type-coerced copy of a
request the way MorphSigner does internally before signing.
Re-exported from @morph-network/chain
This package re-exports all of @morph-network/chain's library-agnostic
primitives, including:
isMorphTx,isAltFeeTx,hasAuthList,resolveMorphTxVersion— classification and envelope-version inference.normalizeAuthorizationList,normalizeAuthorization,toRlpAuthTuples— EIP-7702 authorization normalization and RLP tuple construction.toRlpIntHexand other RLP integer helpers.MorphSdkError/MorphSdkErrorCode— every rejection throws aMorphSdkErrorwith a stable.code(e.g.AUTH_LIST_REQUIRES_MORPH_FIELDS,AUTH_LIST_CANNOT_CREATE,FEE_LIMIT_WITHOUT_TOKEN,AUTH_S_HIGH) that callers can branch on instead of matching message text.MORPH_MAINNET,MORPH_HOODI_TESTNET,MORPH_NETWORKSandgetMorphNetwork.Fee token discovery —
getFeeTokens,resolveFeeToken,getTokenIdByAddress,ethToTokenAmount/tokenToEthAmount,isRegistryFeeToken,getFeeTokenSnapshot/findFeeTokenSnapshot,addressEquals. Pass the provider as the RPC client so the registry is read through ethers:import { JsonRpcProvider, Wallet } from "ethers"; import { MorphSigner, getFeeTokens, ethToTokenAmount, isRegistryFeeToken, } from "@morph-network/ethers"; const provider = new JsonRpcProvider(rpcUrl); const signer = MorphSigner.from(new Wallet(privateKey, provider)); // ethers' provider speaks JSON-RPC directly, so it already satisfies MorphRpcClient. const rpc = { request: <T>({ method, params }: { method: string; params?: unknown }) => provider.send(method, params ?? []) as Promise<T>, }; 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_000n; const maxFeePerGas = 2_000_000_000n; const feeLimit = ethToTokenAmount(usdt, gasLimit * maxFeePerGas); await signer.sendTransaction({ to, gasLimit, maxFeePerGas, maxPriorityFeePerGas: 1_000_000_000n, feeTokenID: usdt.id, feeLimit, });feeLimitis in the token's smallest unit, so it must be converted, not copied from an ETH estimate. Key tokens onid/address, never onsymbol(mainnet has twoBGBand twoUSDC). See the chain package's "Fee tokens" section for the snapshot fallback and error behaviour.
See the @morph-network/chain package for the full list.
