@routedock/routedock 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.
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Integration smoke tests for @routedock/sdk.
3
+ *
4
+ * These tests run against actual package imports to verify:
5
+ * 1. x402 flow against a local mock server (402 → payment → 200)
6
+ * 2. ModeRouter manifest fetch + validation
7
+ * 3. SessionStore monotonic invariant rejection
8
+ *
9
+ * Run with: pnpm --filter @routedock/sdk test
10
+ * No testnet RPC calls are made — all network calls are mocked via fetch interception.
11
+ */
12
+
13
+ import * as http from 'node:http'
14
+ import { createServer } from 'node:http'
15
+ import type { IncomingMessage, ServerResponse } from 'node:http'
16
+ import assert from 'node:assert/strict'
17
+
18
+ // ── Helpers ───────────────────────────────────────────────────────────────────
19
+
20
+ function startTestServer(
21
+ handler: (req: IncomingMessage, res: ServerResponse) => void,
22
+ ): Promise<{ url: string; close: () => Promise<void> }> {
23
+ return new Promise((resolve) => {
24
+ const server = createServer(handler)
25
+ server.listen(0, '127.0.0.1', () => {
26
+ const addr = server.address() as { port: number }
27
+ resolve({
28
+ url: `http://127.0.0.1:${addr.port}`,
29
+ close: () => new Promise<void>((res) => server.close(() => res())),
30
+ })
31
+ })
32
+ })
33
+ }
34
+
35
+ // ── Test 1: ModeRouter — manifest fetch + schema validation ───────────────────
36
+
37
+ {
38
+ const validManifest = {
39
+ routedock: '1.0',
40
+ name: 'Test Provider',
41
+ description: 'Smoke test provider',
42
+ modes: ['x402', 'mpp-charge'],
43
+ network: 'testnet',
44
+ asset: 'USDC',
45
+ asset_contract: 'CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA',
46
+ payee: 'GDHLJWBM6Z2Y4KF6Z4JAFIUUO2KAXAJ6MAIUK2XMGBQ7ZUUZ7HFPW2BK',
47
+ pricing: {
48
+ x402: { amount: '0.001', per: 'request', facilitator: 'https://channels.openzeppelin.com/x402/testnet' },
49
+ 'mpp-charge': { amount: '0.0008', per: 'request' },
50
+ },
51
+ endpoints: { price: 'GET /price' },
52
+ tags: ['price', 'stellar'],
53
+ }
54
+
55
+ const server = await startTestServer((req, res) => {
56
+ if (req.url === '/.well-known/routedock.json') {
57
+ res.writeHead(200, { 'Content-Type': 'application/json' })
58
+ res.end(JSON.stringify(validManifest))
59
+ } else {
60
+ res.writeHead(404)
61
+ res.end()
62
+ }
63
+ })
64
+
65
+ try {
66
+ const { fetchManifest, selectMode } = await import('../client/ModeRouter.js')
67
+
68
+ const manifest = await fetchManifest(server.url)
69
+ assert.equal(manifest.routedock, '1.0', 'manifest version should be 1.0')
70
+ assert.equal(manifest.name, 'Test Provider', 'manifest name should match')
71
+ assert.ok(manifest.modes.includes('x402'), 'manifest should include x402 mode')
72
+
73
+ // Second fetch should be cached
74
+ const cached = await fetchManifest(server.url)
75
+ assert.equal(cached, manifest, 'second fetch should return cached manifest')
76
+
77
+ // Mode selection
78
+ const mode = selectMode(manifest)
79
+ assert.equal(mode, 'mpp-charge', 'mpp-charge should be preferred over x402')
80
+
81
+ const modeForced = selectMode(manifest, { sustained: true })
82
+ assert.equal(modeForced, 'mpp-charge', 'sustained without mpp-session falls back to mpp-charge')
83
+
84
+ console.log('✓ Test 1: ModeRouter manifest fetch + validation PASSED')
85
+ } finally {
86
+ await server.close()
87
+ }
88
+ }
89
+
90
+ // ── Test 2: ModeRouter — invalid manifest rejected ────────────────────────────
91
+
92
+ {
93
+ const badManifest = { routedock: '2.0', name: 'bad' }
94
+
95
+ const server = await startTestServer((req, res) => {
96
+ res.writeHead(200, { 'Content-Type': 'application/json' })
97
+ res.end(JSON.stringify(badManifest))
98
+ })
99
+
100
+ try {
101
+ const { fetchManifest } = await import('../client/ModeRouter.js')
102
+ const { RouteDockManifestError: ManifestError } = await import('../types.js')
103
+
104
+ let threw = false
105
+ try {
106
+ await fetchManifest(server.url + '/bad-url')
107
+ } catch (err) {
108
+ threw = true
109
+ assert.ok(
110
+ err instanceof ManifestError,
111
+ `should throw RouteDockManifestError, got ${String(err)}`,
112
+ )
113
+ }
114
+ assert.ok(threw, 'should have thrown for invalid manifest')
115
+
116
+ console.log('✓ Test 2: Invalid manifest rejection PASSED')
117
+ } finally {
118
+ await server.close()
119
+ }
120
+ }
121
+
122
+ // ── Test 3: SessionStore — monotonic invariant rejection ─────────────────────
123
+
124
+ {
125
+ // Use an in-memory store implementation to test monotonic invariant
126
+ // without a real Supabase connection.
127
+
128
+ const { RouteDockSessionError } = await import('../types.js')
129
+
130
+ // Build a minimal in-memory SessionStore-compatible implementation
131
+ const sessions = new Map<string, import('../types.js').SessionState>()
132
+ const memStore = {
133
+ async get(channelId: string) {
134
+ return sessions.get(channelId) ?? null
135
+ },
136
+ async upsert(channelId: string, state: import('../types.js').SessionState) {
137
+ const existing = sessions.get(channelId)
138
+ if (existing) {
139
+ const prev = parseFloat(existing.cumulative_amount)
140
+ const next = parseFloat(state.cumulative_amount)
141
+ if (next <= prev) {
142
+ throw new RouteDockSessionError(
143
+ `cumulative_amount must be strictly increasing: ${next} <= ${prev}`,
144
+ )
145
+ }
146
+ }
147
+ sessions.set(channelId, { ...state })
148
+ },
149
+ async close(channelId: string) {
150
+ const s = sessions.get(channelId)
151
+ if (s) sessions.set(channelId, { ...s, status: 'closed' })
152
+ },
153
+ }
154
+
155
+ const baseState: import('../types.js').SessionState = {
156
+ channel_id: 'test-channel-1',
157
+ payee: 'GPAYEE',
158
+ payer: 'GPAYER',
159
+ cumulative_amount: '0.0010000',
160
+ last_signature: 'sig1',
161
+ status: 'open',
162
+ opened_at: new Date().toISOString(),
163
+ updated_at: new Date().toISOString(),
164
+ settlement_tx_hash: null,
165
+ }
166
+
167
+ // First upsert — should succeed
168
+ await memStore.upsert('test-channel-1', baseState)
169
+
170
+ // Second upsert with higher amount — should succeed
171
+ await memStore.upsert('test-channel-1', { ...baseState, cumulative_amount: '0.0020000' })
172
+
173
+ // Third upsert with same amount — should throw
174
+ let threw = false
175
+ try {
176
+ await memStore.upsert('test-channel-1', { ...baseState, cumulative_amount: '0.0020000' })
177
+ } catch (err) {
178
+ threw = true
179
+ assert.ok(
180
+ err instanceof RouteDockSessionError,
181
+ `should throw RouteDockSessionError, got ${String(err)}`,
182
+ )
183
+ }
184
+ assert.ok(threw, 'equal cumulative amount should be rejected')
185
+
186
+ // Upsert with lower amount — should also throw
187
+ threw = false
188
+ try {
189
+ await memStore.upsert('test-channel-1', { ...baseState, cumulative_amount: '0.0010000' })
190
+ } catch (err) {
191
+ threw = true
192
+ assert.ok(err instanceof RouteDockSessionError)
193
+ }
194
+ assert.ok(threw, 'lower cumulative amount should be rejected')
195
+
196
+ console.log('✓ Test 3: SessionStore monotonic invariant rejection PASSED')
197
+ }
198
+
199
+ // ── Test 4: Error subclass hierarchy ─────────────────────────────────────────
200
+
201
+ {
202
+ const {
203
+ RouteDockError,
204
+ RouteDockManifestError,
205
+ RouteDockNoSupportedModeError,
206
+ RouteDockSessionError,
207
+ RouteDockPolicyRejectedError,
208
+ } = await import('../types.js')
209
+
210
+ const errors = [
211
+ new RouteDockManifestError('test'),
212
+ new RouteDockNoSupportedModeError('test'),
213
+ new RouteDockSessionError('test'),
214
+ new RouteDockPolicyRejectedError('test'),
215
+ ]
216
+
217
+ for (const err of errors) {
218
+ assert.ok(err instanceof RouteDockError, `${err.name} should be instance of RouteDockError`)
219
+ assert.ok(err instanceof Error, `${err.name} should be instance of Error`)
220
+ }
221
+
222
+ const policyErr = new RouteDockPolicyRejectedError('local_daily_cap_exceeded')
223
+ assert.equal(policyErr.reason, 'local_daily_cap_exceeded')
224
+
225
+ console.log('✓ Test 4: Error subclass hierarchy PASSED')
226
+ }
227
+
228
+ console.log('\nAll smoke tests passed.')
package/src/types.ts ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * TypeScript types for the RouteDock manifest format.
3
+ * Derived from packages/sdk/src/schemas/routedock.schema.json (draft-07).
4
+ *
5
+ * Section 5 of ROUTEDOCK_MASTER.md is the canonical specification.
6
+ */
7
+
8
+ export type PaymentMode = 'x402' | 'mpp-charge' | 'mpp-session'
9
+
10
+ /** Per-request pricing config — used by x402 and mpp-charge modes */
11
+ export interface PricingConfig {
12
+ /** Cost per request in the payment asset, e.g. "0.001" */
13
+ amount: string
14
+ per: 'request'
15
+ /** x402 facilitator URL (OpenZeppelin Channels). Required for x402 mode. */
16
+ facilitator?: string
17
+ }
18
+
19
+ /** Per-voucher pricing config — used by mpp-session (one-way-channel) mode */
20
+ export interface SessionPricingConfig {
21
+ /** Cost per voucher, e.g. "0.0001" */
22
+ rate: string
23
+ per: 'voucher'
24
+ /** Soroban contract address (C...) for the one-way-channel contract */
25
+ channel_contract: string
26
+ /** Minimum initial deposit to open a channel, e.g. "0.10" */
27
+ min_deposit: string
28
+ /**
29
+ * Ledgers the server has to settle before the funder can reclaim.
30
+ * Default: 17280 (~24h). Do NOT reduce in production — this is a
31
+ * security parameter the server depends on to settle first.
32
+ */
33
+ refund_waiting_period_ledgers: number
34
+ }
35
+
36
+ /** Full RouteDock discovery manifest — served at /.well-known/routedock.json */
37
+ export interface RouteDockManifest {
38
+ /** Schema version — always "1.0" */
39
+ routedock: '1.0'
40
+ /** Human-readable provider name */
41
+ name: string
42
+ /** Human-readable description of the provider's data or service */
43
+ description: string
44
+ /** Payment modes supported by this provider */
45
+ modes: PaymentMode[]
46
+ /** Stellar network this provider operates on */
47
+ network: 'testnet' | 'mainnet'
48
+ /** Asset ticker symbol, e.g. "USDC" */
49
+ asset: string
50
+ /** Stellar Asset Contract (SAC) address for the payment asset */
51
+ asset_contract: string
52
+ /** Stellar address (G...) that receives payments */
53
+ payee: string
54
+ /** Pricing configuration per supported payment mode */
55
+ pricing: {
56
+ x402?: PricingConfig
57
+ 'mpp-charge'?: PricingConfig
58
+ 'mpp-session'?: SessionPricingConfig
59
+ }
60
+ /** Map of endpoint name to HTTP method + path, e.g. { price: "GET /price" } */
61
+ endpoints: Record<string, string>
62
+ /** Capability tags indexed with trigram search in the provider registry */
63
+ tags: string[]
64
+ }
65
+
66
+ /** Result returned by client.pay() for any payment mode */
67
+ export interface PaymentResult {
68
+ /** Parsed response body from the provider */
69
+ data: unknown
70
+ /** On-chain Stellar transaction hash, or null for session voucher calls */
71
+ txHash: string | null
72
+ /** Payment mode that was used for this call */
73
+ mode: PaymentMode
74
+ /** Amount paid in the payment asset (decimal string) */
75
+ amount: string
76
+ /** Unix timestamp (ms) when the payment completed */
77
+ timestamp: number
78
+ }
79
+
80
+ /** Result returned by session.close() */
81
+ export interface SessionCloseResult {
82
+ /** On-chain transaction hash for the channel close */
83
+ closeTxHash: string
84
+ /** Total amount settled across all vouchers (decimal string) */
85
+ totalPaid: string
86
+ /** Number of vouchers issued during the session */
87
+ vouchersIssued: number
88
+ }
89
+
90
+ /** Handle for a live MPP session returned by client.openSession() */
91
+ export interface SessionHandle {
92
+ /** Stellar channel contract address (C...) */
93
+ channelId: string
94
+ /** Transaction hash from the channel-open on-chain call */
95
+ openTxHash: string
96
+ /**
97
+ * Async generator of server-sent event data.
98
+ * Each iteration sends a voucher and yields the parsed response.
99
+ * UNAUDITED: uses stellar-experimental/one-way-channel contract.
100
+ */
101
+ stream(): AsyncIterable<unknown>
102
+ /** Close the channel on-chain with the highest signed voucher */
103
+ close(): Promise<SessionCloseResult>
104
+ }
105
+
106
+ /**
107
+ * Durable session state stored in Supabase (sessions table).
108
+ * cumulative_amount is a decimal string to avoid float precision loss.
109
+ * The monotonic invariant is enforced both here and at the DB level via trigger.
110
+ */
111
+ export interface SessionState {
112
+ channel_id: string
113
+ payee: string
114
+ payer: string
115
+ /** Monotonically increasing cumulative amount — stored as string to preserve precision */
116
+ cumulative_amount: string
117
+ last_signature: string
118
+ status: 'open' | 'closing' | 'closed'
119
+ opened_at: string
120
+ updated_at: string
121
+ settlement_tx_hash: string | null
122
+ }
123
+
124
+ // ── Error hierarchy ────────────────────────────────────────────────────────────
125
+
126
+ export class RouteDockError extends Error {
127
+ constructor(message: string) {
128
+ super(message)
129
+ this.name = 'RouteDockError'
130
+ }
131
+ }
132
+
133
+ /** Manifest fetch failed, schema invalid, or required fields missing */
134
+ export class RouteDockManifestError extends RouteDockError {
135
+ constructor(message: string) {
136
+ super(message)
137
+ this.name = 'RouteDockManifestError'
138
+ }
139
+ }
140
+
141
+ /** No payment mode in the manifest is supported by this client */
142
+ export class RouteDockNoSupportedModeError extends RouteDockError {
143
+ constructor(message: string) {
144
+ super(message)
145
+ this.name = 'RouteDockNoSupportedModeError'
146
+ }
147
+ }
148
+
149
+ /** Session invariant violated (e.g. non-monotonic voucher amount) */
150
+ export class RouteDockSessionError extends RouteDockError {
151
+ constructor(message: string) {
152
+ super(message)
153
+ this.name = 'RouteDockSessionError'
154
+ }
155
+ }
156
+
157
+ /** Local spend cap or on-chain policy rejected the payment */
158
+ export class RouteDockPolicyRejectedError extends RouteDockError {
159
+ readonly reason: string
160
+ constructor(reason: string) {
161
+ super(`Payment rejected by policy: ${reason}`)
162
+ this.name = 'RouteDockPolicyRejectedError'
163
+ this.reason = reason
164
+ }
165
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": "src",
6
+ "module": "ESNext",
7
+ "moduleResolution": "bundler",
8
+ "resolveJsonModule": true,
9
+ "allowImportingTsExtensions": false,
10
+ "lib": ["ES2022"],
11
+ "target": "ES2022"
12
+ },
13
+ "include": ["src/**/*"]
14
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { defineConfig } from 'tsup'
2
+
3
+ export default defineConfig({
4
+ entry: {
5
+ index: 'src/index.ts',
6
+ client: 'src/client/index.ts',
7
+ provider: 'src/provider/index.ts',
8
+ },
9
+ format: ['cjs', 'esm'],
10
+ dts: true,
11
+ clean: true,
12
+ splitting: false,
13
+ sourcemap: false,
14
+ treeshake: true,
15
+ })