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

effect-monetization

v0.6.0

Published

Charge for Effect HttpApi endpoints, MCP tools and plain Requests over MPP and x402

Downloads

1,283

Readme

effect-monetization

CI

Charge for Effect HttpApi endpoints, MCP tools and plain Requests over MPP (the Machine Payments Protocol) and x402. Provide a layer per protocol; an unpaid call is answered with every protocol's challenge at once, and the payer uses whichever it speaks. Effect v4.

bun add effect-monetization effect
bun add mppx viem   # for MPP

Rails

Monetization.layer holds the payment rails an app accepts (MPP, x402). Each rail's layer opens it; leave one out and the app doesn't offer it.

import { Config, Layer } from "effect"
import { FetchHttpClient } from "effect/http"
import { Monetization } from "effect-monetization"
import { Mpp } from "effect-monetization/mpp"
import { X402 } from "effect-monetization/x402"
import { tempo } from "mppx/server"

const Payments = Layer.mergeAll(
  Mpp.layer({ methods: [tempo.charge({ recipient: "0x…" })], secretKey: Config.Redacted("MPP_SECRET_KEY") }),
  X402.layer({ recipient: "0x…", network: "eip155:8453", facilitator: { url: "https://…" } }).pipe(
    Layer.provide(FetchHttpClient.layer)
  )
).pipe(Layer.provideMerge(Monetization.layer))
  • Mpp.layer takes the options of mppx's Mppx.create, except that secretKey is a Redacted or a Config of one. Its methods are mppx's: tempo.charge for a Tempo wallet, stripe.charge for a card or Link wallet paying by a Stripe Shared Payment Token.
  • X402.layer charges a network's dollar stablecoin (USDC on most) by x402's exact scheme on an EVM chain. It needs no x402 package: the facilitator verifies and settles over Effect's HttpClient, so provide one (FetchHttpClient.layer).
  • For a facilitator that needs credentials (Coinbase CDP's, for Base mainnet), facilitator.headers is an Effect of each call's headers: (operation) => Effect.succeed({ authorization: "Bearer …" }). e2e/cdp.ts shows CDP's: its URL and the JWT it wants signed for each call.

Prices

A price is in US dollars, and each rail charges it in its own dollar stablecoin:

const price: Price = { amount: "0.002", description: "One render", externalId: "order_1", expires, meta }

MPP binds externalId, expires and meta into its challenge. x402 has nowhere to put them, so it charges the amount only.

An MPP method that costs more to settle can have its own amount (and description), keyed by mppx's "<name>/<intent>". Here a card pays $51.45, and a Tempo wallet or x402 pays $49.95:

import { Paid, type Price } from "effect-monetization"
import { Mpp } from "effect-monetization/mpp"
import { stripe, tempo } from "mppx/server"

const methods = [
  tempo.charge({ recipient: "0x…" }),
  stripe.charge({
    secretKey: "sk_…",
    networkId: "profile_…",
    paymentMethodTypes: ["card", "link"],
    currency: "usd",
    decimals: 2
  })
]

const Payments = Mpp.layer({ methods, secretKey }).pipe(Layer.provideMerge(Monetization.layer))

// Typed by the methods, so a misspelt key doesn't compile.
const price: Price<Mpp.MethodKey<typeof methods>> = {
  amount: "49.95",
  methods: { "stripe/charge": { amount: "51.45", description: "Order, by card" } }
}

// In the paid handler:
const paid = yield* Paid
paid.method // "stripe", "tempo", or "x402" on the x402 rail

Each method's challenge carries its own amount, and a credential is verified at the amount of the method it pays with. A method's canOffer (Stripe's minimum charge) sees its own amount, so a method under its minimum is left out and the rest are still offered. An amount for a method the rail doesn't have is ignored, so one price serves an environment without that method.

Shared Payment Tokens

stripe.charge is paid by a Stripe Shared Payment Token (SPT): the payer's wallet (Link, through link-cli mpp pay, or any agent that issues SPTs) grants your Stripe profile a token for the challenge's amount and sends it as the credential. Settling it creates a PaymentIntent, whose id is Paid.reference; Paid.payer is null, since an SPT doesn't name its payer.

  • networkId is your Stripe profile's id, which the payer grants the token to: profile_…, or profile_test_… in a sandbox.
  • paymentMethodTypes are what the token may be funded by: "card", "link".
  • SPTs are a Stripe preview, so the account needs access to them.

HttpApi endpoints

Put a price on an endpoint with the Charge annotation and add the Payment middleware.

import { Charge, Payment } from "effect-monetization/http-api"

const Api = HttpApi.make("api")
  .add(
    HttpApiGroup.make("tools").add(
      HttpApiEndpoint.post("render", "/render", { success: Schema.String }).annotate(Charge, { amount: "0.002" })
    )
  )
  .middleware(Payment)

const ApiLive = HttpApiBuilder.layer(Api).pipe(
  Layer.provide(ToolsLive),
  Layer.provide(Payment.layer),
  Layer.provide(Payments)
)

Endpoints without Charge pass through. A request without a credential gets a 402 PaymentRequired: MPP's challenges in WWW-Authenticate, x402's in PAYMENT-REQUIRED, and both in the JSON body's data.

Payment takes the payment before the handler runs:

  1. Without a valid credential the handler doesn't run: a 402 with fresh challenges and, for a refused credential, the reason.
  2. The payment is settled. A failure that isn't the payer's (an RPC error, say) is a 5xx.
  3. The handler runs and reads the payment as Paid. Its reference is the transaction, payer the paying address and method what paid: mppx's method name (such as "tempo" or "stripe"), or "x402" on x402.
  4. The response carries the receipt (Payment-Receipt or PAYMENT-RESPONSE), whatever the handler answered.

The client pays even if the handler then fails, so a paid handler should fail rarely and refund when it does.

MppOpenApi.annotate(Api, { methods }) from effect-monetization/mpp-openapi documents MPP's x-payment-info and the 402 on every priced operation.

MCP tools

paywall is McpServer middleware. It works the price out from the call and, like Payment, takes the payment before the handler runs:

import { Paid } from "effect-monetization"
import { paywall } from "effect-monetization/mcp"

const OrderPaywall = paywall(({ payload }) =>
  Effect.succeed(Option.map(Schema.decodeUnknownOption(OrderCall)(payload), (call) => priceOf(call.arguments)))
)

// Provide OrderPaywall.layer to the tool's registration; in its handler:
const paid = yield* Effect.serviceOption(Paid) // None when the call wasn't priced
return McpSchema.CallToolResult.make({ content, _meta: paid.value.meta })

An unpaid call fails with JSON-RPC error -32042 (-32043 when its MPP credential was refused), as MPP's MCP transport has it. Its error data is { httpStatus: 402, challenges, x402 }: MPP's challenges and x402's PaymentRequired. A refused x402 payment is answered as x402's MCP transport has it: a tool result with isError, its PaymentRequired (the reason in error) as structuredContent and as JSON text. Both are what mppx's own MPP-and-x402 server sends, and both mppx's and x402's MCP clients pay them.

Credentials come in _meta["x402/payment"] or _meta["org.paymentauth/credential"]; receipt.meta holds the matching receipt key for the result's _meta.

Returning None from the price function charges nothing and runs the handler, so a call that shouldn't be paid for (bad arguments, something already bought) gets the handler's own answer.

Settling after the work

For work that should be paid for only if it succeeds, pass { settleAfter: true }. The payment is verified before the handler runs and taken only when the handler settles it:

import { Verified } from "effect-monetization"

const MintPaywall = paywall(priceOfCall, { settleAfter: true })

// In the handler:
const verified = yield* Verified
const art = yield* render // fails: answer isError without settling, and nothing is charged
const receipt = yield* verified.settle
return McpSchema.CallToolResult.make({ content: art, _meta: receipt.meta })

A handler that answers isError without settling charges nothing; one that answers otherwise without settling is a defect. A settle the rail refuses (a credential spent elsewhere meanwhile, a card declined) answers the call as unpaid, with fresh challenges.

Verifying changes no payment state: x402 asks the facilitator's /verify and settle its /settle; MPP validates with mppx's validateCredential, which writes no replay marker and broadcasts nothing, and settle broadcasts. A method mppx can't validate without paying (Stripe's SPT) is only decoded and schema-checked before settle, which charges it.

Plain Requests

For a route you dispatch yourself:

import { challenge, pay, stamp } from "effect-monetization/fetch"

const response = yield* pay(price, request).pipe(
  Effect.map((receipt) => stamp(Response.json({ paid: receipt.reference }), receipt)),
  Effect.catchTag("PaymentRequired", (error) => Effect.succeed(challenge(error)))
)

pay takes the payment before your work, as the other adapters do; challenge is the 402 for a request that didn't pay.

verify checks the payment without taking it, for work paid for only if it succeeds:

const verified = yield* verify(price, request)
const body = yield* work // fails: nothing is charged
const receipt = yield* verified.settle // a refusal here is a PaymentRequired: answer its challenge
return stamp(new Response(body), receipt)

Notes

  • Runs on Workers, Bun and Node. mppx's server imports node:util, so Cloudflare Workers need the nodejs_compat flag.
  • examples/server.ts serves all three adapters over both rails on testnets.
  • bun run e2e pays that example for real, on Tempo's testnet and Base Sepolia, and writes each transaction to .e2e/summary.md. x402 is settled by x402.org's facilitator and once by Coinbase CDP's, and MPP's Stripe method is paid once in Stripe's test mode, by an SPT for a test card. It reads the x402 payer's key, a CDP API key and a Stripe test-mode secret key from 1Password (.env.e2e); that wallet needs Base Sepolia USDC from https://faucet.circle.com.

License

MIT