@lacasoft/openrelay-sdk 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 ADDED
@@ -0,0 +1,118 @@
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 made available under
36
+ the License, as indicated by a copyright notice that is included
37
+ 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
42
+ transformations represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship submitted to the
45
+ Licensor for inclusion in the Work by the copyright owner or by an
46
+ individual or Legal Entity authorized to submit on behalf of the
47
+ copyright owner.
48
+
49
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
50
+ whom a Contribution has been received by the Licensor and included
51
+ 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
+ patent license to make, use, sell, offer for sale, import, and
64
+ 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, You must include
82
+ a readable copy of the attribution notices contained
83
+ within such NOTICE file.
84
+
85
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
86
+ any Contribution submitted for inclusion in the Work shall be under
87
+ the terms and conditions of this License, without any additional
88
+ terms or conditions.
89
+
90
+ 6. Trademarks. This License does not grant permission to use the trade
91
+ names, trademarks, service marks, or product names of the Licensor.
92
+
93
+ 7. Disclaimer of Warranty. Unless required by applicable law or
94
+ agreed to in writing, Licensor provides the Work on an "AS IS"
95
+ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
96
+
97
+ 8. Limitation of Liability. In no event and under no legal theory
98
+ shall any Contributor be liable for any damages arising from this
99
+ Work, including direct, indirect, special, incidental, or
100
+ consequential damages.
101
+
102
+ 9. Accepting Warranty or Additional Liability. While redistributing
103
+ the Work, You may offer acceptance of support, warranty, indemnity,
104
+ or other liability obligations consistent with this License.
105
+
106
+ END OF TERMS AND CONDITIONS
107
+
108
+ Copyright 2025 OpenRelay Contributors
109
+
110
+ Licensed under the Apache License, Version 2.0 (the "License");
111
+ you may not use this file except in compliance with the License.
112
+ You may obtain a copy of the License at
113
+
114
+ http://www.apache.org/licenses/LICENSE-2.0
115
+
116
+ Unless required by applicable law or agreed to in writing, software
117
+ distributed under the License is distributed on an "AS IS" BASIS,
118
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package/README.md ADDED
@@ -0,0 +1,135 @@
1
+ # @lacasoft/openrelay-sdk
2
+
3
+ The OpenRelay JavaScript/TypeScript SDK — **Stripe-compatible payments for the open web**.
4
+ Accept **USDC on Base** with no gatekeepers: gasless settlement (ERC-3009), webhooks, and
5
+ **x402** micropayments for AI agents. ~1% protocol fee (0.7% nodeit / 0.3% treasury), settled
6
+ trustlessly on-chain.
7
+
8
+ - ⛽ **Gasless for payers** — they sign an ERC-3009 authorization; the nodeit pays the gas.
9
+ - 🤖 **x402 micropayments** — charge $0.001 per request (Stripe can't; OpenRelay can).
10
+ - 🧩 **Stripe-like DX** — `paymentIntents.create`, `webhooks.verify`.
11
+ - 🌐 **Open network** — no lock-in, self-host or use any nodeit.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @lacasoft/openrelay-sdk
17
+ # pnpm add @lacasoft/openrelay-sdk · yarn add @lacasoft/openrelay-sdk
18
+ ```
19
+
20
+ > No need to clone the monorepo — `@lacasoft/openrelay-protocol` (types + constants) comes along
21
+ > automatically; `viem` is a dependency.
22
+
23
+ ## Quick start
24
+
25
+ ```typescript
26
+ import { OpenRelay } from '@lacasoft/openrelay-sdk'
27
+
28
+ // Use a SECRET key, server-side only — never ship it to the browser.
29
+ const relay = new OpenRelay({ apiKey: process.env.OPENRELAY_SECRET_KEY! })
30
+
31
+ // Create a charge — amounts are USDC base units (6 decimals → 1 USDC = 1_000_000).
32
+ const intent = await relay.paymentIntents.create({
33
+ amount: 10_000_000, // 10.00 USDC
34
+ currency: 'usdc',
35
+ chain: 'base',
36
+ metadata: { orderId: 'order_123' },
37
+ })
38
+
39
+ console.log(intent.id, intent.status) // "pi_…" "created"
40
+ ```
41
+
42
+ ## Webhooks
43
+
44
+ ```typescript
45
+ app.post('/webhooks', (req) => {
46
+ const event = relay.webhooks.verify(
47
+ req.body, // raw body
48
+ req.headers['openrelay-signature'],
49
+ process.env.OPENRELAY_WEBHOOK_SECRET!,
50
+ )
51
+ if (event.type === 'payment_intent.settled') {
52
+ fulfillOrder(event.data.metadata.orderId)
53
+ }
54
+ })
55
+ ```
56
+
57
+ ## x402 — micropayments for AI agents
58
+
59
+ ```typescript
60
+ // Gate any endpoint behind a per-request micropayment.
61
+ app.addHook(
62
+ 'preHandler',
63
+ relay.x402.middleware({
64
+ price: 1000, // 0.001 USDC per request
65
+ currency: 'usdc',
66
+ chain: 'base',
67
+ }),
68
+ )
69
+ ```
70
+
71
+ Any HTTP client that speaks x402 — including AI agents over MCP — can pay and consume your
72
+ endpoint autonomously.
73
+
74
+ ### The HTTP flow (x402 spec)
75
+
76
+ The middleware speaks the standard [x402](https://x402.org) protocol on the wire:
77
+
78
+ ```http
79
+ # 1. Client requests the resource — no payment yet
80
+ GET /api/data HTTP/1.1
81
+
82
+ # 2. Server answers 402 with the payment requirements (x402 spec shape)
83
+ HTTP/1.1 402 Payment Required
84
+ Content-Type: application/json
85
+
86
+ {
87
+ "x402Version": 1,
88
+ "accepts": [{
89
+ "scheme": "exact",
90
+ "network": "base",
91
+ "maxAmountRequired": "1000", // 0.001 USDC (base units)
92
+ "resource": "/api/data",
93
+ "payTo": "0x742d35Cc…", // merchant wallet
94
+ "asset": "0x833589fC…", // USDC on Base
95
+ "maxTimeoutSeconds": 300,
96
+ "extra": { "name": "USDC", "version": "2" }
97
+ }]
98
+ }
99
+
100
+ # 3. Client pays and retries with the payment proof
101
+ GET /api/data HTTP/1.1
102
+ X-PAYMENT: <base64 payment payload>
103
+
104
+ # 4. Server verifies on-chain (POST /v1/x402/verify) and serves the resource
105
+ HTTP/1.1 200 OK
106
+ ```
107
+
108
+ ## Configuration
109
+
110
+ ```typescript
111
+ new OpenRelay({
112
+ apiKey: 'sk_live_…', // required — secret key, server-side only
113
+ baseUrl: 'https://api.openrelay.site', // optional — your OpenRelay API host
114
+ timeout: 30_000, // optional — request timeout in ms
115
+ })
116
+ ```
117
+
118
+ ## Links
119
+
120
+ - Repo, docs & protocol spec: https://github.com/lacasoft/openrelay
121
+ - Source: [`packages/sdk-js`](https://github.com/lacasoft/openrelay/tree/master/packages/sdk-js)
122
+ - License: Apache-2.0
123
+
124
+ ---
125
+
126
+ ### Contributing / local dev
127
+
128
+ The SDK lives in the [OpenRelay monorepo](https://github.com/lacasoft/openrelay). To work on it:
129
+
130
+ ```bash
131
+ pnpm dev # watch mode (cjs + esm + dts)
132
+ pnpm build # build with tsup
133
+ pnpm test # unit tests
134
+ pnpm typecheck # type-check without emitting
135
+ ```
@@ -0,0 +1,277 @@
1
+ import { SupportedChain, CreatePaymentIntentParams, PaymentIntent, WebhookEvent, X402MiddlewareOptions } from '@lacasoft/openrelay-protocol';
2
+ export { AuthError, CreatePaymentIntentParams, NetworkError, OpenRelayError, OpenRelayErrorCode, OpenRelaySDKError, PaymentIntent, RoutingError, SupportedChain, USDC_ADDRESSES, ValidationError, WebhookEvent, X402MiddlewareOptions, classifyError } from '@lacasoft/openrelay-protocol';
3
+ import { Address, Hex } from 'viem';
4
+
5
+ interface LogEntry {
6
+ request_id: string;
7
+ method: string;
8
+ path: string;
9
+ status: number;
10
+ latency_ms: number;
11
+ /** Nodeit wallet selected for routing, if returned by the API. */
12
+ node_route: string | null;
13
+ }
14
+ interface OpenRelayConfig {
15
+ apiKey: string;
16
+ baseUrl?: string;
17
+ timeout?: number;
18
+ merchantWallet?: string;
19
+ /** Optional structured-log hook called after every SDK request. */
20
+ logger?: (entry: LogEntry) => void;
21
+ }
22
+
23
+ interface BuildAuthorizationParams {
24
+ /** Payer address — the `from` of the USDC transfer. Must match the signer. */
25
+ payer: Address;
26
+ /** Amount in USDC base units (6 decimals). Must match the intent's amount. */
27
+ amount: bigint;
28
+ /** SettlementHub contract address — the `to` of the authorization. */
29
+ settlementHub: Address;
30
+ /** Which chain — picks USDC contract address + chainId. */
31
+ chain: SupportedChain;
32
+ /** Optional 32-byte random nonce. SDK generates one if omitted. */
33
+ nonce?: Hex;
34
+ /** Unix seconds; signature invalid before this. Default: 0 (always valid from start). */
35
+ validAfter?: bigint;
36
+ /** Unix seconds; signature invalid after this. Default: now + 30 minutes. */
37
+ validBefore?: bigint;
38
+ }
39
+ interface AuthorizationMessage {
40
+ from: Address;
41
+ to: Address;
42
+ value: bigint;
43
+ validAfter: bigint;
44
+ validBefore: bigint;
45
+ nonce: Hex;
46
+ }
47
+ interface AuthorizationTypedData {
48
+ domain: {
49
+ name: string;
50
+ version: string;
51
+ chainId: number;
52
+ verifyingContract: Address;
53
+ };
54
+ types: {
55
+ EIP712Domain: {
56
+ name: string;
57
+ type: string;
58
+ }[];
59
+ ReceiveWithAuthorization: {
60
+ name: string;
61
+ type: string;
62
+ }[];
63
+ };
64
+ primaryType: 'ReceiveWithAuthorization';
65
+ message: AuthorizationMessage;
66
+ }
67
+ declare function buildReceiveAuthorizationTypedData(params: BuildAuthorizationParams): AuthorizationTypedData;
68
+ interface SignedAuthorization {
69
+ /** Payer address (the `from` of the USDC transfer). */
70
+ payer: Address;
71
+ /** Authorization validity window. */
72
+ validAfter: bigint;
73
+ validBefore: bigint;
74
+ /** 32-byte random nonce, hex-encoded. */
75
+ nonce: Hex;
76
+ /** ECDSA signature components. */
77
+ v: number;
78
+ r: Hex;
79
+ s: Hex;
80
+ }
81
+ declare function signReceiveAuthorization(params: BuildAuthorizationParams, privateKey: Hex): Promise<SignedAuthorization>;
82
+ declare function splitSignature(signature: Hex): {
83
+ v: number;
84
+ r: Hex;
85
+ s: Hex;
86
+ };
87
+ declare function generateNonce(): Hex;
88
+
89
+ interface SubmitAuthorizationResponse {
90
+ /** Echoed intent id. */
91
+ intent_id: string;
92
+ /** Server-side estimate of when the operator will submit it on-chain. */
93
+ estimated_settlement_at: string | null;
94
+ /** Authorization persisted server-side, awaiting operator pickup. */
95
+ status: 'queued';
96
+ }
97
+ interface SubmitAuthorizationBatchResponse {
98
+ /** Per-authorization queueing result. Order matches the input. */
99
+ results: Array<{
100
+ intent_id: string;
101
+ status: 'queued' | 'rejected';
102
+ reason?: string;
103
+ }>;
104
+ queued: number;
105
+ rejected: number;
106
+ }
107
+ declare class PaymentIntents {
108
+ private config;
109
+ constructor(config: OpenRelayConfig);
110
+ /**
111
+ * Create a new payment intent.
112
+ *
113
+ * @example
114
+ * const intent = await relay.paymentIntents.create({
115
+ * amount: 1000, // $0.001000 USDC (6 decimals)
116
+ * currency: 'usdc',
117
+ * chain: 'base',
118
+ * metadata: { orderId: 'order_123' }
119
+ * })
120
+ */
121
+ create(params: CreatePaymentIntentParams): Promise<PaymentIntent>;
122
+ /**
123
+ * Retrieve a payment intent by ID.
124
+ */
125
+ retrieve(id: string): Promise<PaymentIntent>;
126
+ /**
127
+ * Cancel a payment intent (only valid while it is in 'created' state).
128
+ */
129
+ cancel(id: string): Promise<PaymentIntent>;
130
+ /**
131
+ * List payment intents for the authenticated merchant.
132
+ */
133
+ list(params?: {
134
+ limit?: number;
135
+ starting_after?: string;
136
+ }): Promise<{
137
+ data: PaymentIntent[];
138
+ has_more: boolean;
139
+ }>;
140
+ /**
141
+ * Build the EIP-712 typed-data structure for `ReceiveWithAuthorization`
142
+ * that USDC verifies on `payIntentWithAuthorization`. Hand the result to
143
+ * a wallet (viem `walletClient.signTypedData`, `window.ethereum`, etc.)
144
+ * to obtain a signature client-side.
145
+ *
146
+ * For server-side signing with a private key, prefer `signAuthorization`.
147
+ *
148
+ * @example (browser/wallet flow)
149
+ * const typed = relay.paymentIntents.buildAuthorizationTypedData({
150
+ * payer: '0xPayer...',
151
+ * amount: 5_000_000n, // 5 USDC (6 decimals)
152
+ * settlementHub: '0xHub...',
153
+ * chain: 'base-sepolia',
154
+ * })
155
+ * const signature = await walletClient.signTypedData(typed)
156
+ * const { v, r, s } = relay.paymentIntents.splitSignature(signature)
157
+ * await relay.paymentIntents.submitAuthorization(intentId, {
158
+ * payer: typed.message.from,
159
+ * validAfter: typed.message.validAfter,
160
+ * validBefore: typed.message.validBefore,
161
+ * nonce: typed.message.nonce,
162
+ * v, r, s,
163
+ * })
164
+ */
165
+ buildAuthorizationTypedData(params: BuildAuthorizationParams): AuthorizationTypedData;
166
+ /**
167
+ * Server-side convenience: build + sign the `ReceiveWithAuthorization`
168
+ * message in one call. Returns everything needed for `submitAuthorization`.
169
+ *
170
+ * @example
171
+ * const auth = await relay.paymentIntents.signAuthorization(
172
+ * { payer, amount: 5_000_000n, settlementHub, chain: 'base-sepolia' },
173
+ * privateKey,
174
+ * )
175
+ * await relay.paymentIntents.submitAuthorization(intentId, auth)
176
+ */
177
+ signAuthorization(params: BuildAuthorizationParams, privateKey: Hex): Promise<SignedAuthorization>;
178
+ /**
179
+ * Submit a signed authorization for a registered intent. The API queues
180
+ * it for the assigned operator to settle on-chain (via
181
+ * `SettlementHub.payIntentWithAuthorization`).
182
+ *
183
+ * The endpoint is implemented in Phase B3; this client method targets
184
+ * the documented path so SDK + API can be developed in parallel.
185
+ */
186
+ submitAuthorization(intentId: string, auth: SignedAuthorization): Promise<SubmitAuthorizationResponse>;
187
+ /**
188
+ * Submit multiple signed authorizations in one HTTP request. The operator
189
+ * may settle them via `SettlementHub.payIntentBatchWithAuthorization`
190
+ * (skip-on-failure). Useful for x402 micropayment flows where many small
191
+ * payments are aggregated.
192
+ *
193
+ * Hard cap: `MAX_BATCH_SIZE` (matches `SettlementHub.MAX_BATCH_SIZE`,
194
+ * imported from `@lacasoft/openrelay-protocol` SSOT — never hardcode the literal).
195
+ */
196
+ submitAuthorizationBatch(items: Array<{
197
+ intent_id: string;
198
+ authorization: SignedAuthorization;
199
+ }>): Promise<SubmitAuthorizationBatchResponse>;
200
+ /**
201
+ * Helper to split a 65-byte signature (e.g. from `walletClient.signTypedData`)
202
+ * into the {v, r, s} triple that `submitAuthorization` expects.
203
+ */
204
+ splitSignature(signature: Hex): {
205
+ v: number;
206
+ r: Hex;
207
+ s: Hex;
208
+ };
209
+ }
210
+
211
+ declare class Webhooks {
212
+ private config;
213
+ constructor(config: OpenRelayConfig);
214
+ register(url: string, events: string[]): Promise<{
215
+ id: string;
216
+ url: string;
217
+ secret: string;
218
+ }>;
219
+ /**
220
+ * Verify a webhook payload signature.
221
+ * Call this in your webhook handler to ensure the request is from OpenRelay.
222
+ *
223
+ * Validates: (1) signature format, (2) timestamp freshness against
224
+ * `toleranceSeconds` to mitigate replay, (3) HMAC equality with
225
+ * timing-safe compare.
226
+ *
227
+ * @example
228
+ * const event = relay.webhooks.verify(rawBody, req.headers['openrelay-signature'], secret)
229
+ */
230
+ verify(payload: string, signature: string, secret: string, toleranceSeconds?: number): WebhookEvent;
231
+ }
232
+
233
+ declare class X402 {
234
+ private config;
235
+ constructor(config: OpenRelayConfig);
236
+ /**
237
+ * Returns a Fastify preHandler hook that requires x402 payment.
238
+ *
239
+ * @example
240
+ * app.addHook('preHandler', relay.x402.middleware({
241
+ * price: 1000, // $0.001 USDC
242
+ * currency: 'usdc',
243
+ * chain: 'base',
244
+ * }))
245
+ */
246
+ middleware(opts: X402MiddlewareOptions): (req: Request, reply: Response) => Promise<Response | undefined>;
247
+ /**
248
+ * Returns a Next.js App Router compatible handler that wraps a route with x402.
249
+ *
250
+ * @example
251
+ * export const GET = relay.x402.handler({
252
+ * price: 1000,
253
+ * handler: async (req) => Response.json({ data: 'protected' })
254
+ * })
255
+ */
256
+ handler(opts: X402MiddlewareOptions & {
257
+ handler: (req: Request) => Promise<Response>;
258
+ }): (req: Request) => Promise<Response>;
259
+ /**
260
+ * Shared gate: extract X-PAYMENT, verify against the API, and either
261
+ * return a 402 Response (challenge or rejection) or null when payment
262
+ * is valid and the caller should proceed.
263
+ */
264
+ private gate;
265
+ private buildPaymentRequired;
266
+ private verify;
267
+ }
268
+
269
+ declare class OpenRelay {
270
+ private config;
271
+ readonly paymentIntents: PaymentIntents;
272
+ readonly webhooks: Webhooks;
273
+ readonly x402: X402;
274
+ constructor(config: OpenRelayConfig);
275
+ }
276
+
277
+ export { type AuthorizationMessage, type AuthorizationTypedData, type BuildAuthorizationParams, type LogEntry, OpenRelay, type OpenRelayConfig, type SignedAuthorization, type SubmitAuthorizationBatchResponse, type SubmitAuthorizationResponse, buildReceiveAuthorizationTypedData, generateNonce, signReceiveAuthorization, splitSignature };