Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-cooks-smile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'mppx': patch
---
Comment on lines +1 to +3
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unless this is a breaking change, would use patch since we are pre-v1

Suggested change
---
'mppx': minor
---
---
'mppx': patch
---

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍


Added split-payment support to Tempo charge requests, including client transaction construction and stricter server verification for split transfers.
71 changes: 71 additions & 0 deletions src/server/Mppx.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1567,6 +1567,77 @@ describe('cross-route credential replay via scope binding flaw', () => {
// The result should be 200 (matched to cheap), not routed to expensive.
expect(result.status).toBe(200)
})

test('rejects no-splits credential replayed at splits route', async () => {
// Method whose schema transform moves splits into methodDetails.
const splitsMethod = Method.from({
name: 'mock',
intent: 'charge',
schema: {
credential: { payload: z.object({ token: z.string() }) },
request: z.pipe(
z.object({
amount: z.string(),
currency: z.string(),
decimals: z.number(),
recipient: z.string(),
splits: z.optional(z.array(z.object({ amount: z.string(), recipient: z.string() }))),
}),
z.transform(({ amount, currency, decimals, recipient, splits }) => ({
methodDetails: {
amount: String(Number(amount) * 10 ** decimals),
currency,
recipient,
...(splits && { splits }),
},
})),
),
},
})

const splitsServerMethod = Method.toServer(splitsMethod, {
async verify() {
return mockReceipt()
},
})

const handler = Mppx.create({ methods: [splitsServerMethod], realm, secretKey })

// Get a challenge from a route with no splits
const noSplitsHandle = handler.charge({
amount: '1',
currency: '0x0000000000000000000000000000000000000001',
decimals: 6,
expires: new Date(Date.now() + 60_000).toISOString(),
recipient: '0x0000000000000000000000000000000000000002',
})
const noSplitsResult = await noSplitsHandle(new Request('https://example.com/no-splits'))
expect(noSplitsResult.status).toBe(402)
if (noSplitsResult.status !== 402) throw new Error()

const noSplitsChallenge = Challenge.fromResponse(noSplitsResult.challenge)
const credential = Credential.from({
challenge: noSplitsChallenge,
payload: { token: 'valid' },
})

// Present at a route that requires splits
const splitsHandle = handler.charge({
amount: '1',
currency: '0x0000000000000000000000000000000000000001',
decimals: 6,
expires: new Date(Date.now() + 60_000).toISOString(),
recipient: '0x0000000000000000000000000000000000000002',
splits: [{ amount: '0.2', recipient: '0x0000000000000000000000000000000000000003' }],
})
const result = await splitsHandle(
new Request('https://example.com/with-splits', {
headers: { Authorization: Credential.serialize(credential) },
}),
)

expect(result.status).toBe(402)
})
})

describe('withReceipt', () => {
Expand Down
23 changes: 23 additions & 0 deletions src/server/Mppx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,29 @@ function createMethodFn(parameters: createMethodFn.Parameters): createMethodFn.R
return { challenge: response, status: 402 }
}
}

// Compare payment-relevant methodDetails fields (memo, splits).
// These are excluded from the top-level field check above but
// affect verification semantics — a credential issued for a
// no-splits route must not be accepted on a splits route.
for (const field of ['memo', 'splits'] as const) {
const routeVal = routeDetails[field]
const echoedVal = echoedDetails[field]
if (
routeVal !== undefined &&
JSON.stringify(routeVal) !== JSON.stringify(echoedVal)
) {
const response = await transport.respondChallenge({
challenge,
input,
error: new Errors.InvalidChallengeError({
id: credential.challenge.id,
reason: `credential ${field} does not match this route's requirements`,
}),
})
return { challenge: response, status: 402 }
}
}
}
}

Expand Down
79 changes: 79 additions & 0 deletions src/tempo/Methods.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,85 @@ describe('charge', () => {
expect(result.success).toBe(true)
})

