|
| 1 | +--- |
| 2 | +title: 'Machine Payments Protocol (MPP)' |
| 3 | +description: This quickstart shows you how to implement the Machine Payments Protocol (MPP) on Arbitrum. |
| 4 | +author: pete-vielhaber |
| 5 | +sme: EmreDincoglu |
| 6 | +user_story: As a developer, I want to understand how to implement the Machine Payments Protocol (MPP) on Arbitrum. |
| 7 | +content_type: quickstart |
| 8 | +displayed_sidebar: buildAppsSidebar |
| 9 | +--- |
| 10 | + |
| 11 | +This quickstart will guide you through implementing an Arbitrum-specific payment method plugin for the `mppx` library, which implements the Machine Payments Protocol (MPP). MPP defines a generic **challenge → credential → settlement** flow for payments between two parties: |
| 12 | + |
| 13 | +- **Server**: the merchant/payee (the one that wants to get paid) |
| 14 | +- **Client**: the payer (a user or AI agent) |
| 15 | + |
| 16 | +`mppx` itself is payment-method-agnostic. This plugin provides methods for settling payments on Arbitrum One or Arbitrum Sepolia with **ERC-20** stablecoins (currently **USDC**) through [EIP-3009](https://eips.ethereum.org/EIPS/eip-3009) `authorization`, and with almost any **ERC-20** via `permit2`. |
| 17 | + |
| 18 | +## Core concepts |
| 19 | + |
| 20 | +The client (payer) never broadcasts a transaction and never pays gas. |
| 21 | + |
| 22 | +1. The merchant requests payment (issues a challenge). |
| 23 | +2. The payer signs an EIP-712 typed-data authorization offchain—no gas, no prior onchain approval is needed. |
| 24 | +3. The merchant's server submits the signature onchain, completing the fund transfer. The merchant pays for the gas. |
| 25 | + |
| 26 | +This is exactly the "402 Payment Required" flow you'd want for machine/agent commerce: an HTTP request hits a paywalled endpoint, the agent signs a payment authorization, and the server settles it atomically before serving the response. |
| 27 | + |
| 28 | +It supports two settlement mechanisms: |
| 29 | + |
| 30 | +| Type | Onchain mechanism | Supports splits? | Need prior approval? | |
| 31 | +| ------------- | --------------------------------------------------- | ----------------------------------------------- | --------------------------------------------------- | |
| 32 | +| authorization | EIP-3009 transferWithAuthorization (native to USDC) | ❌ | ❌ | |
| 33 | +| permit2 | Uniswap's Permit2 permitWitnessTransferFrom | ✅ (pay multiple recipients in one transaction) | ✅ payer must pre-approve Permit2 on the token once | |
| 34 | + |
| 35 | +:::warning Other options |
| 36 | + |
| 37 | +`transaction` and `hash` credential types are stubbed but intentionally not implemented—these have weaker challenge-binding and carry fraud risk. |
| 38 | + |
| 39 | +::: |
| 40 | + |
| 41 | +<ImageZoom src="/img/mpp.png" className="img-600px" alt="MPP Flow"> |
| 42 | + MPP Flow |
| 43 | +</ImageZoom> |
| 44 | + |
| 45 | +## What the client does |
| 46 | + |
| 47 | +`charge()` returns a `Method.toClient` handler. In `createCredential`: |
| 48 | + |
| 49 | +1. Validates the challenge’s `chainId` is supported and unexpired. |
| 50 | +2. Checks the payer’s token balance onchain (`balanceOf`). |
| 51 | +3. Branches on `credentialTypes`: |
| 52 | + |
| 53 | +- **permit2** (or undefined): builds permitted/`transferDetails` arrays (handling splits, with the primary recipient pushed to the front), derives the nonce from a challenge hash, and signs the Permit2 witness typed-data. |
| 54 | + |
| 55 | +<VanillaAdmonition type="info" title="permit2 splits"> |
| 56 | + The sum of the amounts in the split must be strictly lower than the total amount for the transaction. So if the total transaction is 10,000 and splits have two recipients that will receive 2,000 and 3,000—the main recipient will receive 5,000. |
| 57 | +</VanillaAdmonition> |
| 58 | + |
| 59 | +- **authorization**: derives nonce = `keccak256(challenge.id, challenge.realm)` for challenge-binding (anti-replay), looks up the token's EIP-712 domain from the local erc3009Tokens registry (not an onchain query), and signs the `TransferWithAuthorization` struct. |
| 60 | + |
| 61 | +4. Returns `Credential.serialize(...)`. No transaction is broadcast. |
| 62 | + |
| 63 | +## What the server does |
| 64 | + |
| 65 | +`charge()` returns a `Method.toServer` handler. In `verify(credential, request)`, it independently re-derives and re-checks every value the client claimed (recipient, amount, deadline, nonce/challenge-hash, signature via `verifyTypedData`, `balance`, and, for permit2, the Permit2 allowance and split amounts). Then it: |
| 66 | + |
| 67 | +1. Simulates the transaction with `eth_call` (so a bad credential doesn’t waste gas). |
| 68 | +2. Submits `transferWithAuthorization` (authorization) or `permitWitnessTransferFrom` (permit2) from the merchant’s account. |
| 69 | +3. `waitForTransactionReceipt`, then verifies the emitted Transfer logs match the expected recipients/amounts. |
| 70 | +4. Returns an `mppx` Receipt: `method: "arbitrum", status: "success", timestamp, reference: txHash`. |
| 71 | + |
| 72 | +## How to implement it — server (merchant) side |
| 73 | + |
| 74 | +`mppx` has an Express adapter: |
| 75 | + |
| 76 | +```typescript |
| 77 | +import express from 'express'; |
| 78 | +import { Mppx } from 'mppx/express'; |
| 79 | +import { privateKeyToAccount } from 'viem/accounts'; |
| 80 | +import { charge } from '@arbitrum/mpp/server'; |
| 81 | +import * as defaults from '@arbitrum/mpp/default'; |
| 82 | + |
| 83 | +const account = privateKeyToAccount(process.env.SERVER_PRIVATE_KEY as `0x${string}`); |
| 84 | +const app = express(); |
| 85 | + |
| 86 | +const mppx = Mppx.create({ |
| 87 | + methods: [ |
| 88 | + charge({ |
| 89 | + recipient: account.address, // where funds land |
| 90 | + currency: defaults.TOKEN_CONTRACTS.USDC_ARBITRUM_SEPOLIA, // which token |
| 91 | + methodDetails: { chainId: 421614, decimals: 6 }, |
| 92 | + account, // pays gas to settle |
| 93 | + }), |
| 94 | + ], |
| 95 | + secretKey: process.env.SERVER_PRIVATE_KEY, |
| 96 | +}); |
| 97 | + |
| 98 | +// Gate an endpoint behind a charge: |
| 99 | +app.get( |
| 100 | + '/authorization', |
| 101 | + mppx.charge({ |
| 102 | + amount: '1000', // raw units: 1000 = 0.001 USDC (6 decimals) |
| 103 | + description: 'My favorite food', |
| 104 | + methodDetails: { chainId: 421614, credentialTypes: ['authorization'] }, |
| 105 | + }), |
| 106 | + (req, res) => res.json({ data: 'authorization worked!' }), // only runs after payment settles |
| 107 | +); |
| 108 | + |
| 109 | +app.listen(3000); |
| 110 | +``` |
| 111 | + |
| 112 | +- Set `credentialTypes` to `['permit2']` to use Permit2 instead, and add a `splits: [...]` array to pay multiple recipients in one transaction. |
| 113 | +- ⚠️ `amount` uses raw token units — human-readable decimal conversion isn't supported yet. |
| 114 | + |
| 115 | +## How to implement it - client (payer) side |
| 116 | + |
| 117 | +```typescript |
| 118 | +import { Mppx } from 'mppx/client'; |
| 119 | +import { privateKeyToAccount } from 'viem/accounts'; |
| 120 | +import { charge } from '@arbitrum/mpp/client'; |
| 121 | + |
| 122 | +const account = privateKeyToAccount(process.env.CLIENT_PRIVATE_KEY as `0x${string}`); |
| 123 | + |
| 124 | +const mppx = Mppx.create({ |
| 125 | + methods: [charge({ account, chainId: 421614 })], |
| 126 | +}); |
| 127 | + |
| 128 | +// mppx intercepts the 402, signs the challenge, retries automatically: |
| 129 | +const response = await mppx.fetch('http://localhost:3000/authorization'); |
| 130 | +const data = await response.json(); |
| 131 | +console.log(`Response: ${data}`); // Payment response ('authorization worked!') |
| 132 | +const receipt = response.headers.get('payment-receipt'); // base64-encoded mppx Receipt |
| 133 | +console.log(Buffer.from(receipt!, 'base64').toString('binary')); // Transaction information including hash |
| 134 | +``` |
| 135 | + |
| 136 | +## Run the bundled example locally |
| 137 | + |
| 138 | +```shell |
| 139 | +pnpm install |
| 140 | + |
| 141 | +# .env (copy from .env.example) |
| 142 | +CLIENT_PRIVATE_KEY=0x... # this wallet needs USDC on Arbitrum Sepolia |
| 143 | +SERVER_PRIVATE_KEY=0x... # this wallet needs ETH (gas) on Arbitrum Sepolia |
| 144 | + |
| 145 | +# Terminal 1 |
| 146 | +pnpm run server # tsx test/server → listens on :3000 |
| 147 | + |
| 148 | +# Terminal 2 |
| 149 | +pnpm run client # tsx test/client → hits /authorization, signs, settles |
| 150 | +``` |
| 151 | + |
| 152 | +### Funding requirements |
| 153 | + |
| 154 | +- Server needs **ETH** on the chain (it pays gas to submit the settlement transaction). |
| 155 | +- Client needs **USDC** on the same chain (the funds being pulled). |
| 156 | +- For Permit2, the client must first approve the Permit2 contract (`0x000000000022D473030F116dDEE9F6B43aC78BA3`) as a spender on the **USDC** token—Permit2 can’t move tokens it hasn’t been allowed to. |
| 157 | + |
| 158 | +### Current limitations |
| 159 | + |
| 160 | +- Only **USDC** on Arbitrum One/Sepolia is registered. To add a token, register its address and EIP-712 name/version/chainId. |
| 161 | +- `amount` is raw units only—no human-readable decimal conversion yet. |
| 162 | +- For authorization, the `validBefore` expiry is trusted from the server's challenge; a far-future expiry theoretically widens the window in which an unsubmitted authorization could be settled late. (**Note**: the EIP-3009 nonce is challenge-bound—`keccak256(id, realm)`—and single-use onchain, so a literal replay of an already-settled authorization is blocked once the nonce is consumed.) |
| 163 | +- `transaction` and `hash` credential types are intentionally unimplemented (weak challenge-binding). |
| 164 | +- Status is v0.1.0 — early/experimental. |
| 165 | + |
| 166 | +### Reference links |
| 167 | + |
| 168 | +- [Protocol overview](https://mpp.dev/protocol) |
| 169 | +- [Custom/first-party SDK](https://mpp.dev/payment-methods/custom#first-party-sdk) |
| 170 | +- [Method.from](https://mpp.dev/sdk/typescript/Method.from) |
| 171 | +- [Method.toServer](https://mpp.dev/sdk/typescript/core/Method.toServer) |
| 172 | +- [Method.toClient](https://mpp.dev/sdk/typescript/core/Method.toClient) |
| 173 | +- [Unified EVM Spec](https://github.com/tempoxyz/mpp-specs/blob/main/specs/methods/evm/draft-evm-charge-00.md) |
| 174 | +- [EIP-3009 Transfer with Authorization](https://eips.ethereum.org/EIPS/eip-3009) |
0 commit comments