@agentbadge/circle-payments 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +203 -0
- package/dist/balance.d.ts +33 -0
- package/dist/balance.js +72 -0
- package/dist/chains.d.ts +63 -0
- package/dist/chains.js +41 -0
- package/dist/escrow/commission.d.ts +37 -0
- package/dist/escrow/commission.js +52 -0
- package/dist/escrow/erc8183.d.ts +288 -0
- package/dist/escrow/erc8183.js +318 -0
- package/dist/escrow/evaluator.d.ts +40 -0
- package/dist/escrow/evaluator.js +87 -0
- package/dist/history.d.ts +42 -0
- package/dist/history.js +52 -0
- package/dist/identity/erc8004.d.ts +227 -0
- package/dist/identity/erc8004.js +284 -0
- package/dist/identity/verify-passport.d.ts +17 -0
- package/dist/identity/verify-passport.js +64 -0
- package/dist/identity.d.ts +14 -0
- package/dist/identity.js +38 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +19 -0
- package/dist/ledger.d.ts +18 -0
- package/dist/ledger.js +39 -0
- package/dist/memo/memo.d.ts +100 -0
- package/dist/memo/memo.js +106 -0
- package/dist/middleware.d.ts +26 -0
- package/dist/middleware.js +104 -0
- package/dist/pricing.d.ts +9 -0
- package/dist/pricing.js +25 -0
- package/dist/router.d.ts +30 -0
- package/dist/router.js +72 -0
- package/dist/schemes/arc-self-settle.d.ts +29 -0
- package/dist/schemes/arc-self-settle.js +114 -0
- package/dist/schemes/exact.d.ts +22 -0
- package/dist/schemes/exact.js +71 -0
- package/dist/schemes/gateway.d.ts +22 -0
- package/dist/schemes/gateway.js +76 -0
- package/dist/status.d.ts +32 -0
- package/dist/status.js +86 -0
- package/package.json +51 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface PassportCheck {
|
|
2
|
+
verified: boolean;
|
|
3
|
+
trustScore: number;
|
|
4
|
+
passport?: {
|
|
5
|
+
passportTokenId: string;
|
|
6
|
+
readinessScore?: number;
|
|
7
|
+
mintTx?: string;
|
|
8
|
+
issuedAt?: string;
|
|
9
|
+
verifyUrl?: string;
|
|
10
|
+
};
|
|
11
|
+
reasons: string[];
|
|
12
|
+
}
|
|
13
|
+
interface PaymentRequiredLike {
|
|
14
|
+
extensions?: Record<string, unknown> | undefined;
|
|
15
|
+
}
|
|
16
|
+
export declare function verifyPassport(paymentRequired: string | PaymentRequiredLike): PassportCheck;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const B64_RE = /^[A-Za-z0-9+/=]+$/;
|
|
2
|
+
function decode402(input) {
|
|
3
|
+
if (typeof input !== "string")
|
|
4
|
+
return input;
|
|
5
|
+
try {
|
|
6
|
+
const raw = B64_RE.test(input)
|
|
7
|
+
? Buffer.from(input, "base64").toString("utf-8")
|
|
8
|
+
: input;
|
|
9
|
+
return JSON.parse(raw);
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export function verifyPassport(paymentRequired) {
|
|
16
|
+
const pr = decode402(paymentRequired);
|
|
17
|
+
if (!pr) {
|
|
18
|
+
return {
|
|
19
|
+
verified: false,
|
|
20
|
+
trustScore: 0,
|
|
21
|
+
reasons: ["malformed payment-required payload"],
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
const ext = pr.extensions?.agentbadge;
|
|
25
|
+
if (!ext || typeof ext !== "object") {
|
|
26
|
+
return {
|
|
27
|
+
verified: false,
|
|
28
|
+
trustScore: 0,
|
|
29
|
+
reasons: ["no agentbadge identity extension — seller unverified"],
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const reasons = [];
|
|
33
|
+
const tokenId = ext.passportTokenId;
|
|
34
|
+
if (typeof tokenId !== "string" || tokenId.length === 0) {
|
|
35
|
+
return {
|
|
36
|
+
verified: false,
|
|
37
|
+
trustScore: 0,
|
|
38
|
+
reasons: ["agentbadge extension missing passportTokenId"],
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
reasons.push(`passport ${tokenId}`);
|
|
42
|
+
const score = ext.readinessScore;
|
|
43
|
+
const hasScore = typeof score === "number" && score >= 0 && score <= 100;
|
|
44
|
+
if (hasScore)
|
|
45
|
+
reasons.push(`readiness ${score}`);
|
|
46
|
+
if (typeof ext.verifyUrl === "string")
|
|
47
|
+
reasons.push(`verify: ${ext.verifyUrl}`);
|
|
48
|
+
return {
|
|
49
|
+
verified: true,
|
|
50
|
+
trustScore: hasScore ? score : 50,
|
|
51
|
+
passport: {
|
|
52
|
+
passportTokenId: tokenId,
|
|
53
|
+
...(hasScore ? { readinessScore: score } : {}),
|
|
54
|
+
...(typeof ext.mintTx === "string" ? { mintTx: ext.mintTx } : {}),
|
|
55
|
+
...(typeof ext.issuedAt === "string"
|
|
56
|
+
? { issuedAt: ext.issuedAt }
|
|
57
|
+
: {}),
|
|
58
|
+
...(typeof ext.verifyUrl === "string"
|
|
59
|
+
? { verifyUrl: ext.verifyUrl }
|
|
60
|
+
: {}),
|
|
61
|
+
},
|
|
62
|
+
reasons,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface PassportIdentity {
|
|
2
|
+
passportTokenId: string;
|
|
3
|
+
readinessScore?: number;
|
|
4
|
+
mintTx?: string;
|
|
5
|
+
issuedAt?: string;
|
|
6
|
+
}
|
|
7
|
+
export type IdentityLookup = (sellerAddress: string) => Promise<PassportIdentity | undefined>;
|
|
8
|
+
export interface IdentityExtensionConfig {
|
|
9
|
+
lookup: IdentityLookup;
|
|
10
|
+
verifyUrlBase?: string;
|
|
11
|
+
ttlMs?: number;
|
|
12
|
+
}
|
|
13
|
+
export type IdentityExtensionBuilder = (sellerAddress: string) => Promise<Record<string, unknown> | undefined>;
|
|
14
|
+
export declare function createIdentityExtension(config: IdentityExtensionConfig): IdentityExtensionBuilder;
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
2
|
+
const DEFAULT_BASE = "https://agentbadge.xyz";
|
|
3
|
+
const DEFAULT_TTL_MS = 60_000;
|
|
4
|
+
export function createIdentityExtension(config) {
|
|
5
|
+
const ttl = config.ttlMs ?? DEFAULT_TTL_MS;
|
|
6
|
+
const base = (config.verifyUrlBase ?? DEFAULT_BASE).replace(/\/$/, "");
|
|
7
|
+
const cache = new Map();
|
|
8
|
+
return async (sellerAddress) => {
|
|
9
|
+
if (!EVM_ADDRESS.test(sellerAddress))
|
|
10
|
+
return undefined;
|
|
11
|
+
const now = Date.now();
|
|
12
|
+
const cached = cache.get(sellerAddress);
|
|
13
|
+
if (cached && cached.expiresAt > now)
|
|
14
|
+
return cached.ext;
|
|
15
|
+
let passport;
|
|
16
|
+
try {
|
|
17
|
+
passport = await config.lookup(sellerAddress);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
passport = undefined;
|
|
21
|
+
}
|
|
22
|
+
const ext = passport
|
|
23
|
+
? {
|
|
24
|
+
agentbadge: {
|
|
25
|
+
passportTokenId: passport.passportTokenId,
|
|
26
|
+
...(passport.readinessScore !== undefined
|
|
27
|
+
? { readinessScore: passport.readinessScore }
|
|
28
|
+
: {}),
|
|
29
|
+
verifyUrl: `${base}/verify/${passport.passportTokenId}`,
|
|
30
|
+
...(passport.mintTx ? { mintTx: passport.mintTx } : {}),
|
|
31
|
+
...(passport.issuedAt ? { issuedAt: passport.issuedAt } : {}),
|
|
32
|
+
},
|
|
33
|
+
}
|
|
34
|
+
: undefined;
|
|
35
|
+
cache.set(sellerAddress, { ext, expiresAt: now + ttl });
|
|
36
|
+
return ext;
|
|
37
|
+
};
|
|
38
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare const PACKAGE_VERSION = "0.1.0";
|
|
2
|
+
export * from "./chains.js";
|
|
3
|
+
export * from "./schemes/gateway.js";
|
|
4
|
+
export * from "./schemes/exact.js";
|
|
5
|
+
export * from "./schemes/arc-self-settle.js";
|
|
6
|
+
export * from "./router.js";
|
|
7
|
+
export * from "./middleware.js";
|
|
8
|
+
export * from "./identity.js";
|
|
9
|
+
export * from "./ledger.js";
|
|
10
|
+
export * from "./pricing.js";
|
|
11
|
+
export * from "./status.js";
|
|
12
|
+
export * from "./balance.js";
|
|
13
|
+
export * from "./history.js";
|
|
14
|
+
export * from "./escrow/erc8183.js";
|
|
15
|
+
export * from "./escrow/evaluator.js";
|
|
16
|
+
export * from "./escrow/commission.js";
|
|
17
|
+
export * from "./identity/erc8004.js";
|
|
18
|
+
export * from "./identity/verify-passport.js";
|
|
19
|
+
export * from "./memo/memo.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export const PACKAGE_VERSION = "0.1.0";
|
|
2
|
+
export * from "./chains.js";
|
|
3
|
+
export * from "./schemes/gateway.js";
|
|
4
|
+
export * from "./schemes/exact.js";
|
|
5
|
+
export * from "./schemes/arc-self-settle.js";
|
|
6
|
+
export * from "./router.js";
|
|
7
|
+
export * from "./middleware.js";
|
|
8
|
+
export * from "./identity.js";
|
|
9
|
+
export * from "./ledger.js";
|
|
10
|
+
export * from "./pricing.js";
|
|
11
|
+
export * from "./status.js";
|
|
12
|
+
export * from "./balance.js";
|
|
13
|
+
export * from "./history.js";
|
|
14
|
+
export * from "./escrow/erc8183.js";
|
|
15
|
+
export * from "./escrow/evaluator.js";
|
|
16
|
+
export * from "./escrow/commission.js";
|
|
17
|
+
export * from "./identity/erc8004.js";
|
|
18
|
+
export * from "./identity/verify-passport.js";
|
|
19
|
+
export * from "./memo/memo.js";
|
package/dist/ledger.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface PaymentFailure {
|
|
2
|
+
paymentId?: string;
|
|
3
|
+
scheme: string;
|
|
4
|
+
network: string;
|
|
5
|
+
payer?: string;
|
|
6
|
+
amount: string;
|
|
7
|
+
reason: string;
|
|
8
|
+
txRef?: string;
|
|
9
|
+
at?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface FailureStore {
|
|
12
|
+
append(failure: PaymentFailure): void | Promise<void>;
|
|
13
|
+
list(): PaymentFailure[] | Promise<PaymentFailure[]>;
|
|
14
|
+
}
|
|
15
|
+
export type FailureAlert = (failure: PaymentFailure) => void;
|
|
16
|
+
export declare function createMemoryFailureStore(): FailureStore;
|
|
17
|
+
export declare function createFileFailureStore(path: string): FailureStore;
|
|
18
|
+
export declare function recordFailure(store: FailureStore, failure: PaymentFailure, alert?: FailureAlert): Promise<void>;
|
package/dist/ledger.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
|
2
|
+
export function createMemoryFailureStore() {
|
|
3
|
+
const entries = [];
|
|
4
|
+
return {
|
|
5
|
+
append(f) {
|
|
6
|
+
entries.push(f);
|
|
7
|
+
},
|
|
8
|
+
list() {
|
|
9
|
+
return [...entries];
|
|
10
|
+
},
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export function createFileFailureStore(path) {
|
|
14
|
+
return {
|
|
15
|
+
append(f) {
|
|
16
|
+
appendFileSync(path, JSON.stringify(f) + "\n", "utf-8");
|
|
17
|
+
},
|
|
18
|
+
list() {
|
|
19
|
+
if (!existsSync(path))
|
|
20
|
+
return [];
|
|
21
|
+
return readFileSync(path, "utf-8")
|
|
22
|
+
.split("\n")
|
|
23
|
+
.filter((l) => l.trim().length > 0)
|
|
24
|
+
.map((l) => JSON.parse(l));
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export async function recordFailure(store, failure, alert) {
|
|
29
|
+
const entry = {
|
|
30
|
+
...failure,
|
|
31
|
+
at: new Date().toISOString(),
|
|
32
|
+
};
|
|
33
|
+
await store.append(entry);
|
|
34
|
+
try {
|
|
35
|
+
alert?.(entry);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { Hex } from "viem";
|
|
2
|
+
import type { ReadClient, WriteClient } from "../escrow/erc8183.js";
|
|
3
|
+
export declare const MEMO_CONTRACT: "0x5294E9927c3306DcBaDb03fe70b92e01cCede505";
|
|
4
|
+
export declare const MEMO_ABI: readonly [{
|
|
5
|
+
readonly type: "function";
|
|
6
|
+
readonly name: "memo";
|
|
7
|
+
readonly stateMutability: "nonpayable";
|
|
8
|
+
readonly inputs: readonly [{
|
|
9
|
+
readonly name: "target";
|
|
10
|
+
readonly type: "address";
|
|
11
|
+
}, {
|
|
12
|
+
readonly name: "data";
|
|
13
|
+
readonly type: "bytes";
|
|
14
|
+
}, {
|
|
15
|
+
readonly name: "memoId";
|
|
16
|
+
readonly type: "bytes32";
|
|
17
|
+
}, {
|
|
18
|
+
readonly name: "memoData";
|
|
19
|
+
readonly type: "bytes";
|
|
20
|
+
}];
|
|
21
|
+
readonly outputs: readonly [];
|
|
22
|
+
}, {
|
|
23
|
+
readonly type: "event";
|
|
24
|
+
readonly name: "Memo";
|
|
25
|
+
readonly inputs: readonly [{
|
|
26
|
+
readonly indexed: true;
|
|
27
|
+
readonly name: "sender";
|
|
28
|
+
readonly type: "address";
|
|
29
|
+
}, {
|
|
30
|
+
readonly indexed: true;
|
|
31
|
+
readonly name: "target";
|
|
32
|
+
readonly type: "address";
|
|
33
|
+
}, {
|
|
34
|
+
readonly indexed: false;
|
|
35
|
+
readonly name: "callDataHash";
|
|
36
|
+
readonly type: "bytes32";
|
|
37
|
+
}, {
|
|
38
|
+
readonly indexed: true;
|
|
39
|
+
readonly name: "memoId";
|
|
40
|
+
readonly type: "bytes32";
|
|
41
|
+
}, {
|
|
42
|
+
readonly indexed: false;
|
|
43
|
+
readonly name: "memo";
|
|
44
|
+
readonly type: "bytes";
|
|
45
|
+
}, {
|
|
46
|
+
readonly indexed: false;
|
|
47
|
+
readonly name: "memoIndex";
|
|
48
|
+
readonly type: "uint256";
|
|
49
|
+
}];
|
|
50
|
+
readonly anonymous: false;
|
|
51
|
+
}];
|
|
52
|
+
export declare class MemoError extends Error {
|
|
53
|
+
readonly phase: "call" | "parse";
|
|
54
|
+
readonly cause?: unknown | undefined;
|
|
55
|
+
constructor(message: string, phase: "call" | "parse", cause?: unknown | undefined);
|
|
56
|
+
}
|
|
57
|
+
export declare function memoIdFor(...parts: (string | bigint)[]): Hex;
|
|
58
|
+
export interface SettlementMemoFields {
|
|
59
|
+
orderId: string;
|
|
60
|
+
jobId: bigint;
|
|
61
|
+
verdictRef: Hex;
|
|
62
|
+
feeAmount: bigint;
|
|
63
|
+
}
|
|
64
|
+
export declare function encodeSettlementMemo(f: SettlementMemoFields): {
|
|
65
|
+
memoId: Hex;
|
|
66
|
+
memoData: Hex;
|
|
67
|
+
};
|
|
68
|
+
export interface MemoEvent {
|
|
69
|
+
sender: `0x${string}`;
|
|
70
|
+
target: `0x${string}`;
|
|
71
|
+
callDataHash: Hex;
|
|
72
|
+
memoId: Hex;
|
|
73
|
+
memo: Hex;
|
|
74
|
+
memoIndex: bigint;
|
|
75
|
+
}
|
|
76
|
+
export declare function createMemoClient(cfg: {
|
|
77
|
+
read: ReadClient;
|
|
78
|
+
memo?: `0x${string}`;
|
|
79
|
+
}): {
|
|
80
|
+
contract: `0x${string}`;
|
|
81
|
+
callWithMemo(wallet: WriteClient, args: {
|
|
82
|
+
target: `0x${string}`;
|
|
83
|
+
data: Hex;
|
|
84
|
+
memoId: Hex;
|
|
85
|
+
memoData: Hex;
|
|
86
|
+
}): Promise<Hex>;
|
|
87
|
+
settleWithMemo(wallet: WriteClient, args: {
|
|
88
|
+
escrowContract: `0x${string}`;
|
|
89
|
+
jobId: bigint;
|
|
90
|
+
reason: Hex;
|
|
91
|
+
memo: SettlementMemoFields;
|
|
92
|
+
}): Promise<Hex>;
|
|
93
|
+
parseMemoEvents(receipt: {
|
|
94
|
+
logs: Array<{
|
|
95
|
+
topics: Hex[];
|
|
96
|
+
data: Hex;
|
|
97
|
+
}>;
|
|
98
|
+
}): MemoEvent[];
|
|
99
|
+
};
|
|
100
|
+
export type MemoClient = ReturnType<typeof createMemoClient>;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { decodeEventLog, encodeAbiParameters, encodeFunctionData, keccak256, toBytes } from "viem";
|
|
2
|
+
import { ERC8183_ABI } from "../escrow/erc8183.js";
|
|
3
|
+
export const MEMO_CONTRACT = "0x5294E9927c3306DcBaDb03fe70b92e01cCede505";
|
|
4
|
+
export const MEMO_ABI = [
|
|
5
|
+
{
|
|
6
|
+
type: "function",
|
|
7
|
+
name: "memo",
|
|
8
|
+
stateMutability: "nonpayable",
|
|
9
|
+
inputs: [
|
|
10
|
+
{ name: "target", type: "address" },
|
|
11
|
+
{ name: "data", type: "bytes" },
|
|
12
|
+
{ name: "memoId", type: "bytes32" },
|
|
13
|
+
{ name: "memoData", type: "bytes" },
|
|
14
|
+
],
|
|
15
|
+
outputs: [],
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
type: "event",
|
|
19
|
+
name: "Memo",
|
|
20
|
+
inputs: [
|
|
21
|
+
{ indexed: true, name: "sender", type: "address" },
|
|
22
|
+
{ indexed: true, name: "target", type: "address" },
|
|
23
|
+
{ indexed: false, name: "callDataHash", type: "bytes32" },
|
|
24
|
+
{ indexed: true, name: "memoId", type: "bytes32" },
|
|
25
|
+
{ indexed: false, name: "memo", type: "bytes" },
|
|
26
|
+
{ indexed: false, name: "memoIndex", type: "uint256" },
|
|
27
|
+
],
|
|
28
|
+
anonymous: false,
|
|
29
|
+
},
|
|
30
|
+
];
|
|
31
|
+
export class MemoError extends Error {
|
|
32
|
+
phase;
|
|
33
|
+
cause;
|
|
34
|
+
constructor(message, phase, cause) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.phase = phase;
|
|
37
|
+
this.cause = cause;
|
|
38
|
+
this.name = "MemoError";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export function memoIdFor(...parts) {
|
|
42
|
+
return keccak256(toBytes(parts.join(":")));
|
|
43
|
+
}
|
|
44
|
+
export function encodeSettlementMemo(f) {
|
|
45
|
+
return {
|
|
46
|
+
memoId: memoIdFor("agentbadge", "settle", f.orderId, f.jobId),
|
|
47
|
+
memoData: encodeAbiParameters([
|
|
48
|
+
{ name: "orderId", type: "string" },
|
|
49
|
+
{ name: "jobId", type: "uint256" },
|
|
50
|
+
{ name: "verdictRef", type: "bytes32" },
|
|
51
|
+
{ name: "feeAmount", type: "uint256" },
|
|
52
|
+
], [f.orderId, f.jobId, f.verdictRef, f.feeAmount]),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export function createMemoClient(cfg) {
|
|
56
|
+
const memo = cfg.memo ?? MEMO_CONTRACT;
|
|
57
|
+
return {
|
|
58
|
+
contract: memo,
|
|
59
|
+
async callWithMemo(wallet, args) {
|
|
60
|
+
try {
|
|
61
|
+
return await wallet.writeContract({
|
|
62
|
+
address: memo,
|
|
63
|
+
abi: MEMO_ABI,
|
|
64
|
+
functionName: "memo",
|
|
65
|
+
args: [args.target, args.data, args.memoId, args.memoData],
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
throw new MemoError("memo call failed", "call", e);
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
async settleWithMemo(wallet, args) {
|
|
73
|
+
const data = encodeFunctionData({
|
|
74
|
+
abi: ERC8183_ABI,
|
|
75
|
+
functionName: "complete",
|
|
76
|
+
args: [args.jobId, args.reason, "0x"],
|
|
77
|
+
});
|
|
78
|
+
const { memoId, memoData } = encodeSettlementMemo(args.memo);
|
|
79
|
+
return this.callWithMemo(wallet, {
|
|
80
|
+
target: args.escrowContract,
|
|
81
|
+
data,
|
|
82
|
+
memoId,
|
|
83
|
+
memoData,
|
|
84
|
+
});
|
|
85
|
+
},
|
|
86
|
+
parseMemoEvents(receipt) {
|
|
87
|
+
const out = [];
|
|
88
|
+
for (const log of receipt.logs) {
|
|
89
|
+
try {
|
|
90
|
+
const decoded = decodeEventLog({
|
|
91
|
+
abi: MEMO_ABI,
|
|
92
|
+
data: log.data,
|
|
93
|
+
topics: log.topics,
|
|
94
|
+
});
|
|
95
|
+
if (decoded.eventName === "Memo") {
|
|
96
|
+
out.push(decoded.args);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from "hono";
|
|
2
|
+
import type { PaymentRequirements } from "./chains.js";
|
|
3
|
+
import { type FailureAlert, type FailureStore } from "./ledger.js";
|
|
4
|
+
import { type PaymentRouter, type PaymentRouterConfig } from "./router.js";
|
|
5
|
+
export interface RequirePaymentOptions extends PaymentRouterConfig {
|
|
6
|
+
router?: PaymentRouter;
|
|
7
|
+
description?: string;
|
|
8
|
+
mimeType?: string;
|
|
9
|
+
extensions?: Record<string, unknown> | (() => Promise<Record<string, unknown> | undefined>);
|
|
10
|
+
failureStore?: FailureStore;
|
|
11
|
+
onFailure?: FailureAlert;
|
|
12
|
+
}
|
|
13
|
+
export interface PaymentInfo {
|
|
14
|
+
payer?: string;
|
|
15
|
+
transaction?: string;
|
|
16
|
+
network: string;
|
|
17
|
+
scheme: string;
|
|
18
|
+
amount: string;
|
|
19
|
+
}
|
|
20
|
+
export declare function priceToAmount(price: string): string;
|
|
21
|
+
export interface PaymentPayload {
|
|
22
|
+
x402Version?: number;
|
|
23
|
+
accepted?: PaymentRequirements;
|
|
24
|
+
payload?: Record<string, unknown>;
|
|
25
|
+
}
|
|
26
|
+
export declare function requirePayment(price: string, opts: RequirePaymentOptions): MiddlewareHandler;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { recordFailure, } from "./ledger.js";
|
|
2
|
+
import { createPaymentRouter, } from "./router.js";
|
|
3
|
+
const b64encode = (o) => Buffer.from(JSON.stringify(o)).toString("base64");
|
|
4
|
+
function b64decode(s) {
|
|
5
|
+
try {
|
|
6
|
+
return JSON.parse(Buffer.from(s, "base64").toString("utf-8"));
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return undefined;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export function priceToAmount(price) {
|
|
13
|
+
const n = Number.parseFloat(price.replace("$", ""));
|
|
14
|
+
if (!Number.isFinite(n) || n < 0) {
|
|
15
|
+
throw new Error(`Invalid price: ${price}`);
|
|
16
|
+
}
|
|
17
|
+
return Math.round(n * 1_000_000).toString();
|
|
18
|
+
}
|
|
19
|
+
async function resolveExtensions(opts) {
|
|
20
|
+
const ext = opts.extensions;
|
|
21
|
+
if (!ext)
|
|
22
|
+
return undefined;
|
|
23
|
+
if (typeof ext === "function") {
|
|
24
|
+
try {
|
|
25
|
+
return await ext();
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return ext;
|
|
32
|
+
}
|
|
33
|
+
async function paymentRequired(c, accepts, opts, error) {
|
|
34
|
+
const extensions = await resolveExtensions(opts);
|
|
35
|
+
const body = {
|
|
36
|
+
x402Version: 2,
|
|
37
|
+
...(error ? { error } : {}),
|
|
38
|
+
resource: {
|
|
39
|
+
url: c.req.url,
|
|
40
|
+
description: opts.description ?? "Paid resource",
|
|
41
|
+
mimeType: opts.mimeType ?? "application/json",
|
|
42
|
+
},
|
|
43
|
+
accepts,
|
|
44
|
+
...(extensions ? { extensions } : {}),
|
|
45
|
+
};
|
|
46
|
+
return c.json({ error: error ?? "Payment required" }, 402, { "PAYMENT-REQUIRED": b64encode(body) });
|
|
47
|
+
}
|
|
48
|
+
export function requirePayment(price, opts) {
|
|
49
|
+
const amount = priceToAmount(price);
|
|
50
|
+
const router = opts.router ?? createPaymentRouter(opts);
|
|
51
|
+
return async (c, next) => {
|
|
52
|
+
const accepts = router.acceptsFor(amount);
|
|
53
|
+
const signatureHeader = c.req.header("payment-signature");
|
|
54
|
+
if (!signatureHeader) {
|
|
55
|
+
return paymentRequired(c, accepts, opts);
|
|
56
|
+
}
|
|
57
|
+
const paymentPayload = b64decode(signatureHeader);
|
|
58
|
+
if (!paymentPayload || typeof paymentPayload !== "object") {
|
|
59
|
+
return paymentRequired(c, accepts, opts, "Malformed payment-signature");
|
|
60
|
+
}
|
|
61
|
+
const accepted = paymentPayload.accepted;
|
|
62
|
+
const requirements = accepted &&
|
|
63
|
+
accepts.find((a) => a.scheme === accepted.scheme &&
|
|
64
|
+
a.network === accepted.network &&
|
|
65
|
+
a.asset === accepted.asset &&
|
|
66
|
+
(a.extra?.name ?? undefined) === (accepted.extra?.name ?? undefined));
|
|
67
|
+
if (!requirements) {
|
|
68
|
+
return paymentRequired(c, accepts, opts, "Unsupported payment option");
|
|
69
|
+
}
|
|
70
|
+
const verifyResult = await router.verify(paymentPayload, requirements);
|
|
71
|
+
if (!verifyResult.isValid) {
|
|
72
|
+
return paymentRequired(c, accepts, opts, verifyResult.invalidReason ?? "Payment verification failed");
|
|
73
|
+
}
|
|
74
|
+
const settleResult = await router.settle(paymentPayload, requirements);
|
|
75
|
+
if (!settleResult.success) {
|
|
76
|
+
return paymentRequired(c, accepts, opts, settleResult.errorReason ?? "Payment settlement failed");
|
|
77
|
+
}
|
|
78
|
+
const payment = {
|
|
79
|
+
payer: settleResult.payer ?? verifyResult.payer,
|
|
80
|
+
transaction: settleResult.transaction,
|
|
81
|
+
network: requirements.network,
|
|
82
|
+
scheme: requirements.scheme,
|
|
83
|
+
amount: requirements.amount,
|
|
84
|
+
};
|
|
85
|
+
c.set("payment", payment);
|
|
86
|
+
await next();
|
|
87
|
+
if (c.error && opts.failureStore) {
|
|
88
|
+
await recordFailure(opts.failureStore, {
|
|
89
|
+
scheme: requirements.scheme,
|
|
90
|
+
network: requirements.network,
|
|
91
|
+
payer: payment.payer,
|
|
92
|
+
amount: requirements.amount,
|
|
93
|
+
reason: c.error instanceof Error ? c.error.message : String(c.error),
|
|
94
|
+
txRef: settleResult.transaction,
|
|
95
|
+
}, opts.onFailure);
|
|
96
|
+
}
|
|
97
|
+
c.header("PAYMENT-RESPONSE", b64encode({
|
|
98
|
+
success: true,
|
|
99
|
+
transaction: settleResult.transaction,
|
|
100
|
+
network: requirements.network,
|
|
101
|
+
payer: payment.payer,
|
|
102
|
+
}));
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare const PRICE_TABLE: {
|
|
2
|
+
readonly "passport.mint": "$0.10";
|
|
3
|
+
readonly "readiness.scan": "$0.01";
|
|
4
|
+
readonly "identity.verify": "$0.001";
|
|
5
|
+
readonly "demo.data": "$0.001";
|
|
6
|
+
};
|
|
7
|
+
export type PriceRouteKey = keyof typeof PRICE_TABLE;
|
|
8
|
+
export declare function getPrice(key: string): string;
|
|
9
|
+
export declare function validatePriceTable(table: Record<string, string>): void;
|
package/dist/pricing.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { priceToAmount } from "./middleware.js";
|
|
2
|
+
export const PRICE_TABLE = {
|
|
3
|
+
"passport.mint": "$0.10",
|
|
4
|
+
"readiness.scan": "$0.01",
|
|
5
|
+
"identity.verify": "$0.001",
|
|
6
|
+
"demo.data": "$0.001",
|
|
7
|
+
};
|
|
8
|
+
export function getPrice(key) {
|
|
9
|
+
const price = PRICE_TABLE[key];
|
|
10
|
+
if (price === undefined) {
|
|
11
|
+
throw new Error(`Unknown price route: "${key}". Known: ${Object.keys(PRICE_TABLE).join(", ")}`);
|
|
12
|
+
}
|
|
13
|
+
return price;
|
|
14
|
+
}
|
|
15
|
+
export function validatePriceTable(table) {
|
|
16
|
+
for (const [key, price] of Object.entries(table)) {
|
|
17
|
+
try {
|
|
18
|
+
priceToAmount(price);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
throw new Error(`Invalid price for route "${key}": "${price}" ` +
|
|
22
|
+
`(expected "$0.01" or "0.01" USDC format)`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
package/dist/router.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type PaymentRequirements, type SettleResult, type SupportedChain, type VerifyResult } from "./chains.js";
|
|
2
|
+
export interface SchemeHandle {
|
|
3
|
+
verify(payload: unknown, requirements: PaymentRequirements): Promise<VerifyResult>;
|
|
4
|
+
settle(payload: unknown, requirements: PaymentRequirements): Promise<SettleResult>;
|
|
5
|
+
}
|
|
6
|
+
export interface RouterFlags {
|
|
7
|
+
gateway?: boolean;
|
|
8
|
+
exact?: boolean;
|
|
9
|
+
arc?: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface RouterConfig extends RouterFlags {
|
|
12
|
+
sellerAddress: string;
|
|
13
|
+
gatewayChains?: SupportedChain[];
|
|
14
|
+
exactChains?: SupportedChain[];
|
|
15
|
+
arcChain?: SupportedChain;
|
|
16
|
+
}
|
|
17
|
+
export interface PaymentRouterConfig extends RouterConfig {
|
|
18
|
+
handles: {
|
|
19
|
+
gateway?: SchemeHandle;
|
|
20
|
+
exact?: SchemeHandle;
|
|
21
|
+
arcSelfSettle?: SchemeHandle;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export interface PaymentRouter {
|
|
25
|
+
acceptsFor(amount: string): PaymentRequirements[];
|
|
26
|
+
verify(payload: unknown, requirements: PaymentRequirements): Promise<VerifyResult>;
|
|
27
|
+
settle(payload: unknown, requirements: PaymentRequirements): Promise<SettleResult>;
|
|
28
|
+
}
|
|
29
|
+
export declare function buildAccepts(amount: string, config: RouterConfig): PaymentRequirements[];
|
|
30
|
+
export declare function createPaymentRouter(config: PaymentRouterConfig): PaymentRouter;
|