@chriswilder/feerouter
v0.1.0
Published
TypeScript SDK for an optional ERC-7984 FeeRouter: wrap/unwrap take-rate in front of official Zama wrappers.
Maintainers
Readme
@chriswilder/feerouter
TypeScript SDK for an optional FeeRouter that sits in front of official ERC-7984 confidential token wrappers (Zama fhEVM).
This is not part of ERC-7984 and not an official Zama product. The canonical wrap/unwrap path stays 1:1, permissionless, and fee-free. Integrators who want a sustainability take-rate route shield/unshield through their own FeeRouter proxy.
Published package contents are this SDK only (compiled JS, types, ABIs). Solidity sources are not included.
Roles (fairness)
| Who | What they get | What they cannot do |
| --- | --- | --- |
| Integrator | Their proxy address for the app, plus fees paid instantly to the wallet that was listed (feeRecipient) | Pause, unpause, change the fee, upgrade, or admin the proxy |
| Factory owner | All admin: list, deploy, pause, unpause, set fee, remove, upgrade | — |
The integrator wallet is not the owner of the proxy. The factory owns the proxy. That wallet is only the payout address.
When you (factory owner) pause, set fee, or remove someone, you pass their integrator wallet — the same address you listed — not the proxy contract. The factory looks up routerOf(wallet) and talks to that proxy for you.
await factory.pauseRouter("0xIntegratorWallet");
await factory.setRouterFeeBps("0xIntegratorWallet", 10); // 10 bps = 0.1%
await factory.removeIntegrator("0xIntegratorWallet"); // unlist + pauseDo not pass the proxy into those factory calls. The proxy is only what the integrator puts in new FeeRouter({ address: proxy }).
Why this exists
Wallets and apps that integrate confidential tokens still pay for relayers, infrastructure, and ongoing maintenance. ERC-7984 itself does not need to charge a fee.
FeeRouter explores a narrow incentive:
- A small public fee on shield (wrap) and unshield (unwrap) only.
- New proxies start at 0.05% (5 bps). Factory owner may set 0.01%–0.1% (1–10 bps) per proxy. Integrators cannot raise it.
- Those two boundaries already move public underlying amounts, so the fee does not read confidential transfer amounts.
- Confidential transfers stay fee-free.
- Fees go to that integrator’s listed wallet as they happen (no claim step).
- Tokens are not hardcoded. The router validates wrappers against Zama’s official
ConfidentialTokenWrappersRegistry.
Factory admin lists an integrator wallet, then deployFor. That creates their proxy. Give them the proxy for this SDK. One shared implementation sits behind every proxy; upgrades do not change the address the app uses.
What you need
| Item | Where it lives |
| --- | --- |
| Node 20+ | Your machine / CI |
| viem ^2 | Your app (peerDependency) |
| A browser wallet (or any viem walletClient) | User |
| Your FeeRouter proxy | Factory admin ran deployFor(yourWallet). Ask them for that address. |
| Zama Relayer + @zama-fhe/sdk (or @zama-fhe/react-sdk) | Only for unshield encrypt/decrypt. Wrap does not need FHE. |
| Sepolia (current POC network) | chainId 11155111 |
Official Sepolia wrappers registry (already used by the router on-chain):
0x2f0750Bbb0A246059d80e94c454586a7F27a128eInstall:
npm install @chriswilder/feerouter viemIf you unshield, also install Zama’s packages in your app (not this package):
npm install @zama-fhe/sdk @zama-fhe/react-sdkImport
import {
FeeRouter,
FeeRouterFactory,
SEPOLIA_WRAPPERS_REGISTRY,
routerAbi,
extractBurnHandle,
parseDecryptCleartext,
} from "@chriswilder/feerouter";routerAbi / factoryAbi / wrappersRegistryAbi / wrapperAbi / erc20Abi are exported if you prefer raw viem readContract / writeContract.
Construct the client
Use viem publicClient + walletClient from wagmi, or create them yourself. The address must be the integrator proxy, never the implementation.
import { createPublicClient, custom, http } from "viem";
import { sepolia } from "viem/chains";
import { FeeRouter } from "@chriswilder/feerouter";
const publicClient = createPublicClient({
chain: sepolia,
transport: http(),
});
const walletClient = createWalletClient({
chain: sepolia,
transport: custom(window.ethereum),
account: "0xYourUser",
});
const router = new FeeRouter({
address: "0xYourProxyFromFactory", // FEE_ROUTER_ADDRESS
publicClient,
walletClient,
});With wagmi:
import { usePublicClient, useWalletClient } from "wagmi";
import { FeeRouter } from "@chriswilder/feerouter";
const publicClient = usePublicClient();
const { data: walletClient } = useWalletClient();
const router =
publicClient &&
new FeeRouter({
address: import.meta.env.VITE_FEE_ROUTER_ADDRESS,
publicClient,
walletClient: walletClient ?? undefined,
});Put the proxy in env (example Vite):
# .env
VITE_FEE_ROUTER_ADDRESS=0x…Discover tokens
Do not hardcode cUSDC. Prefer listWrapperMeta() so you get on-chain decimals (USDC/USDT are 6; ZAMA, BRON, tGBP, WETH are typically 18 on the underlying):
const tokens = await router.listWrapperMeta();
// wrapper, underlying, symbol, underlyingDecimals, confidentialDecimals, rate
const selected = tokens.find((t) => t.symbol.startsWith("cZAMA")) ?? tokens[0];listWrappers() is the cheaper registry-only call if you do not need decimals yet.
Amounts and decimals
Never assume 6 decimals for every token.
| Side | What to use |
| --- | --- |
| Shield / faucet / underlying balance / spend grant | underlyingDecimals from the ERC-20 |
| Unshield input / encrypted balance | confidentialDecimals (ERC-7984, usually 6) |
| Unshield fee preview | convert confidential → underlying with rate, then quote() |
import { parseTokenAmount, formatTokenAmount } from "@chriswilder/feerouter";
const wrapAmount = parseTokenAmount("10", selected.underlyingDecimals);
const quote = await router.quoteWrap(selected.wrapper, wrapAmount);
const unwrapConfidential = parseTokenAmount("1", selected.confidentialDecimals);
const grossUnderlying = unwrapConfidential * selected.rate;
const unshieldQuote = await router.quote(grossUnderlying);
formatTokenAmount(quote.net, selected.underlyingDecimals);confidentialAmountToUnderlying(wrapper, amount) does the * rate step for you.
Shield (wrap)
Two wallet steps after the user picks a wrapper and an amount in underlying units:
approveUnderlying— ERC-20approveof the underlying to the proxy.grantSpend— timed allowance on the router (untilis a unix timestamp, max 30 days).wrap— router pulls underlying, takes the public fee, wraps the rest into the confidential token.
const wrapper = selected.wrapper;
const amount = parseTokenAmount("10", selected.underlyingDecimals);
const until = Math.floor(Date.now() / 1000) + 24 * 60 * 60;
const quote = await router.quoteWrap(wrapper, amount);
// quote.fee / quote.net are underlying wei — format with selected.underlyingDecimals
const approveHash = await router.approveUnderlying(wrapper, amount);
await publicClient.waitForTransactionReceipt({ hash: approveHash });
const grantHash = await router.grantSpend(wrapper, amount, until);
await publicClient.waitForTransactionReceipt({ hash: grantHash });
const wrapHash = await router.wrap(wrapper, userAddress, amount);
await publicClient.waitForTransactionReceipt({ hash: wrapHash });revokeSpend(wrapper) clears the router spend window. ERC-20 allowance may still exist until you approve(0).
Unshield (unwrap)
Unshield uses Zama to encrypt the confidential amount, then this SDK to burn via the router (payout mailbox / sink is created inside unwrap).
- Encrypt with
@zama-fhe/sdk/useEncrypttargeting the wrapper contract (not the FeeRouter). - Ensure the FeeRouter mailbox (
ensureSinkif needed), then your wallet calls wrapperunwrap(from, sink, handle, inputProof)— notFeeRouter.unwrap(that would make the proxy the caller and revert). - Read the burn handle from the wrapper logs (
extractBurnHandle). - Public-decrypt that handle with Zama (
useDecryptPublicValues). router.finalizeUnwrap(wrapper, handle, cleartext, proof)— fee is taken in public underlying; net is sent to the user.
FeeRouter.unwrap() in this SDK already does steps 2 for you (ensureSink + wrapper.unwrap).
import { extractBurnHandle, parseDecryptCleartext } from "@chriswilder/feerouter";
const encrypted = await encrypt({
contractAddress: wrapper,
userAddress,
values: [{ value: amount, type: "euint64" }],
});
const handle = encrypted.encryptedValues?.[0] ?? encrypted.handles?.[0];
const inputProof = encrypted.inputProof;
const unwrapHash = await router.unwrap(wrapper, userAddress, handle, inputProof);
const receipt = await publicClient.waitForTransactionReceipt({ hash: unwrapHash });
const burn = extractBurnHandle(receipt.logs, wrapper);
const decrypted = await decryptPublicValues([burn]);
const parsed = parseDecryptCleartext(decrypted, burn);
const finHash = await router.finalizeUnwrap(
wrapper,
burn,
parsed.cleartext,
parsed.proof
);Configure Zama relayerUrl / chain the same way you would for any ERC-7984 app (RelayerWeb HTTP base ending in /v2). This package does not bundle the relayer.
Resume pending unshield
Same idea as Zama’s savePendingUnshield / resumeUnshield, but keyed by FeeRouter proxy + wrapper + user. Always finalize through FeeRouter, never only on the wrapper (otherwise fees never run and payout may sit in the mailbox).
import {
savePendingUnshield,
loadPendingUnshield,
updatePendingUnshieldProof,
clearPendingUnshield,
extractBurnHandle,
parseDecryptCleartext,
} from "@chriswilder/feerouter";
// After FeeRouter.unwrap receipt:
const burn = extractBurnHandle(receipt.logs, wrapper);
await savePendingUnshield({
router: feeRouterProxy,
wrapper,
user: userAddress,
unwrapTxHash: unwrapHash,
handle: burn,
});
// After public decrypt:
await updatePendingUnshieldProof(feeRouterProxy, wrapper, userAddress, cleartext, proof);
// On app load / refresh:
const pending = await loadPendingUnshield(feeRouterProxy, wrapper, userAddress);
if (pending) {
// decrypt if cleartext/proof missing, then:
await router.finalizeUnwrap(wrapper, pending.handle, cleartext, proof);
await clearPendingUnshield(feeRouterProxy, wrapper, userAddress);
}Storage is IndexedDB (browser), same approach as Zama’s pending unshield. Integrators can wrap the same helpers for auto-sign wallets.
Resolve a proxy from the factory
If you know the integrator wallet and the factory:
import { FeeRouterFactory } from "@chriswilder/feerouter";
const factory = new FeeRouterFactory({
address: "0xFactory",
publicClient,
walletClient, // required for admin writes
});
const proxy = await factory.routerOf("0xIntegratorWallet");Integrator apps only use FeeRouter with that proxy. They never need the factory.
Factory owner (admin wallet) uses FeeRouterFactory:
| Call | Argument | Effect |
| --- | --- | --- |
| listIntegrator(wallet) | Integrator wallet | Allow a proxy to be created |
| deployFor(wallet) | Integrator wallet | Deploy their proxy; they are fee recipient only |
| pauseRouter / unpauseRouter | Integrator wallet | Factory finds the proxy and pauses it |
| setRouterFeeBps(wallet, bps) | Integrator wallet + 1–10 | Change that proxy’s fee |
| pauseAllRouters / setFeeBpsAll | — | Every proxy this factory deployed |
| removeIntegrator(wallet) | Integrator wallet | Unlist + pause their proxy |
Sepolia factory (current): 0xe8F00EC75BB7Ef8d79b580CdE828854A05e12383.
API (FeeRouter)
| Method | Kind |
| --- | --- |
| listWrapperMeta() | Registry pairs + decimals + rate |
| listWrappers() | Registry pairs only |
| underlyingDecimals / confidentialDecimals / rate | Per-token scale |
| parseTokenAmount / formatTokenAmount | Human ↔ wei (exported helpers) |
| quote(amount) | Fee on underlying wei |
| quoteWrap(wrapper, amount) | Shield preview (amount is underlying wei) |
| approveUnderlying / grantSpend / revokeSpend / wrap | Shield |
| unwrap / finalizeUnwrap / ensureSink | Unshield |
Independent POC
Live case-study UI: fee-router-poc.netlify.app