test('schema: validates request with splits', () => {
const result = Methods.charge.schema.request.safeParse({
amount: '1',
currency: '0x20c0000000000000000000000000000000000001',
decimals: 6,
recipient: '0x1234567890abcdef1234567890abcdef12345678',
splits: [
{
amount: '0.25',
recipient: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
},
{
amount: '0.1',
memo: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
recipient: '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
},
],
})
expect(result.success).toBe(true)
if (!result.success) return

expect(result.data.methodDetails?.splits).toEqual([
{
amount: '250000',
recipient: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
},
{
amount: '100000',
memo: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
recipient: '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
},
])
})

test('schema: rejects empty splits', () => {
const result = Methods.charge.schema.request.safeParse({
amount: '1',
currency: '0x20c0000000000000000000000000000000000001',
decimals: 6,
recipient: '0x1234567890abcdef1234567890abcdef12345678',
splits: [],
})
expect(result.success).toBe(false)
})

test('schema: rejects more than 10 splits', () => {
const result = Methods.charge.schema.request.safeParse({
amount: '11',
currency: '0x20c0000000000000000000000000000000000001',
decimals: 6,
recipient: '0x1234567890abcdef1234567890abcdef12345678',
splits: Array.from({ length: 11 }, (_, index) => ({
amount: '0.1',
recipient: `0x${(index + 1).toString(16).padStart(40, '0')}`,
})),
})
expect(result.success).toBe(false)
})

test('schema: rejects split totals greater than or equal to amount', () => {
const result = Methods.charge.schema.request.safeParse({
amount: '1',
currency: '0x20c0000000000000000000000000000000000001',
decimals: 6,
recipient: '0x1234567890abcdef1234567890abcdef12345678',
splits: [
{
amount: '0.5',
recipient: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
},
{
amount: '0.5',
recipient: '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
},
],
})
expect(result.success).toBe(false)
})

