From 36526b02e87adf171196edcde71a69519fa232df Mon Sep 17 00:00:00 2001 From: signature18632 Date: Fri, 10 Oct 2025 05:47:27 +0700 Subject: [PATCH] feat: update evaluate-policy request payload format --- docs/API.md | 8 ++++- packages/predicate/src/lib/predicate.ts | 42 +++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/docs/API.md b/docs/API.md index 01955ec..f85516e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -40,7 +40,13 @@ curl "$ENDPOINT/v1/token-maps/list?tokenIndexes=1&tokenIndexes=2&perPage=2" | jq curl "$ENDPOINT/v1/health" | jq curl -X POST "$ENDPOINT/v1/predicate/evaluate-policy" \ -H "Content-Type: application/json" \ - -d '{"policy": "sample_policy_data"}' | jq + -d '{ + "chain_id": 11155111, + "from": "0x", + "to": "0x", + "msg_value": "1000000000000000", + "data": "0x" + }' | jq # TX-Map Service curl "$ENDPOINT/v1/health" | jq diff --git a/packages/predicate/src/lib/predicate.ts b/packages/predicate/src/lib/predicate.ts index 4ae4d6f..d628b7f 100644 --- a/packages/predicate/src/lib/predicate.ts +++ b/packages/predicate/src/lib/predicate.ts @@ -1,8 +1,10 @@ -import { BadRequestError, config } from "@intmax2-function/shared"; +import { BadRequestError, config, logger, sleep } from "@intmax2-function/shared"; import type { PredicateRequest, PredicateResponse } from "../types"; export class Predicate { private static instance: Predicate | undefined; + private readonly maxRetries: number = 3; + private readonly initialDelayMs: number = 1000; public static async getInstance() { if (!Predicate.instance) { @@ -13,9 +15,12 @@ export class Predicate { async evaluatePolicy(body: PredicateRequest): Promise { try { - const response = await fetch(config.PREDICATE_API_URL, { + const response = await this.fetchWithRetry(config.PREDICATE_API_URL, { method: "POST", - headers: { "x-api-key": config.PREDICATE_API_KEY, "Content-Type": "application/json" }, + headers: { + "x-api-key": config.PREDICATE_API_KEY, + "Content-Type": "application/json", + }, body: JSON.stringify(body), }); @@ -29,4 +34,35 @@ export class Predicate { throw new BadRequestError(`Predicate API error: ${(error as Error).message}`); } } + + private async fetchWithRetry( + url: string, + options: RequestInit, + retries: number = this.maxRetries, + ): Promise { + let lastError: Error | undefined; + + for (let attempt = 0; attempt <= retries; attempt++) { + try { + const response = await fetch(url, options); + + if (response.ok || (response.status >= 400 && response.status < 500)) { + return response; + } + + lastError = new Error(`Server error: ${response.status}`); + } catch (error) { + lastError = error as Error; + } + + logger.warn(`Fetch attempt ${attempt + 1} failed: ${lastError?.message}`); + + if (attempt < retries) { + const delayMs = this.initialDelayMs * Math.pow(2, attempt); + await sleep(delayMs); + } + } + + throw lastError || new Error("Failed after retries"); + } }