@resvary/circle 0.5.0-alpha.1

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,119 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including
45
+ the original version of the Work and any modifications or additions
46
+ to that Work or Derivative Works thereof, that is intentionally
47
+ submitted to the Licensor for inclusion in the Work.
48
+
49
+ "Contributor" shall mean Licensor and any individual or Legal Entity
50
+ on behalf of whom a Contribution has been received by the Licensor and
51
+ subsequently incorporated within the Work.
52
+
53
+ 2. Grant of Copyright License. Subject to the terms and conditions of
54
+ this License, each Contributor hereby grants to You a perpetual,
55
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
56
+ copyright license to reproduce, prepare Derivative Works of,
57
+ publicly display, publicly perform, sublicense, and distribute the
58
+ Work and such Derivative Works in Source or Object form.
59
+
60
+ 3. Grant of Patent License. Subject to the terms and conditions of
61
+ this License, each Contributor hereby grants to You a perpetual,
62
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
63
+ (except as stated in this section) patent license to make, have made,
64
+ use, offer to sell, sell, import, and otherwise transfer the Work.
65
+
66
+ 4. Redistribution. You may reproduce and distribute copies of the
67
+ Work or Derivative Works thereof in any medium, with or without
68
+ modifications, and in Source or Object form, provided that You
69
+ meet the following conditions:
70
+
71
+ (a) You must give any other recipients of the Work or
72
+ Derivative Works a copy of this License; and
73
+
74
+ (b) You must cause any modified files to carry prominent notices
75
+ stating that You changed the files; and
76
+
77
+ (c) You must retain, in the Source form of any Derivative Works
78
+ that You distribute, all copyright, patent, trademark, and
79
+ attribution notices from the Source form of the Work; and
80
+
81
+ (d) If the Work includes a "NOTICE" text file as part of its
82
+ distribution, then any Derivative Works that You distribute must
83
+ include a readable copy of the attribution notices contained
84
+ within such NOTICE file.
85
+
86
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
87
+ any Contribution intentionally submitted for inclusion in the Work
88
+ by You to the Licensor shall be under the terms and conditions of
89
+ this License, without any additional terms or conditions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor,
93
+ except as required for reasonable and customary use in describing the
94
+ origin of the Work.
95
+
96
+ 7. Disclaimer of Warranty. Unless required by applicable law or
97
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
98
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
99
+
100
+ 8. Limitation of Liability. In no event and under no legal theory shall
101
+ any Contributor be liable to You for damages arising from this License
102
+ or the use of the Work.
103
+
104
+ 9. Accepting Warranty or Additional Liability. You may choose to offer
105
+ additional warranty or liability obligations for a fee.
106
+
107
+ Copyright 2025 horn111
108
+
109
+ Licensed under the Apache License, Version 2.0 (the "License");
110
+ you may not use this file except in compliance with the License.
111
+ You may obtain a copy of the License at
112
+
113
+ http://www.apache.org/licenses/LICENSE-2.0
114
+
115
+ Unless required by applicable law or agreed to in writing, software
116
+ distributed under the License is distributed on an "AS IS" BASIS,
117
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
118
+ See the License for the specific language governing permissions and
119
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # @resvary/circle
2
+
3
+ Circle-native Testnet funding adapters for the Resvary prepaid credit ledger.
4
+
5
+ - `@resvary/circle/arc`: direct Arc USDC funding and durable worker exports.
6
+ - `@resvary/circle/nanopayments`: official Circle Gateway verify/settle adapter.
7
+ - `@resvary/circle/handlers`: framework-neutral, Next.js, and Express top-up handlers.
8
+ - `@resvary/circle/gateway`: Arc Testnet Gateway constants and supported-kind validation.
9
+
10
+ ```bash
11
+ npm install @resvary/sdk@alpha @resvary/circle@alpha
12
+ ```
13
+
14
+ Credits are granted only after a direct Arc proof or successful Gateway facilitator settlement. 0.4 is Testnet-only. See `docs/circle-gateway-funding.md` and `docs/funding-recovery.md`.
package/dist/arc.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { ArcCreditFunding, type ArcCreditFundingConfig, type ArcFundingRequest, } from '@resvary/sdk/funding/arc';
2
+ export { ArcFundingWorker, type ArcFundingWorkerConfig, type ArcFundingWorkerEvent, } from '@resvary/sdk/funding';
3
+ //# sourceMappingURL=arc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"arc.d.ts","sourceRoot":"","sources":["../src/arc.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,KAAK,sBAAsB,EAC3B,KAAK,iBAAiB,GACvB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EACL,gBAAgB,EAChB,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,GAC3B,MAAM,sBAAsB,CAAC"}
package/dist/arc.js ADDED
@@ -0,0 +1,3 @@
1
+ export { ArcCreditFunding, } from '@resvary/sdk/funding/arc';
2
+ export { ArcFundingWorker, } from '@resvary/sdk/funding';
3
+ //# sourceMappingURL=arc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"arc.js","sourceRoot":"","sources":["../src/arc.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,GAGjB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EACL,gBAAgB,GAGjB,MAAM,sBAAsB,CAAC"}
@@ -0,0 +1,32 @@
1
+ export declare const ARC_GATEWAY_TESTNET: {
2
+ readonly name: "arcTestnet";
3
+ readonly network: "eip155:5042002";
4
+ readonly chainId: 5042002;
5
+ readonly gatewayDomain: 26;
6
+ readonly rpcUrl: "https://rpc.testnet.arc.network";
7
+ readonly facilitatorUrl: "https://gateway-api-testnet.circle.com";
8
+ readonly usdcAddress: "0x3600000000000000000000000000000000000000";
9
+ readonly gatewayWallet: "0x0077777d7EBA4688BDeF3E311b846F25870A19B9";
10
+ readonly gatewayMinter: "0x0022222ABE238Cc2C7Bb1f21003F0a260052475B";
11
+ readonly scheme: "exact";
12
+ readonly requirementName: "GatewayWalletBatched";
13
+ readonly requirementVersion: "1";
14
+ readonly authorizationValiditySeconds: number;
15
+ };
16
+ export interface GatewaySupportedKind {
17
+ x402Version: number;
18
+ scheme: string;
19
+ network: string;
20
+ extra?: Record<string, unknown>;
21
+ }
22
+ export interface GatewaySupportedResponse {
23
+ kinds: GatewaySupportedKind[];
24
+ extensions: string[];
25
+ signers: Record<string, string[]>;
26
+ }
27
+ export declare function requireArcGatewayKind(supported: GatewaySupportedResponse): GatewaySupportedKind & {
28
+ extra: Record<string, unknown> & {
29
+ verifyingContract: string;
30
+ };
31
+ };
32
+ //# sourceMappingURL=gateway.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gateway.d.ts","sourceRoot":"","sources":["../src/gateway.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;CActB,CAAC;AAEX,MAAM,WAAW,oBAAoB;IACnC,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAED,MAAM,WAAW,wBAAwB;IACvC,KAAK,EAAE,oBAAoB,EAAE,CAAC;IAC9B,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;CACnC;AAED,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,wBAAwB,GAClC,oBAAoB,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG;QAAE,iBAAiB,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAc3F"}
@@ -0,0 +1,27 @@
1
+ import { CIRCLE_BATCHING_NAME, CIRCLE_BATCHING_SCHEME, CIRCLE_BATCHING_VERSION, GATEWAY_AUTH_VALIDITY_WINDOW_SECONDS, } from '@circle-fin/x402-batching';
2
+ export const ARC_GATEWAY_TESTNET = {
3
+ name: 'arcTestnet',
4
+ network: 'eip155:5042002',
5
+ chainId: 5_042_002,
6
+ gatewayDomain: 26,
7
+ rpcUrl: 'https://rpc.testnet.arc.network',
8
+ facilitatorUrl: 'https://gateway-api-testnet.circle.com',
9
+ usdcAddress: '0x3600000000000000000000000000000000000000',
10
+ gatewayWallet: '0x0077777d7EBA4688BDeF3E311b846F25870A19B9',
11
+ gatewayMinter: '0x0022222ABE238Cc2C7Bb1f21003F0a260052475B',
12
+ scheme: CIRCLE_BATCHING_SCHEME,
13
+ requirementName: CIRCLE_BATCHING_NAME,
14
+ requirementVersion: CIRCLE_BATCHING_VERSION,
15
+ authorizationValiditySeconds: GATEWAY_AUTH_VALIDITY_WINDOW_SECONDS,
16
+ };
17
+ export function requireArcGatewayKind(supported) {
18
+ const kind = supported.kinds.find((candidate) => candidate.x402Version === 2 &&
19
+ candidate.scheme === ARC_GATEWAY_TESTNET.scheme &&
20
+ candidate.network === ARC_GATEWAY_TESTNET.network &&
21
+ typeof candidate.extra?.verifyingContract === 'string');
22
+ if (!kind) {
23
+ throw new Error('Circle Gateway facilitator does not advertise Arc Testnet batching support');
24
+ }
25
+ return kind;
26
+ }
27
+ //# sourceMappingURL=gateway.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gateway.js","sourceRoot":"","sources":["../src/gateway.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,uBAAuB,EACvB,oCAAoC,GACrC,MAAM,2BAA2B,CAAC;AAEnC,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,IAAI,EAAE,YAAY;IAClB,OAAO,EAAE,gBAAgB;IACzB,OAAO,EAAE,SAAS;IAClB,aAAa,EAAE,EAAE;IACjB,MAAM,EAAE,iCAAiC;IACzC,cAAc,EAAE,wCAAwC;IACxD,WAAW,EAAE,4CAA4C;IACzD,aAAa,EAAE,4CAA4C;IAC3D,aAAa,EAAE,4CAA4C;IAC3D,MAAM,EAAE,sBAAsB;IAC9B,eAAe,EAAE,oBAAoB;IACrC,kBAAkB,EAAE,uBAAuB;IAC3C,4BAA4B,EAAE,oCAAoC;CAC1D,CAAC;AAeX,MAAM,UAAU,qBAAqB,CACnC,SAAmC;IAEnC,MAAM,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,IAAI,CAC/B,CAAC,SAAS,EAAE,EAAE,CACZ,SAAS,CAAC,WAAW,KAAK,CAAC;QAC3B,SAAS,CAAC,MAAM,KAAK,mBAAmB,CAAC,MAAM;QAC/C,SAAS,CAAC,OAAO,KAAK,mBAAmB,CAAC,OAAO;QACjD,OAAO,SAAS,CAAC,KAAK,EAAE,iBAAiB,KAAK,QAAQ,CACzD,CAAC;IACF,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;IAChG,CAAC;IACD,OAAO,IAEN,CAAC;AACJ,CAAC"}
@@ -0,0 +1,33 @@
1
+ import { GatewayNanopaymentFunding } from './nanopayments.js';
2
+ export interface GatewayTopUpRequest {
3
+ customerId: string;
4
+ amount: string;
5
+ idempotencyKey: string;
6
+ expectedPayer?: `0x${string}`;
7
+ metadata?: Record<string, unknown>;
8
+ }
9
+ export interface GatewayTopUpHandlerConfig {
10
+ funding: GatewayNanopaymentFunding;
11
+ enabled?: boolean | (() => boolean);
12
+ disabledMessage?: string;
13
+ resolveRequest(request: Request): GatewayTopUpRequest | Promise<GatewayTopUpRequest>;
14
+ }
15
+ export type GatewayTopUpHandler = (request: Request) => Promise<Response>;
16
+ export declare function createGatewayTopUpHandler(config: GatewayTopUpHandlerConfig): GatewayTopUpHandler;
17
+ export declare function createNextGatewayTopUpHandler(config: GatewayTopUpHandlerConfig): GatewayTopUpHandler;
18
+ export interface ExpressLikeRequest {
19
+ method?: string;
20
+ originalUrl?: string;
21
+ url?: string;
22
+ headers: Record<string, string | string[] | undefined>;
23
+ body?: unknown;
24
+ protocol?: string;
25
+ get?(name: string): string | undefined;
26
+ }
27
+ export interface ExpressLikeResponse {
28
+ status(code: number): ExpressLikeResponse;
29
+ setHeader(name: string, value: string): void;
30
+ json(body: unknown): void;
31
+ }
32
+ export declare function createExpressGatewayTopUpHandler(config: GatewayTopUpHandlerConfig): (request: ExpressLikeRequest, response: ExpressLikeResponse) => Promise<void>;
33
+ //# sourceMappingURL=handlers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handlers.d.ts","sourceRoot":"","sources":["../src/handlers.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EAG1B,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AAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7C,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC;CAC3B;AAED,wBAAgB,gCAAgC,CAC9C,MAAM,EAAE,yBAAyB,GAChC,CAAC,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,mBAAmB,KAAK,OAAO,CAAC,IAAI,CAAC,CAwB/E"}
@@ -0,0 +1,127 @@
1
+ import { createHash } from 'node:crypto';
2
+ export function createGatewayTopUpHandler(config) {
3
+ return async (request) => {
4
+ const enabled = typeof config.enabled === 'function' ? config.enabled() : (config.enabled ?? true);
5
+ if (!enabled) {
6
+ return Response.json({
7
+ error: config.disabledMessage ??
8
+ 'Circle Gateway Testnet top-up is disabled for this deployment',
9
+ }, {
10
+ status: 503,
11
+ headers: { 'cache-control': 'private, no-store' },
12
+ });
13
+ }
14
+ const paymentHeader = request.headers.get('payment-signature');
15
+ if (!paymentHeader) {
16
+ try {
17
+ const input = await config.resolveRequest(request);
18
+ const fundingRequest = await config.funding.createFundingRequest(input);
19
+ return Response.json({
20
+ error: 'Payment required',
21
+ fundingIntentId: fundingRequest.fundingIntent.id,
22
+ }, {
23
+ status: 402,
24
+ headers: {
25
+ 'payment-required': encodeHeader(fundingRequest.paymentRequired),
26
+ 'cache-control': 'private, no-store',
27
+ },
28
+ });
29
+ }
30
+ catch (error) {
31
+ return Response.json({ error: error instanceof Error ? error.message : 'Invalid Gateway top-up request' }, {
32
+ status: 400,
33
+ headers: { 'cache-control': 'private, no-store' },
34
+ });
35
+ }
36
+ }
37
+ try {
38
+ const paymentPayload = decodePaymentPayload(paymentHeader);
39
+ const fundingIntentId = paymentPayload.accepted?.extra?.resvaryFundingIntentId;
40
+ if (typeof fundingIntentId !== 'string' || fundingIntentId.length === 0) {
41
+ throw new Error('Payment payload has no Resvary funding intent binding');
42
+ }
43
+ const nonce = paymentPayload.payload?.authorization?.nonce;
44
+ const idempotencyKey = `gateway-http:${createHash('sha256')
45
+ .update(`${fundingIntentId}\0${String(nonce ?? '')}`)
46
+ .digest('hex')}`;
47
+ const result = await config.funding.verifySettleAndCredit({
48
+ fundingIntentId,
49
+ paymentPayload,
50
+ idempotencyKey,
51
+ metadata: { transport: 'x402-http' },
52
+ });
53
+ return fundingResultResponse(result);
54
+ }
55
+ catch (error) {
56
+ return Response.json({ error: error instanceof Error ? error.message : 'Gateway top-up failed' }, {
57
+ status: 409,
58
+ headers: { 'cache-control': 'private, no-store' },
59
+ });
60
+ }
61
+ };
62
+ }
63
+ export function createNextGatewayTopUpHandler(config) {
64
+ return createGatewayTopUpHandler(config);
65
+ }
66
+ export function createExpressGatewayTopUpHandler(config) {
67
+ const handler = createGatewayTopUpHandler(config);
68
+ return async (request, response) => {
69
+ const host = request.get?.('host') ?? firstHeader(request.headers.host) ?? 'localhost';
70
+ const protocol = request.protocol ?? 'http';
71
+ const url = new URL(request.originalUrl ?? request.url ?? '/', `${protocol}://${host}`);
72
+ const headers = new Headers();
73
+ for (const [name, value] of Object.entries(request.headers)) {
74
+ if (Array.isArray(value))
75
+ headers.set(name, value.join(', '));
76
+ else if (typeof value === 'string')
77
+ headers.set(name, value);
78
+ }
79
+ const method = request.method ?? 'POST';
80
+ const webRequest = new Request(url, {
81
+ method,
82
+ headers,
83
+ body: method === 'GET' || method === 'HEAD' || request.body === undefined
84
+ ? undefined
85
+ : JSON.stringify(request.body),
86
+ });
87
+ const result = await handler(webRequest);
88
+ result.headers.forEach((value, name) => response.setHeader(name, value));
89
+ response.status(result.status).json(await result.json());
90
+ };
91
+ }
92
+ function fundingResultResponse(result) {
93
+ const body = {
94
+ fundingIntent: result.fundingIntent,
95
+ fundingTransaction: result.fundingTransaction,
96
+ grant: result.grant,
97
+ balance: result.account,
98
+ replayed: result.replayed,
99
+ };
100
+ return Response.json(body, {
101
+ status: 200,
102
+ headers: {
103
+ 'payment-response': encodeHeader(result.settlement),
104
+ 'cache-control': 'private, no-store',
105
+ },
106
+ });
107
+ }
108
+ function decodePaymentPayload(header) {
109
+ let decoded;
110
+ try {
111
+ decoded = JSON.parse(Buffer.from(header, 'base64').toString('utf8'));
112
+ }
113
+ catch {
114
+ throw new Error('Payment-Signature is not valid base64 JSON');
115
+ }
116
+ if (!decoded || typeof decoded !== 'object') {
117
+ throw new Error('Payment-Signature payload must be an object');
118
+ }
119
+ return decoded;
120
+ }
121
+ function encodeHeader(value) {
122
+ return Buffer.from(JSON.stringify(value)).toString('base64');
123
+ }
124
+ function firstHeader(value) {
125
+ return Array.isArray(value) ? value[0] : value;
126
+ }
127
+ //# sourceMappingURL=handlers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handlers.js","sourceRoot":"","sources":["../src/handlers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAwBzC,MAAM,UAAU,yBAAyB,CAAC,MAAiC;IACzE,OAAO,KAAK,EAAE,OAAO,EAAE,EAAE;QACvB,MAAM,OAAO,GACX,OAAO,MAAM,CAAC,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC;QACrF,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,QAAQ,CAAC,IAAI,CAClB;gBACE,KAAK,EACH,MAAM,CAAC,eAAe;oBACtB,+DAA+D;aAClE,EACD;gBACE,MAAM,EAAE,GAAG;gBACX,OAAO,EAAE,EAAE,eAAe,EAAE,mBAAmB,EAAE;aAClD,CACF,CAAC;QACJ,CAAC;QAED,MAAM,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;QAC/D,IAAI,CAAC,aAAa,EAAE,CAAC;YACnB,IAAI,CAAC;gBACH,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;gBACnD,MAAM,cAAc,GA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AQ;KAC1B,CAAC;IACF,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE;QACzB,MAAM,EAAE,GAAG;QACX,OAAO,EAAE;YACP,kBAAkB,EAAE,YAAY,CAAC,MAAM,CAAC,UAAU,CAAC;YACnD,eAAe,EAAE,mBAAmB;SACrC;KACF,CAAC,CAAC;AACL,CAAC;AAED,SAAS,oBAAoB,CAAC,MAAc;IAC1C,IAAI,OAAgB,CAAC;IACrB,IAAI,CAAC;QACH,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IACvE,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAChE,CAAC;IACD,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAC5C,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;IACjE,CAAC;IACD,OAAO,OAAgC,CAAC;AAC1C,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,WAAW,CAAC,KAAoC;IACvD,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AACjD,CAAC"}
@@ -0,0 +1,5 @@
1
+ export * from './arc.js';
2
+ export * from './gateway.js';
3
+ export * from './nanopayments.js';
4
+ export * from './handlers.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './arc.js';
2
+ export * from './gateway.js';
3
+ export * from './nanopayments.js';
4
+ export * from './handlers.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC"}
@@ -0,0 +1,119 @@
1
+ import type { CreditAccount, CreditGrant, CreditLedger, FundingIntent, FundingTransaction } from '@resvary/sdk/credits';
2
+ import { type GatewaySupportedResponse } from './gateway.js';
3
+ export interface GatewayPaymentRequirements {
4
+ scheme: string;
5
+ network: string;
6
+ asset: string;
7
+ amount: string;
8
+ payTo: string;
9
+ maxTimeoutSeconds: number;
10
+ extra: Record<string, unknown>;
11
+ }
12
+ export interface GatewayPaymentPayload {
13
+ x402Version: number;
14
+ resource?: {
15
+ url: string;
16
+ description?: string;
17
+ mimeType?: string;
18
+ [key: string]: unknown;
19
+ };
20
+ accepted: GatewayPaymentRequirements;
21
+ payload: {
22
+ signature?: string;
23
+ authorization?: {
24
+ from?: string;
25
+ to?: string;
26
+ value?: string;
27
+ validAfter?: string;
28
+ validBefore?: string;
29
+ nonce?: string;
30
+ [key: string]: unknown;
31
+ };
32
+ [key: string]: unknown;
33
+ };
34
+ extensions?: Record<string, unknown>;
35
+ }
36
+ export interface GatewayVerifyResponse {
37
+ isValid: boolean;
38
+ invalidReason?: string;
39
+ invalidMessage?: string;
40
+ payer?: string;
41
+ }
42
+ export interface GatewaySettleResponse {
43
+ success: boolean;
44
+ errorReason?: string;
45
+ errorMessage?: string;
46
+ payer?: string;
47
+ transaction: string;
48
+ network: string;
49
+ amount?: string;
50
+ }
51
+ export interface GatewayFacilitator {
52
+ getSupported(): Promise<GatewaySupportedResponse>;
53
+ verify(paymentPayload: GatewayPaymentPayload, requirements: GatewayPaymentRequirements): Promise<GatewayVerifyResponse>;
54
+ settle(paymentPayload: GatewayPaymentPayload, requirements: GatewayPaymentRequirements): Promise<GatewaySettleResponse>;
55
+ }
56
+ export interface GatewayNanopaymentFundingConfig {
57
+ ledger: CreditLedger;
58
+ sellerAddress: `0x${string}`;
59
+ facilitator?: GatewayFacilitator;
60
+ facilitatorUrl?: string;
61
+ resourceUrl?: string;
62
+ intentTtlMs?: number;
63
+ now?: () => number;
64
+ }
65
+ export interface CreateGatewayFundingRequestInput {
66
+ customerId: string;
67
+ amount: string;
68
+ idempotencyKey: string;
69
+ expectedPayer?: `0x${string}`;
70
+ metadata?: Record<string, unknown>;
71
+ }
72
+ export interface GatewayFundingRequest {
73
+ fundingIntent: FundingIntent;
74
+ paymentRequired: {
75
+ x402Version: 2;
76
+ resource: {
77
+ url: string;
78
+ description: string;
79
+ mimeType: 'application/json';
80
+ };
81
+ accepts: [GatewayPaymentRequirements];
82
+ extensions: {
83
+ resvary: {
84
+ fundingIntentId: string;
85
+ };
86
+ };
87
+ };
88
+ }
89
+ export interface VerifySettleAndCreditInput {
90
+ fundingIntentId: string;
91
+ paymentPayload: GatewayPaymentPayload;
92
+ idempotencyKey: string;
93
+ metadata?: Record<string, unknown>;
94
+ }
95
+ export interface GatewayFundingResult {
96
+ account: CreditAccount;
97
+ grant: CreditGrant;
98
+ fundingIntent: FundingIntent;
99
+ fundingTransaction: FundingTransaction;
100
+ verification: GatewayVerifyResponse;
101
+ settlement: GatewaySettleResponse;
102
+ replayed: boolean;
103
+ }
104
+ export declare class GatewayNanopaymentFunding {
105
+ private readonly ledger;
106
+ private readonly sellerAddress;
107
+ private readonly facilitator;
108
+ private readonly paymentScheme;
109
+ private readonly resourceUrl;
110
+ private readonly intentTtlMs;
111
+ private readonly now;
112
+ constructor(config: GatewayNanopaymentFundingConfig);
113
+ createFundingRequest(input: CreateGatewayFundingRequestInput): Promise<GatewayFundingRequest>;
114
+ verifySettleAndCredit(input: VerifySettleAndCreditInput): Promise<GatewayFundingResult>;
115
+ markReconciliationRequired(fundingTransactionId: string, reason: string, idempotencyKey: string): Promise<FundingTransaction>;
116
+ private buildRequirements;
117
+ private replayResult;
118
+ }
119
+ //# sourceMappingURL=nanopayments.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nanopayments.d.ts","sourceRoot":"","sources":["../src/nanopayments.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EACX,YAAY,EACZ,aAAa,EACb,kBAAkB,EACnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAGL,KAAK,wBAAwB,EAC9B,MAAM,cAAc,CAAC;AAEtB,MAAM,WAAW,0BAA0B;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,iBAAiB,EAAE,MAAM,CAAC;IAC1B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC;AAED,MAAM,WAAW,qBAAqB;IACpC,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE;QACT,GAAG,EAAE,MAAM,CAAC;QACZ,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;KACxB,CAAC;IACF,QAAQ,EAAE,0BAA0B,CAAC;IACrC,OAAO,EAAE;QACP,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,aAAa,CAAC,EAAE;YACd,IAAI,CAAC,EAAE,MAAM,CAAC;YACd,EAAE,CAAC,EAAE,MAAM,CAAC;YACZ,KAAK,CAAC,EAAE,MAAM,CAAC;YACf,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Aa,CAAgB;IAC9C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAqB;IACjD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA0B;IACxD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAe;gBAEvB,MAAM,EAAE,+BAA+B;IAiB7C,oBAAoB,CACxB,KAAK,EAAE,gCAAgC,GACtC,OAAO,CAAC,qBAAqB,CAAC;IAmC3B,qBAAqB,CAAC,KAAK,EAAE,0BAA0B,GAAG,OAAO,CAAC,oBAAoB,CAAC;IA8FvF,0BAA0B,CAC9B,oBAAoB,EAAE,MAAM,EAC5B,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,kBAAkB,CAAC;YAShB,iBAAiB;YAiCjB,YAAY;CA0B3B"}
@@ -0,0 +1,295 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { BatchFacilitatorClient, GatewayEvmScheme } from '@circle-fin/x402-batching/server';
3
+ import { CIRCLE_BATCHING_NAME, CIRCLE_BATCHING_SCHEME, CIRCLE_BATCHING_VERSION, } from '@circle-fin/x402-batching';
4
+ import { ARC_GATEWAY_TESTNET, requireArcGatewayKind, } from './gateway.js';
5
+ export class GatewayNanopaymentFunding {
6
+ ledger;
7
+ sellerAddress;
8
+ facilitator;
9
+ paymentScheme = new GatewayEvmScheme();
10
+ resourceUrl;
11
+ intentTtlMs;
12
+ now;
13
+ constructor(config) {
14
+ this.ledger = config.ledger;
15
+ this.sellerAddress = normalizeAddress(config.sellerAddress, 'sellerAddress');
16
+ this.facilitator =
17
+ config.facilitator ??
18
+ new BatchFacilitatorClient({
19
+ url: config.facilitatorUrl ?? ARC_GATEWAY_TESTNET.facilitatorUrl,
20
+ });
21
+ this.resourceUrl = config.resourceUrl ?? '/api/credits/gateway';
22
+ this.intentTtlMs =
23
+ config.intentTtlMs ?? ARC_GATEWAY_TESTNET.authorizationValiditySeconds * 1_000;
24
+ this.now = config.now ?? Date.now;
25
+ if (!Number.isSafeInteger(this.intentTtlMs) || this.intentTtlMs <= 0) {
26
+ throw new Error('intentTtlMs must be a positive integer');
27
+ }
28
+ }
29
+ async createFundingRequest(input) {
30
+ const expiresAt = this.now() + this.intentTtlMs;
31
+ const fundingIntent = await this.ledger.createFundingIntent({
32
+ customerId: input.customerId,
33
+ amount: input.amount,
34
+ rail: 'circle_gateway_nanopayment',
35
+ network: ARC_GATEWAY_TESTNET.network,
36
+ invoiceId: `gateway:${input.idempotencyKey}`,
37
+ expiresAt,
38
+ idempotencyKey: input.idempotencyKey,
39
+ metadata: {
40
+ ...input.metadata,
41
+ expectedPayer: input.expectedPayer?.toLowerCase(),
42
+ },
43
+ });
44
+ const requirements = await this.buildRequirements(fundingIntent);
45
+ return {
46
+ fundingIntent,
47
+ paymentRequired: {
48
+ x402Version: 2,
49
+ resource: {
50
+ url: this.resourceUrl,
51
+ description: `Fund Resvary credits for ${input.customerId}`,
52
+ mimeType: 'application/json',
53
+ },
54
+ accepts: [requirements],
55
+ extensions: {
56
+ resvary: {
57
+ fundingIntentId: fundingIntent.id,
58
+ },
59
+ },
60
+ },
61
+ };
62
+ }
63
+ async verifySettleAndCredit(input) {
64
+ const intent = await this.ledger.getFundingIntent(input.fundingIntentId);
65
+ if (!intent || intent.rail !== 'circle_gateway_nanopayment') {
66
+ throw new Error(`Gateway funding intent not found: ${input.fundingIntentId}`);
67
+ }
68
+ if (intent.status === 'failed') {
69
+ throw new Error(`Gateway funding intent is failed: ${intent.id}`);
70
+ }
71
+ const authorization = requireAuthorization(input.paymentPayload);
72
+ const authorizationHash = hashAuthorization(input.paymentPayload, input.paymentPayload.accepted);
73
+ const existing = await this.ledger.store.getFundingTransactionByExternalPayment('circle_gateway_nanopayment', ARC_GATEWAY_TESTNET.network, authorizationHash);
74
+ if (existing) {
75
+ if (existing.fundingIntentId !== intent.id) {
76
+ throw new Error('Gateway authorization is already assigned to another funding intent');
77
+ }
78
+ return this.replayResult(existing);
79
+ }
80
+ const requirements = await this.buildRequirements(intent);
81
+ validatePayload(intent, requirements, input.paymentPayload, this.sellerAddress, this.now());
82
+ const verification = await this.facilitator.verify(input.paymentPayload, requirements);
83
+ if (!verification.isValid) {
84
+ throw new Error(`Circle Gateway verification failed: ${verification.invalidReason ?? verification.invalidMessage ?? 'unknown reason'}`);
85
+ }
86
+ const payer = normalizeAddress(verification.payer ?? authorization.from, 'verified payer');
87
+ validateExpectedPayer(intent, payer);
88
+ const settlement = await this.facilitator.settle(input.paymentPayload, requirements);
89
+ if (!settlement.success) {
90
+ throw new Error(`Circle Gateway settlement failed: ${settlement.errorReason ?? settlement.errorMessage ?? 'unknown reason'}`);
91
+ }
92
+ if (settlement.network !== ARC_GATEWAY_TESTNET.network) {
93
+ throw new Error(`Gateway settled on unexpected network: ${settlement.network}`);
94
+ }
95
+ if (settlement.amount !== undefined && settlement.amount !== intent.requestedUnits) {
96
+ throw new Error(`Gateway settled amount mismatch: ${settlement.amount} !== ${intent.requestedUnits}`);
97
+ }
98
+ const credited = await this.ledger.confirmFunding({
99
+ fundingIntentId: intent.id,
100
+ rail: 'circle_gateway_nanopayment',
101
+ network: ARC_GATEWAY_TESTNET.network,
102
+ externalPaymentId: authorizationHash,
103
+ txHash: isHexTransaction(settlement.transaction)
104
+ ? settlement.transaction
105
+ : undefined,
106
+ amount: intent.requestedAmount,
107
+ paymentReceiptId: `circle-gateway:${authorizationHash}`,
108
+ payer,
109
+ settlementStatus: 'settled',
110
+ settledAt: this.now(),
111
+ requireExactAmount: true,
112
+ evidence: {
113
+ authorizationHash,
114
+ nonce: authorization.nonce,
115
+ payer,
116
+ recipient: this.sellerAddress,
117
+ facilitatorReference: settlement.transaction,
118
+ metadata: {
119
+ gatewayDomain: ARC_GATEWAY_TESTNET.gatewayDomain,
120
+ verifyingContract: requirements.extra.verifyingContract,
121
+ },
122
+ },
123
+ idempotencyKey: input.idempotencyKey,
124
+ metadata: input.metadata,
125
+ });
126
+ return {
127
+ ...credited,
128
+ verification,
129
+ settlement,
130
+ replayed: false,
131
+ };
132
+ }
133
+ async markReconciliationRequired(fundingTransactionId, reason, idempotencyKey) {
134
+ return this.ledger.updateFundingSettlement({
135
+ fundingTransactionId,
136
+ status: 'reconciliation_required',
137
+ reason,
138
+ idempotencyKey,
139
+ });
140
+ }
141
+ async buildRequirements(intent) {
142
+ const supported = await this.facilitator.getSupported();
143
+ const kind = requireArcGatewayKind(supported);
144
+ const baseRequirements = {
145
+ scheme: CIRCLE_BATCHING_SCHEME,
146
+ network: ARC_GATEWAY_TESTNET.network,
147
+ asset: ARC_GATEWAY_TESTNET.usdcAddress,
148
+ amount: intent.requestedUnits,
149
+ payTo: this.sellerAddress,
150
+ maxTimeoutSeconds: ARC_GATEWAY_TESTNET.authorizationValiditySeconds,
151
+ extra: {
152
+ name: CIRCLE_BATCHING_NAME,
153
+ version: CIRCLE_BATCHING_VERSION,
154
+ resvaryFundingIntentId: intent.id,
155
+ },
156
+ };
157
+ const enhanced = await this.paymentScheme.enhancePaymentRequirements(baseRequirements, {
158
+ ...kind,
159
+ network: kind.network,
160
+ }, supported.extensions);
161
+ return {
162
+ ...enhanced,
163
+ extra: {
164
+ ...enhanced.extra,
165
+ resvaryFundingIntentId: intent.id,
166
+ },
167
+ };
168
+ }
169
+ async replayResult(transaction) {
170
+ const intent = await this.ledger.getFundingIntent(transaction.fundingIntentId);
171
+ const account = await this.ledger.store.getAccount(transaction.accountId);
172
+ const grant = await this.ledger.store.getGrant(transaction.grantId);
173
+ if (!intent || !account || !grant) {
174
+ throw new Error('Stored Gateway funding replay is incomplete');
175
+ }
176
+ return {
177
+ account,
178
+ grant,
179
+ fundingIntent: intent,
180
+ fundingTransaction: transaction,
181
+ verification: {
182
+ isValid: true,
183
+ payer: transaction.payer,
184
+ },
185
+ settlement: {
186
+ success: transaction.settlementStatus === 'settled',
187
+ payer: transaction.payer,
188
+ transaction: transaction.evidence?.facilitatorReference ?? transaction.externalPaymentId,
189
+ network: transaction.network,
190
+ amount: transaction.amountUnits,
191
+ },
192
+ replayed: true,
193
+ };
194
+ }
195
+ }
196
+ function validatePayload(intent, requirements, payload, sellerAddress, now) {
197
+ if (payload.x402Version !== 2)
198
+ throw new Error('Gateway payment must use x402 version 2');
199
+ const accepted = payload.accepted;
200
+ if (!accepted)
201
+ throw new Error('Gateway payment is missing accepted requirements');
202
+ if (accepted.scheme !== CIRCLE_BATCHING_SCHEME)
203
+ throw new Error(`Unsupported Gateway scheme: ${accepted.scheme}`);
204
+ if (accepted.network !== ARC_GATEWAY_TESTNET.network)
205
+ throw new Error(`Unsupported Gateway network: ${accepted.network}`);
206
+ if (accepted.asset.toLowerCase() !== ARC_GATEWAY_TESTNET.usdcAddress.toLowerCase())
207
+ throw new Error('Gateway payment asset is not Arc Testnet USDC');
208
+ if (accepted.payTo.toLowerCase() !== sellerAddress.toLowerCase())
209
+ throw new Error('Gateway payment recipient does not match the seller');
210
+ if (accepted.amount !== intent.requestedUnits)
211
+ throw new Error(`Gateway payment amount mismatch: ${accepted.amount} !== ${intent.requestedUnits}`);
212
+ if (accepted.extra?.name !== CIRCLE_BATCHING_NAME)
213
+ throw new Error('Gateway batching name is invalid');
214
+ if (accepted.extra?.version !== CIRCLE_BATCHING_VERSION)
215
+ throw new Error('Gateway batching version is invalid');
216
+ if (accepted.extra?.resvaryFundingIntentId !== intent.id)
217
+ throw new Error('Gateway payment is not bound to this funding intent');
218
+ if (!sameRequirements(accepted, requirements))
219
+ throw new Error('Gateway accepted requirements differ from the funding request');
220
+ const authorization = requireAuthorization(payload);
221
+ if (authorization.to.toLowerCase() !== sellerAddress.toLowerCase())
222
+ throw new Error('Gateway authorization recipient does not match the seller');
223
+ if (authorization.value !== intent.requestedUnits)
224
+ throw new Error('Gateway authorization amount must equal the funding intent amount');
225
+ if (!/^0x[0-9a-fA-F]{64}$/.test(authorization.nonce))
226
+ throw new Error('Gateway authorization nonce must be a 32-byte hex value');
227
+ const validBeforeMs = Number(BigInt(authorization.validBefore)) * 1_000;
228
+ const validAfterMs = Number(BigInt(authorization.validAfter)) * 1_000;
229
+ if (!Number.isSafeInteger(validBeforeMs) || validBeforeMs <= now)
230
+ throw new Error('Gateway authorization is expired');
231
+ if (!Number.isSafeInteger(validAfterMs) || validAfterMs > now)
232
+ throw new Error('Gateway authorization is not valid yet');
233
+ if (intent.expiresAt !== undefined && intent.expiresAt <= now)
234
+ throw new Error('Gateway funding intent is expired');
235
+ }
236
+ function requireAuthorization(payload) {
237
+ const authorization = payload.payload?.authorization;
238
+ if (!authorization)
239
+ throw new Error('Gateway payment is missing authorization');
240
+ for (const key of ['from', 'to', 'value', 'validAfter', 'validBefore', 'nonce']) {
241
+ if (typeof authorization[key] !== 'string' || authorization[key].length === 0) {
242
+ throw new Error(`Gateway authorization is missing ${key}`);
243
+ }
244
+ }
245
+ normalizeAddress(authorization.from, 'authorization.from');
246
+ normalizeAddress(authorization.to, 'authorization.to');
247
+ return authorization;
248
+ }
249
+ function validateExpectedPayer(intent, payer) {
250
+ const expected = intent.metadata?.expectedPayer;
251
+ if (typeof expected === 'string' && expected.toLowerCase() !== payer.toLowerCase()) {
252
+ throw new Error('Verified Gateway payer does not match the funding intent');
253
+ }
254
+ }
255
+ function sameRequirements(left, right) {
256
+ return (left.scheme === right.scheme &&
257
+ left.network === right.network &&
258
+ left.asset.toLowerCase() === right.asset.toLowerCase() &&
259
+ left.amount === right.amount &&
260
+ left.payTo.toLowerCase() === right.payTo.toLowerCase() &&
261
+ left.maxTimeoutSeconds === right.maxTimeoutSeconds &&
262
+ left.extra?.name === right.extra?.name &&
263
+ left.extra?.version === right.extra?.version &&
264
+ left.extra?.verifyingContract === right.extra?.verifyingContract &&
265
+ left.extra?.resvaryFundingIntentId === right.extra?.resvaryFundingIntentId);
266
+ }
267
+ function hashAuthorization(payload, requirements) {
268
+ const authorization = requireAuthorization(payload);
269
+ const canonical = JSON.stringify({
270
+ x402Version: payload.x402Version,
271
+ scheme: requirements.scheme,
272
+ network: requirements.network,
273
+ asset: requirements.asset.toLowerCase(),
274
+ payTo: requirements.payTo.toLowerCase(),
275
+ authorization: {
276
+ from: authorization.from.toLowerCase(),
277
+ to: authorization.to.toLowerCase(),
278
+ value: authorization.value,
279
+ validAfter: authorization.validAfter,
280
+ validBefore: authorization.validBefore,
281
+ nonce: authorization.nonce.toLowerCase(),
282
+ },
283
+ });
284
+ return `0x${createHash('sha256').update(canonical).digest('hex')}`;
285
+ }
286
+ function normalizeAddress(value, field) {
287
+ if (!/^0x[0-9a-fA-F]{40}$/.test(value)) {
288
+ throw new Error(`${field} must be an EVM address`);
289
+ }
290
+ return value.toLowerCase();
291
+ }
292
+ function isHexTransaction(value) {
293
+ return /^0x[0-9a-fA-F]{64}$/.test(value);
294
+ }
295
+ //# sourceMappingURL=nanopayments.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nanopayments.js","sourceRoot":"","sources":["../src/nanopayments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAE5F,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,2BAA2B,CAAC;AAQnC,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GAEtB,MAAM,cAAc,CAAC;AAuHtB,MAAM,OAAO,yBAAyB;IACnB,MAAM,CAAe;IACrB,aAAa,CAAgB;IAC7B,WAAW,CAAqB;IAChC,aAAa,GAAG,IAAI,gBAAgB,EAAE,CAAC;IACvC,WAAW,CAAS;IACpB,WAAW,CAAS;IACpB,GAAG,CAAe;IAEnC,YAAY,MAAuC;QACjD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;QAC5B,IAAI,CAAC,aAAa,GAAG,gBAAgB,CAAC,MAAM,CAAC,aAAa,EAAE,eAAe,CAAC,C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arc and Gateway funding adapters for Resvary prepaid credits",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./arc": {
14
+ "types": "./dist/arc.d.ts",
15
+ "import": "./dist/arc.js"
16
+ },
17
+ "./gateway": {
18
+ "types": "./dist/gateway.d.ts",
19
+ "import": "./dist/gateway.js"
20
+ },
21
+ "./nanopayments": {
22
+ "types": "./dist/nanopayments.d.ts",
23
+ "import": "./dist/nanopayments.js"
24
+ },
25
+ "./handlers": {
26
+ "types": "./dist/handlers.d.ts",
27
+ "import": "./dist/handlers.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "tag": "alpha"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc",
41
+ "dev": "tsc --watch",
42
+ "clean": "node -e \"const fs=require('node:fs');fs.rmSync('dist',{recursive:true,force:true});fs.rmSync('tsconfig.tsbuildinfo',{force:true})\"",
43
+ "test": "vitest run src",
44
+ "typecheck": "tsc --noEmit"
45
+ },
46
+ "keywords": [
47
+ "circle",
48
+ "arc",
49
+ "gateway",
50
+ "nanopayments",
51
+ "x402",
52
+ "prepaid-credits"
53
+ ],
54
+ "author": "horn111",
55
+ "license": "Apache-2.0",
56
+ "repository": {
57
+ "type": "git",
58
+ "url": "https://github.com/horn111/resvary.git",
59
+ "directory": "packages/circle"
60
+ },
61
+ "dependencies": {
62
+ "@circle-fin/x402-batching": "^3.3.0",
63
+ "@resvary/sdk": "0.5.0-alpha.1",
64
+ "@x402/core": "^2.23.0",
65
+ "@x402/evm": "^2.23.0",
66
+ "viem": "^2.55.19"
67
+ },
68
+ "devDependencies": {
69
+ "typescript": "^5.6.0",
70
+ "vitest": "^4.1.10"
71
+ }
72
+ }