@agent402-dev/pay-server 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,6 @@
1
+ A402 Check — token check engine
2
+ Copyright 2026 Agent402
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ Results produced by this software are factual information from public on-chain data and are not investment advice.
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # @agent402-dev/pay-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **A402 (v1) is deprecated.** The token payment option is now **PREQ** (mint `aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX`). Official addresses: https://claude.ai/artifact/S6UafAfViJk3DJeMsDMAja
4
+
5
+ Server helpers for [x402](https://github.com/coinbase/x402) payments on Solana that accept **USDC** and, optionally, **PREQ** (a Token-2022 token) through standard x402 facilitators.
6
+
7
+ Part of the [Agent402 toolkit](https://github.com/agent402-dev/agent402-toolkit) (Solana).
8
+ Not related to `agent402.tools`, `@agents402` or other similarly named sites, accounts or projects, including projects named "a402" on other chains.
9
+
10
+ > This package moves no funds itself and gives no opinion on any token. Rates and amounts are facts computed from public on-chain data, not investment advice.
11
+
12
+ ## What it does
13
+ - Builds x402 v2 `exact` payment requirements per request with the official `@x402/core` `x402ResourceServer` (USDC, plus PREQ when it can be offered).
14
+ - Order of work: **verify → your handler → settle**. If your handler fails, times out (default 40 s), or returns a status ≥ 400, the payment is **not settled**.
15
+ - If a settlement fails or its result is unknown, it checks the chain for the buyer's transaction before answering. It treats the payment as not taken only after the transaction can no longer land (about 150 s).
16
+ - Keeps a ledger so a payment cannot be used twice.
17
+ - Rechecks the settlement transaction on chain (amount received by your address).
18
+ - Uses the next facilitator in your list when one is unreachable or fails for reasons on its own side (for example its fee payer lacks SOL).
19
+
20
+ ## What it does not do
21
+ - It **does not judge, score or rate tokens** and gives no investment advice.
22
+ - It **does not operate a facilitator.** Verification and settlement are done by the external facilitators you configure.
23
+ - It **does not hold funds.** Payments go from the buyer's wallet directly to your receiving address.
24
+ - It **does not exchange** currencies. The PREQ rate is used only to compute the PREQ amount; there is no PREQ ↔ USDC conversion.
25
+ - It **does not accept or send payments on anyone's behalf.** Your server receives only your receiving address (public key); there is no API that takes a private key.
26
+
27
+ ## PREQ option
28
+ PREQ is offered only when all of these hold for the request:
29
+ 1. The selected facilitator is configured to accept PREQ.
30
+ 2. Your receiving address has a PREQ (Token-2022) token account. `exact` payments do not create the receiving account; create it in advance. The same applies to USDC.
31
+ 3. The day's PREQ rate is available. The rate is the median of the previous UTC day's hourly samples (Meteora DAMM v2 PREQ/SOL pool price × Pyth SOL/USD). It is switched off for the day when there are fewer than 12 samples, the pool's SOL-side depth fell below 100 USD, the max/min ratio exceeded 1.5, or any sample has a zero or non-finite price. These thresholds are configurable. Right after trading starts, a single-sided pool holds almost no SOL, so the depth rule keeps PREQ off until the pool has SOL-side depth.
32
+
33
+ When PREQ is not offered, the 402 response lists it under `notOffered` with the reason.
34
+
35
+ **PREQ addresses.** `PREQ_MAINNET` (mint) and the pricing pool address are kept in one place, `src/preq.ts`. Until they are filled in, enabling PREQ (`config.preq` with `PREQ_MAINNET`, or `rates.record()`) stops with an error that names the missing value.
36
+
37
+ **Units.** As in every x402 requirement, `amount` is in the token's smallest unit. USDC and PREQ both have 6 decimals: 1 USDC = 1,000,000 smallest units, 1 PREQ = 1,000,000 smallest units. For example, a PREQ `amount` of `140000000000` is 140,000 PREQ. The PREQ amount is `priceUsd ÷ (PREQ rate in USD)`, rounded up to the smallest unit: the same USD price as USDC. (`discountPercent` exists as an optional setting and defaults to 0.)
38
+
39
+ **A402 (v1).** A402 is deprecated and is not part of any default. `A402_MAINNET` and `config.a402` remain only for existing setups; passing `config.a402` prints the warning "A402 (v1) is deprecated and no longer supported; use PREQ.". Nothing is paid in A402 unless you configure it explicitly.
40
+
41
+ ## Facilitators (facts as checked on Solana mainnet, 2026-11-19)
42
+ | Facilitator | USDC `exact` | A402 (v1, deprecated; Token-2022) `exact` |
43
+ |---|---|---|
44
+ | PayAI `https://facilitator.payai.network` | verify and settle succeeded | verify and settle succeeded (fee paid by the facilitator's fee payer) |
45
+ | Dexter `https://x402.dexter.cash` | listed in `/supported`; at the time of the check, verify returned `transaction_simulation_failed` because its fee payer account held 0.000656 SOL | verify returned `policy:asset_not_allowed` (A402 is not in its asset allowlist) |
46
+
47
+ PREQ has not been checked on a hosted facilitator yet. On 2026-11-22 a PREQ payment was verified and settled end to end in a local mainnet-fork rehearsal (Surfpool, with the official x402 facilitator code `@x402/svm` exact scheme and the real PREQ mint). `KNOWN_FACILITATORS.payai` lists PREQ because PayAI's `/supported` shows no asset restriction for the Solana `exact` scheme and it accepted a Token-2022 token in the check above. These are observations from one day. Facilitator policies and balances change; `KNOWN_FACILITATORS` only provides defaults that you can override.
48
+
49
+ **Facilitator fees.** As of 2026-11-22, PayAI's documentation describes a free tier of up to 10,000 settlements per month without an API key, and paid credits with an API key beyond that. Check the facilitator's current terms before production use.
50
+
51
+ ## Install
52
+ ```bash
53
+ npm install @agent402-dev/pay-server
54
+ ```
55
+ Node 20+ or Cloudflare Workers (`nodejs_compat`). ESM only.
56
+
57
+ ## Usage
58
+ ```ts
59
+ import { createPaymentGate, rpcChain, KNOWN_FACILITATORS, SOLANA_MAINNET, USDC_MAINNET, PREQ_MAINNET,
60
+ createRateBook, memoryRateStore } from '@agent402-dev/pay-server';
61
+
62
+ const rates = createRateBook({ store: memoryRateStore(), fetcher: rpcChain(RPC_URL).accounts }); // PREQ pool from src/preq.ts
63
+ const gate = createPaymentGate({
64
+ network: SOLANA_MAINNET,
65
+ payTo: 'YOUR_RECEIVING_ADDRESS',
66
+ priceUsd: 0.02, // example setting
67
+ usdc: USDC_MAINNET,
68
+ preq: { asset: PREQ_MAINNET, rate: () => rates.today() },
69
+ facilitators: [KNOWN_FACILITATORS.payai, KNOWN_FACILITATORS.dexter],
70
+ chain: rpcChain(RPC_URL),
71
+ });
72
+
73
+ export default {
74
+ fetch: gate.withPayment(async (req) => new Response(JSON.stringify({ hello: 'paid world' }))),
75
+ };
76
+ // call rates.record() hourly (cron) to collect samples
77
+ ```
78
+ Rate stores: `memoryRateStore()` (default, tests), `fileRateStore(path)` from `@agent402-dev/pay-server/rates-file` (Node), or your own `RateStore` (for example a Cloudflare Durable Object; see the [Workers example](https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/pay-server/examples/cloudflare-worker)). A Node example is in [`examples/node-server`](https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/pay-server/examples/node-server).
79
+
80
+ ## License
81
+ Apache-2.0. See [LICENSE](https://github.com/agent402-dev/agent402-toolkit/blob/main/LICENSE) and [NOTICE](https://github.com/agent402-dev/agent402-toolkit/blob/main/NOTICE).
82
+
83
+ ---
84
+ Factual information from public on-chain data. Not investment advice.
@@ -0,0 +1,48 @@
1
+ /** Transaction info needed to confirm settlement */
2
+ export interface ChainTx {
3
+ signature: string;
4
+ err: boolean;
5
+ /** Index 0 = fee payer */
6
+ accountKeys: string[];
7
+ preTokenBalances: {
8
+ accountIndex: number;
9
+ mint: string;
10
+ owner?: string | null;
11
+ amount: string;
12
+ }[];
13
+ postTokenBalances: {
14
+ accountIndex: number;
15
+ mint: string;
16
+ owner?: string | null;
17
+ amount: string;
18
+ }[];
19
+ /** All signatures in the transaction (to find the buyer's signature) */
20
+ signatures: string[];
21
+ }
22
+ export interface ChainAccount {
23
+ owner: string;
24
+ data: Uint8Array;
25
+ lamports?: number;
26
+ }
27
+ export type AccountFetcher = (addresses: string[]) => Promise<{
28
+ slot: number;
29
+ accounts: (ChainAccount | null)[];
30
+ }>;
31
+ export interface ChainReader {
32
+ loadTx(signature: string): Promise<ChainTx | null>;
33
+ recentSignatures(address: string, limit: number): Promise<string[]>;
34
+ accounts: AccountFetcher;
35
+ }
36
+ /** Increase at the receiving address for this payment asset (sum of that mint's token accounts owned by the receiver) */
37
+ export declare function receivedBy(tx: ChainTx, owner: string, mint: string): bigint;
38
+ export interface RpcOptions {
39
+ fetchImpl?: typeof fetch;
40
+ commitment?: 'confirmed' | 'finalized';
41
+ }
42
+ /** Builds a ChainReader over JSON-RPC. The RPC address (which may contain a key) is never put in error messages */
43
+ export declare function rpcChain(rpcUrl: string, o?: RpcOptions): ChainReader;
44
+ export declare const SPL_TOKEN = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
45
+ export declare const TOKEN_2022 = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
46
+ /** Associated token account (ATA) address */
47
+ export declare function ataOf(owner: string, mint: string, tokenProgram: string): Promise<string>;
48
+ export declare function base58Encode(bytes: Uint8Array): string;
package/dist/chain.js ADDED
@@ -0,0 +1,71 @@
1
+ // What the SDK reads from the chain (minimal implementation, independent of the check engine). Uses only fetch, so it runs on Cloudflare Workers and Node.
2
+ // - Reads settlement transactions (checks the received increase) and recent signatures of receiving token accounts (to decide when the settlement result is unknown)
3
+ // - Reads multiple accounts (rate recording, checking the receiver's token account)
4
+ /** Increase at the receiving address for this payment asset (sum of that mint's token accounts owned by the receiver) */
5
+ export function receivedBy(tx, owner, mint) {
6
+ const sum = (xs) => xs.filter((b) => b.owner === owner && b.mint === mint).reduce((s, b) => s + BigInt(b.amount), 0n);
7
+ return sum(tx.postTokenBalances) - sum(tx.preTokenBalances);
8
+ }
9
+ /** Builds a ChainReader over JSON-RPC. The RPC address (which may contain a key) is never put in error messages */
10
+ export function rpcChain(rpcUrl, o = {}) {
11
+ const f = o.fetchImpl ?? fetch;
12
+ const commitment = o.commitment ?? 'confirmed';
13
+ let id = 0;
14
+ async function call(method, params) {
15
+ const res = await f(rpcUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: ++id, method, params }) });
16
+ if (!res.ok)
17
+ throw new Error(`rpc ${method}: HTTP ${res.status}`);
18
+ const j = (await res.json());
19
+ if (j.error)
20
+ throw new Error(`rpc ${method}: ${j.error.code}`);
21
+ return j.result;
22
+ }
23
+ return {
24
+ async loadTx(signature) {
25
+ const r = await call('getTransaction', [signature, { encoding: 'json', commitment, maxSupportedTransactionVersion: 0 }]);
26
+ if (!r || !r.meta)
27
+ return null;
28
+ const keys = [...r.transaction.message.accountKeys, ...(r.meta.loadedAddresses?.writable ?? []), ...(r.meta.loadedAddresses?.readonly ?? [])];
29
+ const tb = (xs) => (xs ?? []).map((b) => ({ accountIndex: b.accountIndex, mint: b.mint, owner: b.owner, amount: b.uiTokenAmount.amount }));
30
+ return { signature, err: r.meta.err !== null, accountKeys: keys, preTokenBalances: tb(r.meta.preTokenBalances), postTokenBalances: tb(r.meta.postTokenBalances), signatures: r.transaction.signatures };
31
+ },
32
+ async recentSignatures(address, limit) {
33
+ const r = await call('getSignaturesForAddress', [address, { limit, commitment }]);
34
+ return r.map((x) => x.signature);
35
+ },
36
+ async accounts(addresses) {
37
+ const r = await call('getMultipleAccounts', [addresses, { encoding: 'base64', commitment }]);
38
+ return {
39
+ slot: r.context.slot,
40
+ accounts: r.value.map((a) => (a ? { owner: a.owner, lamports: a.lamports, data: Uint8Array.from(atob(a.data[0]), (c) => c.charCodeAt(0)) } : null)),
41
+ };
42
+ },
43
+ };
44
+ }
45
+ // ---------- Addresses ----------
46
+ export const SPL_TOKEN = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
47
+ export const TOKEN_2022 = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';
48
+ const ATA_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
49
+ /** Associated token account (ATA) address */
50
+ export async function ataOf(owner, mint, tokenProgram) {
51
+ const { PublicKey } = await import('@solana/web3.js');
52
+ return PublicKey.findProgramAddressSync([new PublicKey(owner).toBuffer(), new PublicKey(tokenProgram).toBuffer(), new PublicKey(mint).toBuffer()], new PublicKey(ATA_PROGRAM))[0].toBase58();
53
+ }
54
+ const B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
55
+ export function base58Encode(bytes) {
56
+ let n = 0n;
57
+ for (const b of bytes)
58
+ n = n * 256n + BigInt(b);
59
+ let s = '';
60
+ while (n > 0n) {
61
+ s = B58[Number(n % 58n)] + s;
62
+ n /= 58n;
63
+ }
64
+ for (const b of bytes) {
65
+ if (b === 0)
66
+ s = '1' + s;
67
+ else
68
+ break;
69
+ }
70
+ return s;
71
+ }
package/dist/core.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { x402ResourceServer, type FacilitatorClient } from '@x402/core/server';
2
+ import type { PaymentPayload, PaymentRequirements } from '@x402/core/types';
3
+ /** Official resource server wrapping one facilitator (initialized from that facilitator's /supported) */
4
+ export declare function createCoreServer(client: FacilitatorClient, network: string): Promise<x402ResourceServer>;
5
+ /** The current requirement equal to the one the payment chose (accepted), using the official matching rules */
6
+ export declare function matchRequirement(current: PaymentRequirements[], payload: PaymentPayload, network: string): PaymentRequirements | undefined;
7
+ export interface CoreOffer {
8
+ asset: string;
9
+ amount: string;
10
+ extra: Record<string, unknown>;
11
+ }
12
+ /** Builds payment requirements with the official server (the caller decides the payment assets per request) */
13
+ export declare function buildCoreRequirements(server: x402ResourceServer, network: string, payTo: string, maxTimeoutSeconds: number, offers: CoreOffer[]): Promise<PaymentRequirements[]>;
14
+ /**
15
+ * Failure reason the facilitator sent in a settle exception, if any. For logging and messages only: even with a failure response, the facilitator may have sent the tx
16
+ * and then timed out waiting for confirmation, so the result is always decided on-chain
17
+ */
18
+ export declare function settleFailureReason(e: unknown): string | null;
19
+ /** Whether a verify exception is a "definite rejection" (4xx + invalidReason) */
20
+ export declare function definiteVerifyRejection(e: unknown): {
21
+ reason: string;
22
+ message?: string;
23
+ } | null;
package/dist/core.js ADDED
@@ -0,0 +1,59 @@
1
+ // Layer on top of the official @x402/core x402ResourceServer.
2
+ // The official code handles: reading /supported, building payment requirements (parsePrice, filling feePayer and transactionVersions),
3
+ // matching payments to requirements (findMatchingRequirements), and calling facilitator verify and settle
4
+ // What we handle (x402.ts): fallback when a facilitator is down, choosing payment assets per request, the replay-protection ledger, on-chain decisions and rechecks
5
+ import { x402ResourceServer } from '@x402/core/server';
6
+ import { ExactSvmScheme } from '@x402/svm/exact/server';
7
+ /** Official resource server wrapping one facilitator (initialized from that facilitator's /supported) */
8
+ export async function createCoreServer(client, network) {
9
+ const server = new x402ResourceServer(client).register(network, new ExactSvmScheme());
10
+ await server.initialize();
11
+ return server;
12
+ }
13
+ /** Server that only matches requirements, without a facilitator (one per network) */
14
+ const matchers = new Map();
15
+ function matcher(network) {
16
+ let m = matchers.get(network);
17
+ if (!m) {
18
+ m = new x402ResourceServer([]).register(network, new ExactSvmScheme());
19
+ matchers.set(network, m);
20
+ }
21
+ return m;
22
+ }
23
+ /** The current requirement equal to the one the payment chose (accepted), using the official matching rules */
24
+ export function matchRequirement(current, payload, network) {
25
+ try {
26
+ return matcher(network).findMatchingRequirements(current, payload);
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ /** Builds payment requirements with the official server (the caller decides the payment assets per request) */
33
+ export function buildCoreRequirements(server, network, payTo, maxTimeoutSeconds, offers) {
34
+ return server.buildPaymentRequirementsFromOptions(offers.map((o) => ({
35
+ scheme: 'exact',
36
+ network: network,
37
+ payTo,
38
+ maxTimeoutSeconds,
39
+ price: { asset: o.asset, amount: o.amount, extra: o.extra },
40
+ })), {});
41
+ }
42
+ /**
43
+ * Failure reason the facilitator sent in a settle exception, if any. For logging and messages only: even with a failure response, the facilitator may have sent the tx
44
+ * and then timed out waiting for confirmation, so the result is always decided on-chain
45
+ */
46
+ export function settleFailureReason(e) {
47
+ const err = e;
48
+ if (err?.name === 'SettleError' && err.errorReason)
49
+ return `${err.errorReason}${typeof err.statusCode === 'number' ? ` (HTTP ${err.statusCode})` : ''}`;
50
+ return null;
51
+ }
52
+ /** Whether a verify exception is a "definite rejection" (4xx + invalidReason) */
53
+ export function definiteVerifyRejection(e) {
54
+ const err = e;
55
+ if (err?.name === 'VerifyError' && typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 500 && err.invalidReason) {
56
+ return { reason: err.invalidReason, message: err.invalidMessage };
57
+ }
58
+ return null;
59
+ }
package/dist/gate.d.ts ADDED
@@ -0,0 +1,118 @@
1
+ import { type FacilitatorClient } from '@x402/core/server';
2
+ import type { PaymentRequirements } from '@x402/core/types';
3
+ import { type ChainReader } from './chain.js';
4
+ import { type DailyRate } from './pricing.js';
5
+ import { type Asset, type X402Ledger } from './x402.js';
6
+ /** A402 is deprecated (v1) */
7
+ export type AssetSymbol = 'USDC' | 'PREQ' | 'A402';
8
+ /** Settings for a token accepted in addition to USDC */
9
+ export interface TokenPayment {
10
+ asset: Asset;
11
+ /** Optional. Default 0: the token is charged the same USD price as USDC */
12
+ discountPercent?: number;
13
+ /** Today's fixed rate. If off or failing, that request does not offer this token */
14
+ rate: () => Promise<DailyRate | null>;
15
+ }
16
+ export interface FacilitatorSpec {
17
+ name: string;
18
+ /** Either url or client */
19
+ url?: string;
20
+ client?: FacilitatorClient;
21
+ /** Payment assets this facilitator accepts. Assets it does not accept are not put in the 402 */
22
+ assets: AssetSymbol[];
23
+ }
24
+ /**
25
+ * Facilitator defaults. Policies and status can change, so these are only defaults and can be overridden in config.
26
+ * - USDC: confirmed with mainnet verify and settle on 2026-11-19 (PayAI, Dexter)
27
+ * - A402 (v1, deprecated): record of a check on PayAI on 2026-11-19
28
+ * - PREQ: listed for PayAI (no asset restriction for Solana exact in /supported). Verified and settled in a local mainnet-fork rehearsal on 2026-11-22; not yet checked on a hosted facilitator
29
+ */
30
+ export declare const KNOWN_FACILITATORS: {
31
+ readonly payai: {
32
+ readonly name: "payai";
33
+ readonly url: "https://facilitator.payai.network";
34
+ readonly assets: AssetSymbol[];
35
+ };
36
+ readonly dexter: {
37
+ readonly name: "dexter";
38
+ readonly url: "https://x402.dexter.cash";
39
+ readonly assets: AssetSymbol[];
40
+ };
41
+ };
42
+ export declare const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
43
+ export declare const SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
44
+ export declare const USDC_MAINNET: Asset;
45
+ /** PREQ (Token-2022, 6 decimals). The mint is PREQ_MAINNET_MINT in preq.ts; if empty, createPaymentGate stops with an error */
46
+ export declare const PREQ_MAINNET: Asset;
47
+ /** @deprecated A402 (v1) is deprecated. Use PREQ_MAINNET. Enabling it explicitly with config.a402 prints a warning */
48
+ export declare const A402_MAINNET: Asset;
49
+ export interface GateConfig {
50
+ network: string;
51
+ /** Public address of the receiving wallet */
52
+ payTo: string;
53
+ /** USDC price (USD) */
54
+ priceUsd: number;
55
+ usdc: Asset;
56
+ /** Only when accepting PREQ. If rate() is off or fails, that request does not offer PREQ. Errors if asset.mint is empty */
57
+ preq?: TokenPayment;
58
+ /**
59
+ * @deprecated A402 (v1) is deprecated; use PREQ. Not in the defaults.
60
+ * Accepted only when set explicitly, and createPaymentGate prints a warning ("A402 (v1) is deprecated and no longer supported; use PREQ.")
61
+ */
62
+ a402?: TokenPayment;
63
+ /** Warning output (default console.warn) */
64
+ warn?: (message: string) => void;
65
+ /** First is primary, the rest are fallbacks */
66
+ facilitators: FacilitatorSpec[];
67
+ /** Chain reader (settlement recheck, deciding unknown results, checking receiving token accounts) */
68
+ chain: ChainReader;
69
+ ledger?: X402Ledger;
70
+ /** Handler time limit: if exceeded, no settlement (default 40 s, shorter than the payment transaction's validity) */
71
+ handlerTimeoutMs?: number;
72
+ maxTimeoutSeconds?: number;
73
+ /** If verify fails because of the facilitator (e.g. fee payer balance too low), skip that facilitator for this long (default 5 min) */
74
+ facilitatorCooldownMs?: number;
75
+ /** Cache for the receiving token account check (default 10 min) */
76
+ receivingCheckTtlMs?: number;
77
+ resource?: {
78
+ description?: string;
79
+ mimeType?: string;
80
+ serviceName?: string;
81
+ };
82
+ now?: () => number;
83
+ /** Retry intervals for the on-chain recheck (default 1, 2, 4 s) */
84
+ confirmDelaysMs?: number[];
85
+ }
86
+ export interface ReceivingAccount {
87
+ asset: AssetSymbol;
88
+ mint: string;
89
+ tokenAccount: string;
90
+ exists: boolean;
91
+ }
92
+ export interface PaymentInfo {
93
+ asset: string;
94
+ amount: string;
95
+ payTo: string;
96
+ network: string;
97
+ }
98
+ export interface PaymentGate {
99
+ /** Wraps a paid handler */
100
+ withPayment(handler: (req: Request, payment: PaymentInfo) => Promise<Response>): (req: Request) => Promise<Response>;
101
+ /** Payment requirements that would go in a 402 now, plus missing assets and why (for checking) */
102
+ quote(resourceUrl: string): Promise<{
103
+ accepts: PaymentRequirements[];
104
+ notOffered: {
105
+ asset: AssetSymbol;
106
+ reason: string;
107
+ }[];
108
+ facilitator: string;
109
+ } | null>;
110
+ /** Whether the receiving wallet has USDC and PREQ (and A402) token accounts (assets without one are not put in the 402) */
111
+ checkReceivingAccounts(): Promise<ReceivingAccount[]>;
112
+ }
113
+ /**
114
+ * Whether a verify failure is a facilitator-side problem rather than the buyer's fault (e.g. the fee payer = transaction account 0 has too little balance).
115
+ * Real case on 2026-11-19: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
116
+ */
117
+ export declare function isFacilitatorSideFailure(reason?: string, message?: string): boolean;
118
+ export declare function createPaymentGate(c: GateConfig): PaymentGate;