@epitropos/sdk 0.0.0-stage → 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 alienx5499
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,55 @@
1
- # Temporary Holding Version
1
+ # @epitropos/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Protect an x402 call with the Epitropos escrow in one call. Hedera testnet only.
4
+
5
+ ## Quick start
6
+
7
+ ```ts
8
+ // bun add @epitropos/sdk @x402/hedera @hiero-ledger/sdk
9
+ import { createProtectedFetch } from "@epitropos/sdk";
10
+ import { PrivateKey } from "@hiero-ledger/sdk";
11
+ import { createClientHederaSigner } from "@x402/hedera";
12
+
13
+ const signer = createClientHederaSigner(accountId, PrivateKey.fromStringECDSA(key), {
14
+ network: "hedera:testnet",
15
+ });
16
+ const protectedFetch = createProtectedFetch({
17
+ signer,
18
+ network: "hedera:testnet",
19
+ ensRpcUrl: sepoliaRpcUrl,
20
+ });
21
+ const r = await protectedFetch("weather.epitropos.eth");
22
+ console.log(r.verdict, r.paymentTx, r.answer); // "pass" | "fail" | "cancelled_by_agent" | "held" | "refunded" | "unknown"
23
+ ```
24
+
25
+ You bring the signer, so you bring your own Hedera key. The package never reads env.
26
+ Pass `endpoint` (the escrow URL ending in `/api/call/`) to skip the ENS lookup, or `readText`
27
+ to use your own ENS reader. Without either `endpoint` or `ensRpcUrl` the call throws.
28
+ Set `maxTinybars` to cap what one call may spend; the default is 20 HBAR.
29
+
30
+ `quote("weather.epitropos.eth", { ensRpcUrl })` reads the price and payee without paying.
31
+
32
+ ## What you get back
33
+
34
+ `verdict`, `escrowId`, `paymentTx` (a HashScan link), `answer` (the seller's body as text) and
35
+ `refundNote` (set for every verdict but `pass` and `unknown`). `held` means a person must approve
36
+ the payout, or the scheduled refund returns the payment; `refunded` means the payment already went
37
+ back. `unknown` means the escrow has no verdict yet. A broken seller promise or a rejected payment throws `CallFailedError`
38
+ with the HTTP status and body. A missing ENS record throws `EndpointNotFoundError`.
39
+
40
+ ## When the check fails
41
+
42
+ My escrow holds your payment until it has checked the seller's answer against the seller's ENS
43
+ promise. If the answer breaks the promise, you get the money back. The refund is a scheduled
44
+ Hedera transaction made when the payment arrives, so it fires at expiry on its own, even if
45
+ Epitropos is down.
46
+
47
+ ## Fees
48
+
49
+ The escrow keeps 3% of the price (`FEE_BPS` is 300 basis points), with a floor of 0.5 HBAR
50
+ (`MIN_FEE_TINYBARS` is 50,000,000), and only when the answer passes. The seller pays it out of the
51
+ price; you pay the price. A fail or an AI judge cancel refunds you the full price.
52
+
53
+ ## Testnet only
54
+
55
+ This runs on Hedera testnet with test HBAR. Do not point it at mainnet keys.
@@ -0,0 +1,10 @@
1
+ import { type TextReader } from "./ens-text.ts";
2
+ export type EndpointSource = {
3
+ readonly endpoint?: string;
4
+ readonly ensRpcUrl?: string;
5
+ readonly readText?: TextReader;
6
+ };
7
+ export declare const ESCROW_ENS_NAME = "epitropos.eth";
8
+ export declare const ENDPOINT_KEY = "agent-endpoint[web]";
9
+ export declare const checkEndpoint: (base: string) => string;
10
+ export declare const sellerUrlResolver: (src: EndpointSource) => (seller: string) => Promise<string>;
@@ -0,0 +1,43 @@
1
+ import { viemTextReader } from "./ens-text.js";
2
+ import { EndpointNotFoundError } from "./errors.js";
3
+ export const ESCROW_ENS_NAME = "epitropos.eth";
4
+ // The SDK is installed outside this repo, so it keeps its own copy; a test pins it to shared-kernel.
5
+ export const ENDPOINT_KEY = "agent-endpoint[web]";
6
+ const textReaderFor = (src) => {
7
+ if (src.readText)
8
+ return src.readText;
9
+ if (!src.ensRpcUrl) {
10
+ throw new Error("pass endpoint, ensRpcUrl or readText: the package reads no env");
11
+ }
12
+ return viemTextReader(src.ensRpcUrl);
13
+ };
14
+ // The base comes from ENS or the caller and decides where money is sent, so it must be an https
15
+ // URL on the paid-call path. Plain http is allowed only for a loopback host during local runs.
16
+ export const checkEndpoint = (base) => {
17
+ let url;
18
+ try {
19
+ url = new URL(base);
20
+ }
21
+ catch {
22
+ throw new Error("escrow endpoint is not a valid URL");
23
+ }
24
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
25
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
26
+ throw new Error("escrow endpoint must use https");
27
+ }
28
+ if (!url.pathname.endsWith("/api/call/") || url.search || url.hash || url.username) {
29
+ throw new Error("escrow endpoint must end in /api/call/ with no query, fragment or credentials");
30
+ }
31
+ return url.href;
32
+ };
33
+ // Returns a resolver for the URL of one seller. The ENS record holds the base URL that ends in
34
+ // /api/call/, so the seller name is appended. An explicit endpoint skips ENS.
35
+ export const sellerUrlResolver = (src) => {
36
+ const read = src.endpoint ? null : textReaderFor(src);
37
+ return async (seller) => {
38
+ const base = src.endpoint ?? (await read?.(ESCROW_ENS_NAME, ENDPOINT_KEY));
39
+ if (!base)
40
+ throw new EndpointNotFoundError(ESCROW_ENS_NAME, ENDPOINT_KEY);
41
+ return `${checkEndpoint(base)}${encodeURIComponent(seller)}`;
42
+ };
43
+ };
@@ -0,0 +1,2 @@
1
+ export type TextReader = (name: string, key: string) => Promise<string | null>;
2
+ export declare const viemTextReader: (rpcUrl: string, universalResolverAddress?: `0x${string}`) => TextReader;
@@ -0,0 +1,12 @@
1
+ import { createPublicClient, http } from "viem";
2
+ import { sepolia } from "viem/chains";
3
+ // Reads go through the Universal Resolver; multicall batching folds same-tick reads into one call.
4
+ // No retries: viem's default 3 retries turn the 4 s budget into 17 s while an RPC hangs.
5
+ export const viemTextReader = (rpcUrl, universalResolverAddress) => {
6
+ const client = createPublicClient({
7
+ chain: sepolia,
8
+ transport: http(rpcUrl, { timeout: 4000, retryCount: 0 }),
9
+ batch: { multicall: true },
10
+ });
11
+ return async (name, key) => (await client.getEnsText({ name, key, universalResolverAddress })) ?? null;
12
+ };
@@ -0,0 +1,10 @@
1
+ export declare class EndpointNotFoundError extends Error {
2
+ readonly ensName: string;
3
+ readonly key: string;
4
+ constructor(ensName: string, key: string);
5
+ }
6
+ export declare class CallFailedError extends Error {
7
+ readonly status: number;
8
+ readonly body: string;
9
+ constructor(status: number, body: string);
10
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,22 @@
1
+ export class EndpointNotFoundError extends Error {
2
+ ensName;
3
+ key;
4
+ constructor(ensName, key) {
5
+ super(`${ensName} has no ${key} record; pass endpoint`);
6
+ this.ensName = ensName;
7
+ this.key = key;
8
+ this.name = "EndpointNotFoundError";
9
+ }
10
+ }
11
+ // The escrow answered with something other than a finished call: a broken promise (424), a
12
+ // rejected payment (402) or a server fault.
13
+ export class CallFailedError extends Error {
14
+ status;
15
+ body;
16
+ constructor(status, body) {
17
+ super(`HTTP ${status} ${body}`);
18
+ this.status = status;
19
+ this.body = body;
20
+ this.name = "CallFailedError";
21
+ }
22
+ }
@@ -0,0 +1,6 @@
1
+ export { checkEndpoint, ENDPOINT_KEY, ESCROW_ENS_NAME } from "./endpoint.ts";
2
+ export { type TextReader, viemTextReader } from "./ens-text.ts";
3
+ export { CallFailedError, EndpointNotFoundError } from "./errors.ts";
4
+ export { createProtectedFetch, type ProtectedFetchOptions, type ProtectedResult, type Verdict, } from "./protected-fetch.ts";
5
+ export { type Quote, quote } from "./quote.ts";
6
+ export { hbarPayingFetch, hbarX402Client } from "./x402-buyer.ts";
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { checkEndpoint, ENDPOINT_KEY, ESCROW_ENS_NAME } from "./endpoint.js";
2
+ export { viemTextReader } from "./ens-text.js";
3
+ export { CallFailedError, EndpointNotFoundError } from "./errors.js";
4
+ export { createProtectedFetch, } from "./protected-fetch.js";
5
+ export { quote } from "./quote.js";
6
+ export { hbarPayingFetch, hbarX402Client } from "./x402-buyer.js";
@@ -0,0 +1,18 @@
1
+ import type { ClientHederaSigner } from "@x402/hedera";
2
+ import { type EndpointSource } from "./endpoint.ts";
3
+ export declare const hashscanTx: (txId: string) => string;
4
+ export type Verdict = "pass" | "fail" | "cancelled_by_agent" | "held" | "refunded" | "unknown";
5
+ export type ProtectedResult = {
6
+ readonly verdict: Verdict;
7
+ readonly escrowId: string;
8
+ readonly paymentTx: string;
9
+ readonly answer: string;
10
+ readonly refundNote: string | null;
11
+ };
12
+ export type ProtectedFetchOptions = EndpointSource & {
13
+ readonly signer: ClientHederaSigner;
14
+ readonly network: "hedera:testnet";
15
+ readonly maxTinybars?: string;
16
+ readonly fetch?: typeof fetch;
17
+ };
18
+ export declare const createProtectedFetch: (opts: ProtectedFetchOptions) => (seller: string, init?: RequestInit) => Promise<ProtectedResult>;
@@ -0,0 +1,38 @@
1
+ import { sellerUrlResolver } from "./endpoint.js";
2
+ import { CallFailedError } from "./errors.js";
3
+ import { hbarPayingFetch } from "./x402-buyer.js";
4
+ // Same rule as shared-kernel's hashscanTx (a test pins them): "0.0.1@123.456" -> "0.0.1-123-456".
5
+ export const hashscanTx = (txId) => {
6
+ const [account, time] = txId.split("@");
7
+ const key = time ? `${account}-${time.replace(".", "-")}` : txId;
8
+ return `https://hashscan.io/testnet/transaction/${key}`;
9
+ };
10
+ const REFUND_NOTE = "the scheduled refund returns your payment by itself at expiry";
11
+ const NOTES = {
12
+ pass: null,
13
+ fail: REFUND_NOTE,
14
+ cancelled_by_agent: "the AI judge cancelled the payment and refunds it now; the scheduled refund is the backstop",
15
+ held: `held for a person to approve; unless approved, ${REFUND_NOTE}`,
16
+ refunded: "your payment was refunded",
17
+ unknown: null,
18
+ };
19
+ // Any other header value is an escrow state that has no verdict yet, such as "opened".
20
+ const toVerdict = (raw) => raw && raw !== "unknown" && Object.hasOwn(NOTES, raw) ? raw : "unknown";
21
+ export const createProtectedFetch = (opts) => {
22
+ const paying = hbarPayingFetch(opts.signer, opts.maxTinybars ?? "2000000000", opts.fetch);
23
+ const urlFor = sellerUrlResolver(opts);
24
+ return async (seller, init) => {
25
+ const res = await paying(await urlFor(seller), init);
26
+ if (res.status !== 200)
27
+ throw new CallFailedError(res.status, await res.text());
28
+ const verdict = toVerdict(res.headers.get("X-Epitropos-Verdict"));
29
+ const escrowId = res.headers.get("X-Epitropos-Escrow") ?? "";
30
+ return {
31
+ verdict,
32
+ escrowId,
33
+ paymentTx: escrowId ? hashscanTx(escrowId) : "",
34
+ answer: await res.text(),
35
+ refundNote: NOTES[verdict],
36
+ };
37
+ };
38
+ };
@@ -0,0 +1,11 @@
1
+ import { type EndpointSource } from "./endpoint.ts";
2
+ export type Quote = {
3
+ readonly seller: string;
4
+ readonly price: string;
5
+ readonly asset: string;
6
+ readonly payTo: string;
7
+ readonly accepts: readonly unknown[];
8
+ };
9
+ export declare const quote: (seller: string, src?: EndpointSource & {
10
+ readonly fetch?: typeof fetch;
11
+ }) => Promise<Quote>;
package/dist/quote.js ADDED
@@ -0,0 +1,18 @@
1
+ import { sellerUrlResolver } from "./endpoint.js";
2
+ import { CallFailedError } from "./errors.js";
3
+ // An unpaid GET: the escrow answers 402 with the payment terms and moves no money.
4
+ export const quote = async (seller, src = {}) => {
5
+ const res = await (src.fetch ?? fetch)(await sellerUrlResolver(src)(seller));
6
+ const body = await res.text();
7
+ if (res.status !== 402)
8
+ throw new CallFailedError(res.status, body);
9
+ const accepts = JSON.parse(body).accepts ?? [];
10
+ const first = accepts[0] ?? {};
11
+ return {
12
+ seller,
13
+ price: first.amount ?? "",
14
+ asset: first.asset ?? "",
15
+ payTo: first.payTo ?? "",
16
+ accepts,
17
+ };
18
+ };
@@ -0,0 +1,4 @@
1
+ import { x402Client } from "@x402/core/client";
2
+ import type { ClientHederaSigner } from "@x402/hedera";
3
+ export declare const hbarX402Client: (signer: ClientHederaSigner, maxTinybars: string) => x402Client;
4
+ export declare const hbarPayingFetch: (signer: ClientHederaSigner, maxTinybars: string, base?: typeof fetch) => (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
@@ -0,0 +1,17 @@
1
+ import { x402Client } from "@x402/core/client";
2
+ import { wrapFetchWithPayment } from "@x402/fetch";
3
+ import { ExactHederaScheme } from "@x402/hedera/exact/client";
4
+ // The buyer side of x402, shared by the SDK, the CLI agent, the browser wallet and the demo buyer.
5
+ // Only Hedera testnet is registered, and an HBAR payment above maxTinybars is refused before the
6
+ // signer is asked.
7
+ export const hbarX402Client = (signer, maxTinybars) => {
8
+ const client = new x402Client().register("hedera:testnet", new ExactHederaScheme(signer));
9
+ // HBAR is not a default x402 asset, so it has to be allowed by name.
10
+ client.setSpendControls({
11
+ allowedAssets: [
12
+ { network: "hedera:testnet", asset: "0.0.0", maxAmountPerPayment: maxTinybars },
13
+ ],
14
+ });
15
+ return client;
16
+ };
17
+ export const hbarPayingFetch = (signer, maxTinybars, base = fetch) => wrapFetchWithPayment(base, hbarX402Client(signer, maxTinybars));
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@epitropos/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Protect any x402 call on Hedera testnet with the Epitropos escrow",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./x402": {
15
+ "types": "./dist/x402-buyer.d.ts",
16
+ "import": "./dist/x402-buyer.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "dependencies": {
25
+ "@x402/core": "2.32.0",
26
+ "@x402/fetch": "2.32.0",
27
+ "@x402/hedera": "2.32.0",
28
+ "viem": "2.58.8"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/alienx5499/Epitropos.git",
33
+ "directory": "packages/sdk"
34
+ },
35
+ "homepage": "https://epitropos.0xprabal.com/integrate",
36
+ "bugs": "https://github.com/alienx5499/Epitropos/issues",
37
+ "keywords": [
38
+ "x402",
39
+ "hedera",
40
+ "escrow",
41
+ "ens",
42
+ "ai-agents",
43
+ "refund"
44
+ ],
45
+ "engines": {
46
+ "node": ">=20"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }