@agent402-dev/pay-server 0.1.0 → 0.3.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/dist/x402.js CHANGED
@@ -1,11 +1,11 @@
1
- // 표준 x402 v2 (exact, Solana) — 리소스 서버 쪽 처리 단계 (@agent402-dev/pay-server 내부, gate.ts 가 씀).
1
+ // Standard x402 v2 (exact, Solana): resource-server-side processing steps (internal to @agent402-dev/pay-server, used by gate.ts).
2
2
  //
3
- // 흐름: 검증 → (호출자의 작업) → 정산
4
- // - verifyPaymentHeader: 결제가 고른 조건(accepted)이 지금 조건과 같은지(공식 매칭), resource 경로, 장부에서 잡기, facilitator verify
5
- // - settleVerified: facilitator settle → 체인 재확인. 실패·결과 모름이면 체인에서 구매자 서명으로 판정,
6
- // 없으면 "결과 모름"으로 두고 유효시간(150초)이 지나도 없을 때만 "결제 안 됨"
3
+ // Flow: verify → (caller's work) → settle
4
+ // - verifyPaymentHeader: checks the payment's chosen requirement (accepted) equals the current one (official matching), the resource path, claims it in the ledger, facilitator verify
5
+ // - settleVerified: facilitator settle → on-chain recheck. If it fails or the result is unknown, decide on-chain by the buyer's signature;
6
+ // if not found, keep it as "result unknown" and mark "not paid" only when it is still missing after the validity window (150 s)
7
7
  //
8
- // 서버에는 수령 지갑 공개 주소만 있음. 수수료 대납(feePayer) 키는 facilitator 가 가짐.
8
+ // The server holds only the receiving wallet's public address. The fee payer (feePayer) key belongs to the facilitator.
9
9
  import { decodePaymentSignatureHeader, encodePaymentResponseHeader } from '@x402/core/http';
10
10
  import { buildCoreRequirements, createCoreServer, definiteVerifyRejection, matchRequirement, settleFailureReason } from './core.js';
11
11
  import { ataOf, base58Encode, receivedBy, SPL_TOKEN, TOKEN_2022 } from './chain.js';
@@ -14,7 +14,7 @@ export const SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
14
14
  export const SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';
15
15
  const supportedCache = new Map();
16
16
  const SUPPORTED_TTL_MS = 10 * 60_000;
17
- /** facilitator 하나의 /supported 에서 이 네트워크 exact(v2) 의 feePayer (캐시) */
17
+ /** feePayer for exact (v2) on this network from one facilitator's /supported (cached) */
18
18
  async function supportedFor(f, network, nowMs) {
19
19
  const key = `${f.name}|${network}`;
20
20
  const c = supportedCache.get(key);
@@ -28,11 +28,11 @@ async function supportedFor(f, network, nowMs) {
28
28
  if (feePayer)
29
29
  chosen = { facilitator: f, feePayer, transactionVersions: kind?.extra?.transactionVersions, server };
30
30
  }
31
- catch { /* 장애 → null (짧게 캐시해 다음 facilitator 로) */ }
31
+ catch { /* outage → null (cached briefly, move on to the next facilitator) */ }
32
32
  supportedCache.set(key, { at: chosen ? nowMs : nowMs - SUPPORTED_TTL_MS + 30_000, chosen });
33
33
  return chosen;
34
34
  }
