@agent402-dev/pay-server 0.0.0-stage → 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/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +76 -2
- package/dist/chain.d.ts +48 -0
- package/dist/chain.js +71 -0
- package/dist/core.d.ts +23 -0
- package/dist/core.js +59 -0
- package/dist/gate.d.ts +101 -0
- package/dist/gate.js +212 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +6 -0
- package/dist/pricing.d.ts +87 -0
- package/dist/pricing.js +127 -0
- package/dist/rates-file.d.ts +2 -0
- package/dist/rates-file.js +33 -0
- package/dist/rates.d.ts +26 -0
- package/dist/rates.js +41 -0
- package/dist/x402.d.ts +199 -0
- package/dist/x402.js +270 -0
- package/package.json +51 -4
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
package/README.md
CHANGED
|
@@ -1,3 +1,77 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @agent402-dev/pay-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Server helpers for [x402](https://github.com/coinbase/x402) payments on Solana that accept **USDC** and, optionally, **A402** (a Token-2022 token) through standard x402 facilitators.
|
|
4
|
+
|
|
5
|
+
Part of the [Agent402 toolkit](https://github.com/agent402-dev/agent402-toolkit) (Solana).
|
|
6
|
+
Not related to `agent402.tools`, `@agents402` or other similarly named sites, accounts or projects, including projects named "a402" on other chains.
|
|
7
|
+
|
|
8
|
+
> 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.
|
|
9
|
+
> 공개 온체인 데이터에 따른 사실 정보이며 투자 권유가 아닙니다.
|
|
10
|
+
|
|
11
|
+
## What it does
|
|
12
|
+
- Builds x402 v2 `exact` payment requirements per request with the official `@x402/core` `x402ResourceServer` (USDC, plus A402 when it can be offered).
|
|
13
|
+
- 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**.
|
|
14
|
+
- 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).
|
|
15
|
+
- Keeps a ledger so a payment cannot be used twice.
|
|
16
|
+
- Rechecks the settlement transaction on chain (amount received by your address).
|
|
17
|
+
- 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).
|
|
18
|
+
|
|
19
|
+
## What it does not do
|
|
20
|
+
- It **does not judge, score or rate tokens** and gives no investment advice.
|
|
21
|
+
- It **does not operate a facilitator.** Verification and settlement are done by the external facilitators you configure.
|
|
22
|
+
- It **does not hold funds.** Payments go from the buyer's wallet directly to your receiving address.
|
|
23
|
+
- It **does not exchange** currencies. The A402 rate is used only to compute the A402 amount; there is no A402 ↔ USDC conversion.
|
|
24
|
+
- 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.
|
|
25
|
+
|
|
26
|
+
## A402 option
|
|
27
|
+
A402 is offered only when all of these hold for the request:
|
|
28
|
+
1. The selected facilitator is configured to accept A402.
|
|
29
|
+
2. Your receiving address has an A402 (Token-2022) token account. `exact` payments do not create the receiving account; create it in advance. The same applies to USDC.
|
|
30
|
+
3. The day's A402 rate is available. The rate is the median of the previous UTC day's hourly samples (Meteora DAMM v2 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, or the max/min ratio exceeded 1.5. These thresholds are configurable.
|
|
31
|
+
|
|
32
|
+
When A402 is not offered, the 402 response lists it under `notOffered` with the reason.
|
|
33
|
+
|
|
34
|
+
**Units.** As in every x402 requirement, `amount` is in the token's smallest unit. USDC and A402 both have 6 decimals: 1 USDC = 1,000,000 smallest units, 1 A402 = 1,000,000 smallest units. For example, an A402 `amount` of `140000000000` is 140,000 A402. The A402 amount is `priceUsd × (1 − discountPercent / 100) ÷ (A402 rate in USD)`, rounded up to the smallest unit.
|
|
35
|
+
|
|
36
|
+
## Facilitators (facts as checked on Solana mainnet, 2026-11-19)
|
|
37
|
+
| Facilitator | USDC `exact` | A402 (Token-2022) `exact` |
|
|
38
|
+
|---|---|---|
|
|
39
|
+
| PayAI `https://facilitator.payai.network` | verify and settle succeeded | verify and settle succeeded (fee paid by the facilitator's fee payer) |
|
|
40
|
+
| 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) |
|
|
41
|
+
|
|
42
|
+
These are observations from one day. Facilitator policies and balances change; `KNOWN_FACILITATORS` only provides defaults that you can override.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
```bash
|
|
46
|
+
npm install @agent402-dev/pay-server
|
|
47
|
+
```
|
|
48
|
+
Node 20+ or Cloudflare Workers (`nodejs_compat`). ESM only.
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
```ts
|
|
52
|
+
import { createPaymentGate, rpcChain, KNOWN_FACILITATORS, SOLANA_MAINNET, USDC_MAINNET, A402_MAINNET,
|
|
53
|
+
createRateBook, memoryRateStore } from '@agent402-dev/pay-server';
|
|
54
|
+
|
|
55
|
+
const rates = createRateBook({ store: memoryRateStore(), fetcher: rpcChain(RPC_URL).accounts });
|
|
56
|
+
const gate = createPaymentGate({
|
|
57
|
+
network: SOLANA_MAINNET,
|
|
58
|
+
payTo: 'YOUR_RECEIVING_ADDRESS',
|
|
59
|
+
priceUsd: 0.02, // example setting
|
|
60
|
+
usdc: USDC_MAINNET,
|
|
61
|
+
a402: { asset: A402_MAINNET, discountPercent: 30 /* example setting — choose your own */, rate: () => rates.today() },
|
|
62
|
+
facilitators: [KNOWN_FACILITATORS.payai, KNOWN_FACILITATORS.dexter],
|
|
63
|
+
chain: rpcChain(RPC_URL),
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
export default {
|
|
67
|
+
fetch: gate.withPayment(async (req) => new Response(JSON.stringify({ hello: 'paid world' }))),
|
|
68
|
+
};
|
|
69
|
+
// call rates.record() hourly (cron) to collect samples
|
|
70
|
+
```
|
|
71
|
+
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).
|
|
72
|
+
|
|
73
|
+
## License
|
|
74
|
+
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).
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
Factual information from public on-chain data. Not investment advice. / 공개 온체인 데이터에 따른 사실 정보이며 투자 권유가 아닙니다.
|
package/dist/chain.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** 정산 확인에 필요한 트랜잭션 정보 */
|
|
2
|
+
export interface ChainTx {
|
|
3
|
+
signature: string;
|
|
4
|
+
err: boolean;
|
|
5
|
+
/** 0번 = 수수료 낸 주소 */
|
|
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
|
+
/** 트랜잭션의 모든 서명 (구매자 서명 찾기용) */
|
|
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
|
+
/** 이 결제 수단의 수령 주소 증가량 (수령 주소가 소유한 그 민트 토큰 계정 합) */
|
|
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
|
+
/** JSON-RPC 로 ChainReader 만들기. RPC 주소(키 포함일 수 있음)는 오류 메시지에 넣지 않음 */
|
|
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
|
+
/** 연결 토큰 계정(ATA) 주소 */
|
|
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
|
+
// SDK 가 체인에서 읽는 것 (점검 엔진에 기대지 않는 최소 구현). fetch 만 씀 → Cloudflare Workers·Node 모두.
|
|
2
|
+
// - 정산 트랜잭션 읽기 (수령 증가액 확인), 수령 토큰 계정의 최근 서명 (정산 결과를 모를 때 판정)
|
|
3
|
+
// - 계정 여러 개 읽기 (환율 기록·받는 쪽 토큰 계정 확인)
|
|
4
|
+
/** 이 결제 수단의 수령 주소 증가량 (수령 주소가 소유한 그 민트 토큰 계정 합) */
|
|
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
|
+
/** JSON-RPC 로 ChainReader 만들기. RPC 주소(키 포함일 수 있음)는 오류 메시지에 넣지 않음 */
|
|
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
|
+
// ---------- 주소 ----------
|
|
46
|
+
export const SPL_TOKEN = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
|
|
47
|
+
export const TOKEN_2022 = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';
|
|
48
|
+
const ATA_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
|
|
49
|
+
/** 연결 토큰 계정(ATA) 주소 */
|
|
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
|
+
/** facilitator 하나를 감싼 공식 리소스 서버 (그 facilitator 의 /supported 로 초기화) */
|
|
4
|
+
export declare function createCoreServer(client: FacilitatorClient, network: string): Promise<x402ResourceServer>;
|
|
5
|
+
/** 공식 매칭 규칙으로, 결제가 고른 조건(accepted)과 같은 지금 조건 */
|
|
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
|
+
/** 공식 서버로 결제 조건 만들기 (요청마다 결제 수단 목록은 호출자가 정함) */
|
|
13
|
+
export declare function buildCoreRequirements(server: x402ResourceServer, network: string, payTo: string, maxTimeoutSeconds: number, offers: CoreOffer[]): Promise<PaymentRequirements[]>;
|
|
14
|
+
/**
|
|
15
|
+
* 정산 예외에 facilitator 가 적어 보낸 실패 이유 (있으면). 기록·안내용일 뿐 — 실패 응답이어도 facilitator 가 tx 를 보낸 뒤
|
|
16
|
+
* 확정 대기 시간 초과로 실패를 돌려줄 수 있으므로, 결과는 언제나 체인에서 판정함
|
|
17
|
+
*/
|
|
18
|
+
export declare function settleFailureReason(e: unknown): string | null;
|
|
19
|
+
/** verify 예외가 "확실한 거절 응답"인지 (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
|
+
// 공식 @x402/core x402ResourceServer 위에 얹는 부분 (2주차 시제품).
|
|
2
|
+
// 공식 코드가 맡는 것: /supported 읽기, 결제 조건 만들기(parsePrice·feePayer·transactionVersions 채우기),
|
|
3
|
+
// 결제와 조건 맞추기(findMatchingRequirements), facilitator verify·settle 호출
|
|
4
|
+
// 우리가 맡는 것(x402.ts): facilitator 장애 시 예비로, 요청마다 결제 수단 고르기, 재사용 방지 장부, 체인 판정·재확인
|
|
5
|
+
import { x402ResourceServer } from '@x402/core/server';
|
|
6
|
+
import { ExactSvmScheme } from '@x402/svm/exact/server';
|
|
7
|
+
/** facilitator 하나를 감싼 공식 리소스 서버 (그 facilitator 의 /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
|
+
/** facilitator 없이 조건 맞추기만 하는 서버 (네트워크별 하나) */
|
|
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
|
+
/** 공식 매칭 규칙으로, 결제가 고른 조건(accepted)과 같은 지금 조건 */
|
|
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
|
+
/** 공식 서버로 결제 조건 만들기 (요청마다 결제 수단 목록은 호출자가 정함) */
|
|
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
|
+
* 정산 예외에 facilitator 가 적어 보낸 실패 이유 (있으면). 기록·안내용일 뿐 — 실패 응답이어도 facilitator 가 tx 를 보낸 뒤
|
|
44
|
+
* 확정 대기 시간 초과로 실패를 돌려줄 수 있으므로, 결과는 언제나 체인에서 판정함
|
|
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
|
+
/** verify 예외가 "확실한 거절 응답"인지 (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,101 @@
|
|
|
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
|
+
export type AssetSymbol = 'USDC' | 'A402';
|
|
7
|
+
export interface FacilitatorSpec {
|
|
8
|
+
name: string;
|
|
9
|
+
/** url 또는 client 중 하나 */
|
|
10
|
+
url?: string;
|
|
11
|
+
client?: FacilitatorClient;
|
|
12
|
+
/** 이 facilitator 가 받는 결제 자산. 받지 않는 자산은 402 에 넣지 않음 */
|
|
13
|
+
assets: AssetSymbol[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* 확인된 facilitator (2026-11-19 메인넷에서 verify·settle 로 확인한 사실 — docs: README "Facilitators").
|
|
17
|
+
* 정책·상태는 바뀔 수 있으므로 기본값일 뿐, 설정으로 덮어쓸 수 있음
|
|
18
|
+
*/
|
|
19
|
+
export declare const KNOWN_FACILITATORS: {
|
|
20
|
+
readonly payai: {
|
|
21
|
+
readonly name: "payai";
|
|
22
|
+
readonly url: "https://facilitator.payai.network";
|
|
23
|
+
readonly assets: AssetSymbol[];
|
|
24
|
+
};
|
|
25
|
+
readonly dexter: {
|
|
26
|
+
readonly name: "dexter";
|
|
27
|
+
readonly url: "https://x402.dexter.cash";
|
|
28
|
+
readonly assets: AssetSymbol[];
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
export declare const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
|
|
32
|
+
export declare const SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
|
|
33
|
+
export declare const USDC_MAINNET: Asset;
|
|
34
|
+
export declare const A402_MAINNET: Asset;
|
|
35
|
+
export interface GateConfig {
|
|
36
|
+
network: string;
|
|
37
|
+
/** 수령 지갑 공개 주소 */
|
|
38
|
+
payTo: string;
|
|
39
|
+
/** USDC 가격 (USD) */
|
|
40
|
+
priceUsd: number;
|
|
41
|
+
usdc: Asset;
|
|
42
|
+
/** A402 를 받을 때만. rate() 가 off 거나 실패하면 그 요청은 USDC 만 */
|
|
43
|
+
a402?: {
|
|
44
|
+
asset: Asset;
|
|
45
|
+
discountPercent: number;
|
|
46
|
+
rate: () => Promise<DailyRate | null>;
|
|
47
|
+
};
|
|
48
|
+
/** 앞이 기본, 뒤가 예비 */
|
|
49
|
+
facilitators: FacilitatorSpec[];
|
|
50
|
+
/** 체인 읽기 (정산 재확인·결과 모를 때 판정·수령 토큰 계정 확인) */
|
|
51
|
+
chain: ChainReader;
|
|
52
|
+
ledger?: X402Ledger;
|
|
53
|
+
/** 핸들러 제한 시간 — 넘으면 정산하지 않음 (기본 40초, 결제 트랜잭션 유효시간보다 짧게) */
|
|
54
|
+
handlerTimeoutMs?: number;
|
|
55
|
+
maxTimeoutSeconds?: number;
|
|
56
|
+
/** facilitator 쪽 문제(수수료 대납 주소 잔액 부족 등)로 verify 가 실패하면 이 시간 동안 그 facilitator 를 건너뜀 (기본 5분) */
|
|
57
|
+
facilitatorCooldownMs?: number;
|
|
58
|
+
/** 수령 토큰 계정 확인 캐시 (기본 10분) */
|
|
59
|
+
receivingCheckTtlMs?: number;
|
|
60
|
+
resource?: {
|
|
61
|
+
description?: string;
|
|
62
|
+
mimeType?: string;
|
|
63
|
+
serviceName?: string;
|
|
64
|
+
};
|
|
65
|
+
now?: () => number;
|
|
66
|
+
/** 체인 재확인 재시도 간격 (기본 1·2·4초) */
|
|
67
|
+
confirmDelaysMs?: number[];
|
|
68
|
+
}
|
|
69
|
+
export interface ReceivingAccount {
|
|
70
|
+
asset: AssetSymbol;
|
|
71
|
+
mint: string;
|
|
72
|
+
tokenAccount: string;
|
|
73
|
+
exists: boolean;
|
|
74
|
+
}
|
|
75
|
+
export interface PaymentInfo {
|
|
76
|
+
asset: string;
|
|
77
|
+
amount: string;
|
|
78
|
+
payTo: string;
|
|
79
|
+
network: string;
|
|
80
|
+
}
|
|
81
|
+
export interface PaymentGate {
|
|
82
|
+
/** 유료 핸들러 감싸기 */
|
|
83
|
+
withPayment(handler: (req: Request, payment: PaymentInfo) => Promise<Response>): (req: Request) => Promise<Response>;
|
|
84
|
+
/** 지금 402 에 넣을 결제 조건과 빠진 자산·이유 (확인용) */
|
|
85
|
+
quote(resourceUrl: string): Promise<{
|
|
86
|
+
accepts: PaymentRequirements[];
|
|
87
|
+
notOffered: {
|
|
88
|
+
asset: AssetSymbol;
|
|
89
|
+
reason: string;
|
|
90
|
+
}[];
|
|
91
|
+
facilitator: string;
|
|
92
|
+
} | null>;
|
|
93
|
+
/** 수령 지갑의 USDC·A402 토큰 계정이 있는지 (없으면 그 자산은 402 에 넣지 않음) */
|
|
94
|
+
checkReceivingAccounts(): Promise<ReceivingAccount[]>;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* verify 실패가 구매자 탓이 아니라 facilitator 쪽 문제인지 (수수료 대납 주소 = 트랜잭션 계정 0 의 잔액 부족 등).
|
|
98
|
+
* 2026-11-19 실제 사례: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
|
|
99
|
+
*/
|
|
100
|
+
export declare function isFacilitatorSideFailure(reason?: string, message?: string): boolean;
|
|
101
|
+
export declare function createPaymentGate(c: GateConfig): PaymentGate;
|