Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 39 additions & 3 deletions packages/predicate/src/lib/predicate.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -13,9 +15,12 @@ export class Predicate {

async evaluatePolicy(body: PredicateRequest): Promise<PredicateResponse> {
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),
});

Expand All @@ -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<Response> {
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");
}
}