|
| 1 | +/** |
| 2 | + * Gateway API Worker |
| 3 | + * |
| 4 | + * DWS-deployable worker using Elysia with workerd compatibility. |
| 5 | + * Compatible with workerd runtime and DWS infrastructure. |
| 6 | + * |
| 7 | + * @see https://elysiajs.com/integrations/cloudflare-worker |
| 8 | + */ |
| 9 | + |
| 10 | +import { cors } from '@elysiajs/cors' |
| 11 | +import { |
| 12 | + CORE_PORTS, |
| 13 | + getCoreAppUrl, |
| 14 | + getCurrentNetwork, |
| 15 | + getLocalhostHost, |
| 16 | +} from '@jejunetwork/config' |
| 17 | +import { Elysia } from 'elysia' |
| 18 | +import { z } from 'zod' |
| 19 | +import { config } from './config' |
| 20 | +import { |
| 21 | + claimFromFaucet, |
| 22 | + getFaucetInfo, |
| 23 | + getFaucetStatus, |
| 24 | +} from './services/faucet-service' |
| 25 | + |
| 26 | +/** |
| 27 | + * Worker Environment Types |
| 28 | + */ |
| 29 | +export interface GatewayEnv { |
| 30 | + // Standard workerd bindings |
| 31 | + NETWORK: 'localnet' | 'testnet' | 'mainnet' |
| 32 | + RPC_URL: string |
| 33 | + FAUCET_PRIVATE_KEY?: string |
| 34 | + |
| 35 | + // KV bindings (optional) |
| 36 | + GATEWAY_CACHE?: KVNamespace |
| 37 | +} |
| 38 | + |
| 39 | +interface KVNamespace { |
| 40 | + get(key: string): Promise<string | null> |
| 41 | + put( |
| 42 | + key: string, |
| 43 | + value: string, |
| 44 | + options?: { expirationTtl?: number }, |
| 45 | + ): Promise<void> |
| 46 | + delete(key: string): Promise<void> |
| 47 | +} |
| 48 | + |
| 49 | +const AddressSchema = z.string().regex(/^0x[a-fA-F0-9]{40}$/) |
| 50 | + |
| 51 | +/** |
| 52 | + * Create the Gateway Elysia app |
| 53 | + */ |
| 54 | +export function createGatewayApp(env?: Partial<GatewayEnv>) { |
| 55 | + const isDev = env?.NETWORK === 'localnet' |
| 56 | + const network = env?.NETWORK ?? getCurrentNetwork() |
| 57 | + |
| 58 | + const app = new Elysia().use( |
| 59 | + cors({ |
| 60 | + origin: isDev |
| 61 | + ? true |
| 62 | + : [ |
| 63 | + 'https://gateway.jejunetwork.org', |
| 64 | + 'https://jejunetwork.org', |
| 65 | + getCoreAppUrl('GATEWAY'), |
| 66 | + ], |
| 67 | + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], |
| 68 | + allowedHeaders: ['Content-Type', 'Authorization', 'X-API-Key'], |
| 69 | + credentials: true, |
| 70 | + }), |
| 71 | + ) |
| 72 | + |
| 73 | + // Health check |
| 74 | + app.get('/health', () => ({ |
| 75 | + status: 'ok', |
| 76 | + service: 'gateway-api', |
| 77 | + version: '1.0.0', |
| 78 | + network, |
| 79 | + runtime: 'workerd', |
| 80 | + endpoints: { |
| 81 | + faucet: '/api/faucet', |
| 82 | + rpc: '/rpc', |
| 83 | + x402: '/x402', |
| 84 | + oracle: '/oracle', |
| 85 | + leaderboard: '/leaderboard', |
| 86 | + }, |
| 87 | + })) |
| 88 | + |
| 89 | + // Faucet routes |
| 90 | + app.group('/api/faucet', (app) => |
| 91 | + app |
| 92 | + .get('/info', () => getFaucetInfo()) |
| 93 | + .get('/status/:address', async ({ params }) => { |
| 94 | + const parsed = AddressSchema.safeParse(params.address) |
| 95 | + if (!parsed.success) { |
| 96 | + return { error: 'Invalid address format' } |
| 97 | + } |
| 98 | + return getFaucetStatus(parsed.data as `0x${string}`) |
| 99 | + }) |
| 100 | + .post('/claim', async ({ body }) => { |
| 101 | + const bodyParsed = z.object({ address: AddressSchema }).safeParse(body) |
| 102 | + if (!bodyParsed.success) { |
| 103 | + return { success: false, error: 'Invalid address format' } |
| 104 | + } |
| 105 | + return claimFromFaucet(bodyParsed.data.address as `0x${string}`) |
| 106 | + }), |
| 107 | + ) |
| 108 | + |
| 109 | + // Root route - API info |
| 110 | + app.get('/', () => ({ |
| 111 | + name: 'Gateway API', |
| 112 | + version: '1.0.0', |
| 113 | + description: 'Jeju Network Gateway - Faucet, RPC Proxy, x402 Payments, Oracle', |
| 114 | + runtime: 'workerd', |
| 115 | + network, |
| 116 | + endpoints: { |
| 117 | + health: '/health', |
| 118 | + faucet: '/api/faucet', |
| 119 | + rpc: '/rpc', |
| 120 | + x402: '/x402', |
| 121 | + oracle: '/oracle', |
| 122 | + leaderboard: '/leaderboard', |
| 123 | + }, |
| 124 | + })) |
| 125 | + |
| 126 | + // Agent card endpoint |
| 127 | + app.get('/.well-known/agent-card.json', () => ({ |
| 128 | + name: 'Gateway', |
| 129 | + description: 'Jeju Network Gateway - Faucet, RPC Proxy, x402 Payments, Oracle', |
| 130 | + version: '1.0.0', |
| 131 | + skills: [ |
| 132 | + { id: 'faucet-claim', name: 'Claim Faucet', description: 'Claim testnet tokens from faucet' }, |
| 133 | + { id: 'faucet-status', name: 'Faucet Status', description: 'Check faucet claim status' }, |
| 134 | + { id: 'rpc-proxy', name: 'RPC Proxy', description: 'Proxy JSON-RPC requests' }, |
| 135 | + { id: 'x402-verify', name: 'Verify Payment', description: 'Verify x402 payments' }, |
| 136 | + ], |
| 137 | + endpoints: { |
| 138 | + a2a: '/a2a', |
| 139 | + mcp: '/mcp', |
| 140 | + }, |
| 141 | + })) |
| 142 | + |
| 143 | + return app |
| 144 | +} |
| 145 | + |
| 146 | +// Worker Export (for DWS/workerd) |
| 147 | + |
| 148 | +/** |
| 149 | + * Workerd/Cloudflare Workers execution context |
| 150 | + */ |
| 151 | +interface ExecutionContext { |
| 152 | + waitUntil(promise: Promise<unknown>): void |
| 153 | + passThroughOnException(): void |
| 154 | +} |
| 155 | + |
| 156 | +/** |
| 157 | + * Cached app instance for worker reuse |
| 158 | + */ |
| 159 | +let cachedApp: ReturnType<typeof createGatewayApp> | null = null |
| 160 | +let cachedEnvHash: string | null = null |
| 161 | + |
| 162 | +function getAppForEnv(env: GatewayEnv): ReturnType<typeof createGatewayApp> { |
| 163 | + const envHash = `${env.NETWORK}` |
| 164 | + |
| 165 | + if (cachedApp && cachedEnvHash === envHash) { |
| 166 | + return cachedApp |
| 167 | + } |
| 168 | + |
| 169 | + cachedApp = createGatewayApp(env).compile() |
| 170 | + cachedEnvHash = envHash |
| 171 | + return cachedApp |
| 172 | +} |
| 173 | + |
| 174 | +/** |
| 175 | + * Default export for workerd/Cloudflare Workers |
| 176 | + */ |
| 177 | +export default { |
| 178 | + async fetch( |
| 179 | + request: Request, |
| 180 | + env: GatewayEnv, |
| 181 | + _ctx: ExecutionContext, |
| 182 | + ): Promise<Response> { |
| 183 | + const app = getAppForEnv(env) |
| 184 | + return app.handle(request) |
| 185 | + }, |
| 186 | +} |
| 187 | + |
| 188 | +// Standalone Server (for local dev) |
| 189 | + |
| 190 | +const isMainModule = typeof Bun !== 'undefined' && import.meta.path === Bun.main |
| 191 | + |
| 192 | +if (isMainModule) { |
| 193 | + const PORT = config.gatewayApiPort || CORE_PORTS.NODE_EXPLORER_API.get() |
| 194 | + const network = getCurrentNetwork() |
| 195 | + |
| 196 | + const app = createGatewayApp({ |
| 197 | + NETWORK: network, |
| 198 | + RPC_URL: process.env.RPC_URL || 'http://localhost:8545', |
| 199 | + FAUCET_PRIVATE_KEY: process.env.FAUCET_PRIVATE_KEY, |
| 200 | + }) |
| 201 | + |
| 202 | + const host = getLocalhostHost() |
| 203 | + app.listen(PORT, () => { |
| 204 | + console.log(`[Gateway] Worker running at http://${host}:${PORT}`) |
| 205 | + console.log(`[Gateway] Network: ${network}`) |
| 206 | + }) |
| 207 | +} |
0 commit comments