35
- /** 기본 → 예비 순서로, 이 네트워크 exact 를 지원하는 첫 facilitator */
35
+ /** First facilitator, primary then fallbacks, that supports exact on this network */
36
36
  export async function chooseFacilitator(cfg, nowMs) {
37
37
  for (const f of cfg.facilitators) {
38
38
  const c = await supportedFor(f, cfg.network, nowMs);
@@ -41,7 +41,7 @@ export async function chooseFacilitator(cfg, nowMs) {
41
41
  }
42
42
  return null;
43
43
  }
44
- /** 결제 조건의 feePayer 를 쓰는 facilitator (정산은 반드시 그 facilitator 로) */
44
+ /** Facilitator using the feePayer in the payment requirements (settlement must go to that facilitator) */
45
45
  export async function facilitatorForFeePayer(cfg, feePayer, nowMs) {
46
46
  if (typeof feePayer !== 'string')
47
47
  return null;
@@ -54,7 +54,7 @@ export async function facilitatorForFeePayer(cfg, feePayer, nowMs) {
54
54
  }
55
55
  export function clearSupportedCache() { supportedCache.clear(); }
56
56
  // ---------- 402 ----------
57
- /** 결제 조건 만들기 — 공식 x402ResourceServer.buildPaymentRequirementsFromOptions (feePayer·transactionVersions 는 공식 SVM 서버가 채움) */
57
+ /** Builds payment requirements with the official x402ResourceServer.buildPaymentRequirementsFromOptions (the official SVM server fills feePayer and transactionVersions) */
58
58
  export function buildRequirements(cfg, offers, chosen) {
59
59
  return buildCoreRequirements(chosen.server, cfg.network, cfg.payTo, cfg.maxTimeoutSeconds, offers.map((o) => ({
60
60
  asset: o.asset.mint,
@@ -64,11 +64,11 @@ export function buildRequirements(cfg, offers, chosen) {
64
64
  }
65
65
  const IN_PROGRESS_TTL_MS = 120_000;
66
66
  /**
67
- * 정산 결과를 모를 때, 이 시간이 지나도 체인에 없으면 그 트랜잭션은 더는 처리될 수 없음
68
- * (blockhash 유효 150블록 ≈ 60~90초에 여유를 둠)
67
+ * When the settlement result is unknown and the transaction is still not on-chain after this time, it can no longer be processed
68
+ * (blockhash is valid for 150 blocks ≈ 60 to 90 s, with margin)
69
69
  */
70
70
  export const SETTLE_UNKNOWN_EXPIRY_MS = 150_000;
71
- /** 장부 상태 전이 (Durable Object 와 메모리 구현이 같이 씀) */
71
+ /** Ledger state transitions (shared by the Durable Object and memory implementations) */
72
72
  export function ledgerClaim(e, nowMs) {
73
73
  if (!e)
74
74
  return { next: { state: 'in_progress', at: nowMs }, result: { ok: true, state: 'new' } };
@@ -78,7 +78,7 @@ export function ledgerClaim(e, nowMs) {
78
78
  return { next: e, result: { ok: false, state: 'in_progress' } };
79
79
  if (e.state === 'in_progress')
80
80
  return { next: { state: 'in_progress', at: nowMs }, result: { ok: true, state: 'new' } };
81
- // settle_unknown: 처리 중으로 잡되 원래 시각을 함께 돌려줌
81
+ // settle_unknown: claim as in progress, and also return the original time
82
82
  return { next: { state: 'in_progress', at: nowMs }, result: { ok: true, state: 'settle_unknown', since: e.at } };
83
83
  }
84
84
  export function memoryX402Ledger() {
@@ -95,7 +95,7 @@ export async function sha256Hex(s) {
95
95
  const d = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s));
96
96
  return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, '0')).join('');
97
97
  }
98
- /** 부분 서명된 트랜잭션(base64)에서 이미 채워진 서명들 (구매자 서명). 비어 있는 자리(전부 0)는 뺌 */
98
+ /** Signatures already filled in a partially signed transaction (base64) (the buyer's signatures). Empty slots (all zeros) are left out */
99
99
  export function presentSignatures(txBase64) {
100
100
  const buf = Uint8Array.from(atob(txBase64), (c) => c.charCodeAt(0));
101
101
  let n = 0, shift = 0, i = 0;
@@ -114,13 +114,13 @@ export function presentSignatures(txBase64) {
114
114
  }
115
115
  return out;
116
116
  }
117
- /** 체인 기록이 이 결제 조건을 만족하는지 */
117
+ /** Whether the on-chain record satisfies this payment requirement */
118
118
  function satisfies(tx, accepted) {
119
119
  return !tx.err && receivedBy(tx, accepted.payTo, accepted.asset) >= BigInt(accepted.amount);
120
120
  }
121
121
  /**
122
- * 정산 결과를 모를 때 체인에서 판정: 수령 토큰 계정의 최근 기록 중 구매자 서명이 들어 있는 트랜잭션을 찾음.
123
- * 찾으면 그 트랜잭션, 없으면 null
122
+ * Decides on-chain when the settlement result is unknown: finds a transaction containing the buyer's signature among recent records of the receiving token account.
123
+ * Returns that transaction if found, otherwise null
124
124
  */
125
125
  export async function findSettledOnChain(v, d) {
126
126
  const mine = new Set(presentSignatures(v.payload.payload.transaction));
@@ -135,8 +135,8 @@ export async function findSettledOnChain(v, d) {
135
135
  return null;
136
136
  }
137
137
  /**
138
- * 1단계: PAYMENT-SIGNATURE 확인 → 장부에서 잡기 → facilitator /verify. 돈은 아직 나가지 않음.
139
- * 호출자는 이 다음에 리포트를 만들고, 성공했을 때만 settleVerified 를 부름
138
+ * Step 1: check PAYMENT-SIGNATURE → claim in the ledger → facilitator /verify. No money moves yet.
139
+ * The caller then builds the report and calls settleVerified only on success
140
140
  */
141
141
  export async function verifyPaymentHeader(header, resourcePath, current, d) {
142
142
  let payload;
@@ -156,7 +156,7 @@ export async function verifyPaymentHeader(header, resourcePath, current, d) {
156
156
  catch {
157
157
  return { kind: 'payment_required', reason: 'resource_mismatch', message: 'Could not parse resource.url. No payment was taken.' };
158
158
  }
159
- // 공식 매칭 규칙 (scheme·network·asset·amount·payTo·maxTimeoutSeconds 완전 일치 + extra 포함 관계)
159
+ // Official matching rules (exact match of scheme, network, asset, amount, payTo, maxTimeoutSeconds + extra containment)
160
160
  const accepted = matchRequirement(current, payload, d.cfg.network);
161
161
  if (!accepted) {
162
162
  return { kind: 'payment_required', reason: 'requirements_mismatch', message: 'The chosen payment requirements no longer match the current ones (amount, rate, recipient or facilitator may have changed). No payment was taken; pay again with the new requirements.' };
@@ -174,7 +174,7 @@ export async function verifyPaymentHeader(header, resourcePath, current, d) {
174
174
  return { kind: 'unavailable', message: 'Could not reach the facilitator. No payment was taken.' };
175
175
  }
176
176
  const payment = { key, payload, accepted, facilitator: target.facilitator, server: target.server, settleUnknownSince: claim.state === 'settle_unknown' ? claim.since : null };
177
- // 지난번 정산 결과를 모르는 결제: 다시 verify 하지 않고 정산 단계에서 체인으로 판정
177
+ // Payment whose previous settlement result is unknown: do not verify again; decide on-chain in the settle step
178
178
  if (payment.settleUnknownSince !== null)
179
179
  return { kind: 'verified', payment };
180
180
  try {
@@ -194,12 +194,12 @@ export async function verifyPaymentHeader(header, resourcePath, current, d) {
194
194
  return { kind: 'verified', payment };
195
195
  }
196
196
  /**
197
- * 2단계 (리포트를 만든 뒤에만): facilitator /settle → 우리 RPC 로 체인 재확인.
198
- * 정산 결과를 모르면(시간 초과 등) 체인에서 구매자 서명으로 판정하고, 그래도 모르면 "결과 모름"으로 남김
197
+ * Step 2 (only after the report is built): facilitator /settle → on-chain recheck with our RPC.
198
+ * If the settlement result is unknown (timeout, etc.), decide on-chain by the buyer's signature; if still unknown, leave it as "result unknown"
199
199
  */
200
200
  export async function settleVerified(v, d) {
201
201
  const { accepted, key } = v;
202
- /** 체인에서 못 찾음 → 유효시간 안이면 "결과 모름"(재판정 대기), 지났으면 그때 비로소 "결제 안 됨"으로 풀어 줌 */
202
+ /** Not found on-chain → within the validity window, "result unknown" (awaiting recheck); after it, released as "not paid" */
203
203
  const unknown = async (facilitatorSaid) => {
204
204
  const since = v.settleUnknownSince ?? d.nowMs;
205
205
  if (d.nowMs - since > SETTLE_UNKNOWN_EXPIRY_MS) {
@@ -213,8 +213,8 @@ export async function settleVerified(v, d) {
213
213
  };
214
214
  };
215
215
  /**
216
- * 정산이 실패했거나 결과를 모를 때 (응답 없음·4xx·5xx·success:false 모두): facilitator 말만 믿지 않고 체인에서 먼저 찾음
217
- * (facilitator 가 tx 를 보낸 뒤 확정 대기 시간 초과로 실패를 돌려주는 경우 — 돈은 나갔을 수 있음)
216
+ * When settlement failed or its result is unknown (no response, 4xx, 5xx, success:false): don't rely only on the facilitator; look on-chain first
217
+ * (the facilitator may have sent the tx and then returned a failure after timing out on confirmation, so money may have moved)
218
218
  */
219
219
  const judgeOnChain = async (facilitatorSaid, reportedTx) => {
220
220
  if (reportedTx) {
@@ -231,7 +231,7 @@ export async function settleVerified(v, d) {
231
231
  kind: 'paid', confirmation: 'confirmed',
232
232
  settlement: { success: true, transaction: tx.signature, network: accepted.network, payer: tx.accountKeys[0] },
233
233
  });
234
- // 지난번 결과를 모르는 결제 → 체인으로만 판정 (다시 settle 하지 않음)
234
+ // Payment with an unknown previous result → decide on-chain only (do not settle again)
235
235
  if (v.settleUnknownSince !== null) {
236
236
  const tx = await findSettledOnChain(v, d).catch(() => null);
237
237
  if (tx && satisfies(tx, accepted))
@@ -243,13 +243,13 @@ export async function settleVerified(v, d) {
243
243
  settlement = await v.server.settlePayment(v.payload, accepted);
244
244
  }
245
245
  catch (e) {
246
- // 4xx 실패 응답이든 응답 없음(시간 초과·5xx)이든 → 체인에서 먼저 판정
246
+ // Whether a 4xx failure response or no response (timeout, 5xx) → decide on-chain first
247
247
  return judgeOnChain(settleFailureReason(e) ?? undefined);
248
248
  }
249
249
  if (!settlement.success) {
250
250
  return judgeOnChain(settlement.errorReason ?? 'settle_failed', settlement.transaction || undefined);
251
251
  }
252
- // 체인 재확인 (facilitator 응답을 그대로 믿지 않음)
252
+ // On-chain recheck (don't trust the facilitator response as is)
253
253
  let confirmed = null;
254
254
  for (const wait of [0, ...(d.confirmDelaysMs ?? [1000, 2000, 4000])]) {
255
255
  if (wait)
@@ -262,7 +262,7 @@ export async function settleVerified(v, d) {
262
262
  await d.ledger.release(key);
263
263
  return { kind: 'payment_required', reason: 'onchain_mismatch', message: 'On-chain record shows the receiving address did not receive the required amount.' };
264
264
  }
265
- // facilitator 는 성공이라 했는데 아직 체인에서 못 찾음 → 구매자가 돈을 냈을 수 있으므로 리포트는 드리고 "확인 대기"로 표시
265
+ // The facilitator reported success but it is not on-chain yet → the buyer may have paid, so deliver the report and mark it "pending confirmation"
266
266
  return { kind: 'paid', settlement, confirmation: confirmed ? 'confirmed' : 'pending' };
267
267
  }
268
268
  export function paymentResponseHeader(s) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent402-dev/pay-server",
3
- "description": "Server helpers for x402 on Solana: accept USDC and optionally A402 (Token-2022) through external facilitators. Verify, run your handler, then settle. Holds no funds and no private keys.",
3
+ "description": "Server helpers for x402 on Solana: accept USDC and optionally PREQ (Token-2022) through external facilitators. Verify, run your handler, then settle. Holds no funds and no private keys.",
4
4
  "keywords": [
5
5
  "x402",
6
6
  "solana",
@@ -25,7 +25,7 @@
25
25
  "@x402/core": "2.31.0",
26
26
  "@x402/svm": "2.31.0"
27
27
  },
28
- "version": "0.1.0",
28
+ "version": "0.3.0",
29
29
  "author": "Agent402",
30
30
  "license": "Apache-2.0",
31
31
  "type": "module",