test('schema: rejects invalid request', () => {
const result = Methods.charge.schema.request.safeParse({
amount: '1',
Expand Down
70 changes: 53 additions & 17 deletions src/tempo/Methods.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import type { Account } from 'viem'
import type { Account, Address } from 'viem'
import { parseUnits } from 'viem'

import * as Method from '../Method.js'
import * as z from '../zod.js'

const split = z.object({
amount: z.amount(),
memo: z.optional(z.hash()),
recipient: z.pipe(
z.string(),
z.transform((v) => v as Address),
),
})

/**
* Tempo charge intent for one-time TIP-20 token transfers.
*
Expand All @@ -20,31 +29,58 @@ export const charge = Method.from({
]),
},
request: z.pipe(
z.object({
amount: z.amount(),
chainId: z.optional(z.number()),
currency: z.string(),
decimals: z.number(),
description: z.optional(z.string()),
externalId: z.optional(z.string()),
feePayer: z.optional(
z.pipe(
z.union([z.boolean(), z.custom<Account>()]),
z.transform((v): boolean => (typeof v === 'object' ? true : v)),
z
.object({
amount: z.amount(),
chainId: z.optional(z.number()),
currency: z.string(),
decimals: z.number(),
description: z.optional(z.string()),
externalId: z.optional(z.string()),
feePayer: z.optional(
z.pipe(
z.union([z.boolean(), z.custom<Account>()]),
z.transform((v): boolean => (typeof v === 'object' ? true : v)),
),
),
memo: z.optional(z.hash()),
recipient: z.optional(z.string()),
splits: z.optional(z.array(split).check(z.minLength(1), z.maxLength(10))),
})
.check(
z.refine(({ amount, decimals, splits }) => {
if (!splits) return true

const totalAmount = parseUnits(amount, decimals)
const splitTotal = splits.reduce(
(sum, split) => sum + parseUnits(split.amount, decimals),
0n,
)

return (
splits.every((split) => parseUnits(split.amount, decimals) > 0n) &&
splitTotal < totalAmount
)
}, 'Invalid splits'),
),
memo: z.optional(z.hash()),
recipient: z.optional(z.string()),
}),
z.transform(({ amount, chainId, decimals, feePayer, memo, ...rest }) => ({
z.transform(({ amount, chainId, decimals, feePayer, memo, splits, ...rest }) => ({
...rest,
amount: parseUnits(amount, decimals).toString(),
...(chainId !== undefined || feePayer !== undefined || memo !== undefined
...(chainId !== undefined ||
feePayer !== undefined ||
memo !== undefined ||
splits !== undefined
? {
methodDetails: {
...(chainId !== undefined && { chainId }),
...(feePayer !== undefined && { feePayer }),
...(memo !== undefined && { memo }),
...(splits !== undefined && {
splits: splits.map((split) => ({
...split,
amount: parseUnits(split.amount, decimals).toString(),
})),
}),
},
}
: {}),
Expand Down
49 changes: 41 additions & 8 deletions src/tempo/client/Charge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import * as Client from '../../viem/Client.js'
import * as z from '../../zod.js'
import * as Attribution from '../Attribution.js'
import * as AutoSwap from '../internal/auto-swap.js'
import * as Charge_internal from '../internal/charge.js'
import * as defaults from '../internal/defaults.js'
import * as Methods from '../Methods.js'

Expand Down Expand Up @@ -54,18 +55,37 @@ export function charge(parameters: charge.Parameters = {}) {
const { request } = challenge
const { amount, methodDetails } = request
const currency = request.currency as Address
const recipient = request.recipient as Address

if (parameters.expectedRecipients) {
const allowed = new Set(parameters.expectedRecipients.map((a) => a.toLowerCase()))
const splits = methodDetails?.splits as readonly { recipient: string }[] | undefined
if (splits) {
for (const split of splits) {
if (!allowed.has(split.recipient.toLowerCase()))
throw new Error(`Unexpected split recipient: ${split.recipient}`)
}
}
}

const memo = methodDetails?.memo
? (methodDetails.memo as Hex.Hex)
: Attribution.encode({ serverId: challenge.realm, clientId })

const transferCall = Actions.token.transfer.call({
amount: BigInt(amount),
memo,
to: recipient,
token: currency,
const transfers = Charge_internal.getTransfers({
amount,
methodDetails: {
...methodDetails,
memo,
},
recipient: request.recipient as Address,
})
const transferCalls = transfers.map((transfer) =>
Actions.token.transfer.call({
amount: BigInt(transfer.amount),
...(transfer.memo && { memo: transfer.memo as Hex.Hex }),
to: transfer.recipient as Address,
token: currency,
}),
)

const autoSwap = AutoSwap.resolve(
context?.autoSwap ?? parameters.autoSwap,
Expand All @@ -82,7 +102,14 @@ export function charge(parameters: charge.Parameters = {}) {
})
: undefined

const calls = [...(swapCalls ?? []), transferCall]
const calls = [...(swapCalls ?? []), ...transferCalls]

const validBefore = (() => {
const defaultExpiry = Math.floor(Date.now() / 1000) + 25
if (!challenge.expires) return defaultExpiry
const challengeExpiry = Math.floor(new Date(challenge.expires).getTime() / 1000)
return Math.min(defaultExpiry, challengeExpiry)
})()

if (mode === 'push') {
const { receipts } = await sendCallsSync(client, {
Expand All @@ -104,6 +131,7 @@ export function charge(parameters: charge.Parameters = {}) {
calls,
...(methodDetails?.feePayer && { feePayer: true }),
nonceKey: 'expiring',
validBefore,
} as never)
// FIXME: figure out gas estimation issue for fee payer tx
prepared.gas = prepared.gas! + 5_000n
Expand Down Expand Up @@ -131,6 +159,11 @@ export declare namespace charge {
autoSwap?: AutoSwap | undefined
/** Client identifier used to derive the client fingerprint in attribution memos. */
clientId?: string | undefined
/**
* Allowlist of expected split recipient addresses. When set, the client
* rejects any challenge whose split recipients are not in this list.
*/
expectedRecipients?: readonly Address[] | undefined
/**
* Controls how the charge transaction is submitted.
*
Expand Down
Loading
Loading