surety-provider 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 +21 -0
- package/README.md +100 -2
- package/cli.js +96 -0
- package/index.d.ts +129 -0
- package/index.js +15 -0
- package/lib/bond.js +150 -0
- package/lib/check.js +106 -0
- package/lib/surety.js +191 -0
- package/lib/try.js +58 -0
- package/package.json +26 -4
- package/template/app.js +41 -0
- package/template/env.example +16 -0
- package/template/gitignore +5 -0
- package/template/package.json +19 -0
- package/template/vercel.json +4 -0
- package/template/vercelignore +4 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jay Turner
|
|
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,101 @@
|
|
|
1
|
-
#
|
|
1
|
+
# surety-provider
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Launch a paid [x402](https://www.x402.org) API on Monad with a bond behind it. When one of your paid calls comes back slow or in the wrong shape, the caller is refunded on-chain from your bond. That is a reason for an AI agent to pick your API over one with nothing at stake.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
npm install surety-provider
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
const { serve } = require("surety-provider");
|
|
11
|
+
|
|
12
|
+
serve({
|
|
13
|
+
payTo: "0xYourWallet",
|
|
14
|
+
endpoints: [{ path: "/v1/hello", maxLatencyMs: 4000, handler: () => ({ hello: "world" }) }],
|
|
15
|
+
});
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
That is a working paid API. It charges $0.001 per call over x402, and publishes the promise it will be held to at `/.well-known/surety.json`.
|
|
19
|
+
|
|
20
|
+
**Status: beta.** Runs on Monad testnet by default and on Monad mainnet with one setting. The Surety vault contract has not been independently audited. Read the [threat model](https://github.com/j-6-z/surety/blob/main/audit/THREAT_MODEL.md) before bonding real money.
|
|
21
|
+
|
|
22
|
+
## From nothing to bonded
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
npx surety-provider init my-api
|
|
26
|
+
cd my-api
|
|
27
|
+
npm install
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
1. Copy `.env.example` to `.env` and set `PAY_TO_ADDRESS` to the wallet your payments should land in.
|
|
31
|
+
2. Edit the endpoints in `app.js`.
|
|
32
|
+
3. `npm start`, then `npm run check` to time every endpoint against its own promise. No payment involved.
|
|
33
|
+
4. Host it. It runs on Vercel as it is. Set `PAY_TO_ADDRESS` and `PUBLIC_URL` on the host.
|
|
34
|
+
5. Put a wallet key in `.env` as `PRIVATE_KEY`, then `npm run bond -- https://your-api.example`.
|
|
35
|
+
6. `npm run try -- https://your-api.example/v1/shout/hello` makes one real paid call through the relay.
|
|
36
|
+
|
|
37
|
+
Your wallet key stays on your own computer. The hosted API never needs it.
|
|
38
|
+
|
|
39
|
+
## An endpoint
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
{
|
|
43
|
+
method: "GET", // default
|
|
44
|
+
path: "/v1/pool/:address",
|
|
45
|
+
price: "$0.002", // default: the API's price
|
|
46
|
+
maxLatencyMs: 4000, // THE PROMISE: answer within this
|
|
47
|
+
responseSchema: { /* JSON Schema */ },// THE PROMISE: in this shape
|
|
48
|
+
example: "/v1/pool/0xabc", // a real call `check` can try
|
|
49
|
+
validate: (req) => null, // runs before payment; return a message to reject for free
|
|
50
|
+
handler: async (req) => ({ /* … */ }),// THE WORK
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Four rules that save you money:
|
|
55
|
+
|
|
56
|
+
- **The clock includes payment.** `maxLatencyMs` covers the whole call, and settling the payment takes a second or more. Promise what you can keep.
|
|
57
|
+
- **The library gives up before you pay for being late.** A handler still running with 2 seconds of its promise left is cut off with a 504. The caller is not charged, so nothing comes out of your bond. Change the margin with `settleReserveMs`, or set `guard: false` on an endpoint.
|
|
58
|
+
- **Throwing is free for the caller.** A handler that throws answers with an error and charges nobody.
|
|
59
|
+
- **`validate` runs before payment.** Reject bad input there so nobody pays for a typo.
|
|
60
|
+
|
|
61
|
+
## API
|
|
62
|
+
|
|
63
|
+
| Function | What it does |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `serve(options, { port, host })` | `createBondedApi` and listen. Reads `PORT`, `PAY_TO_ADDRESS` and the public address from the environment |
|
|
66
|
+
| `createBondedApi(options)` | Builds the Express app and the SLA document. Returns `{ app, sla, listen, close, endpoints, run }` |
|
|
67
|
+
| `check(api)` / `report(api)` | Runs every handler a few times, unpaid, and compares it with its promise |
|
|
68
|
+
| `bond({ url, wallet, amount })` | Lists a hosted API on the vault and tops its bond up. Approves exactly what it deposits |
|
|
69
|
+
| `tryCall({ suretyUrl, provider, path, privateKey })` | One real paid call through the relay, with the verdict |
|
|
70
|
+
| `publicUrlFromEnv()`, `networkFromEnv()` | The settings below, resolved |
|
|
71
|
+
|
|
72
|
+
Options for `createBondedApi` and `serve`: `name`, `description`, `payTo`, `endpoints`, `price`, `publicUrl`, `settleReserveMs`, and `network`, `usdc`, `facilitatorUrl` if you need to override the network profile. Types are included.
|
|
73
|
+
|
|
74
|
+
## Command line
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
surety-provider init [folder] start a new bonded API
|
|
78
|
+
surety-provider check [file] time every endpoint against its promise (default file: ./app.js)
|
|
79
|
+
surety-provider bond <url> [usdc] list your hosted API and post its bond (default: the minimum)
|
|
80
|
+
surety-provider try <endpoint-url> one real paid call through the relay
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`check` needs your file to export what `createBondedApi` returned: `module.exports.api = api`.
|
|
84
|
+
|
|
85
|
+
## Settings
|
|
86
|
+
|
|
87
|
+
| Variable | Where | What |
|
|
88
|
+
| --- | --- | --- |
|
|
89
|
+
| `PAY_TO_ADDRESS` | host and local | The wallet payments land in |
|
|
90
|
+
| `PUBLIC_URL` | host | Your https address, no slash at the end. Vercel, Render and Railway are detected if you leave it out |
|
|
91
|
+
| `SURETY_NETWORK` | host and local | Leave out for Monad testnet. `mainnet` for real USDC |
|
|
92
|
+
| `PRIVATE_KEY` | local only | The wallet that posts the bond. Never put it on the host |
|
|
93
|
+
| `SURETY_URL` | local | The relay to join. Default `https://www.surety.buzz` |
|
|
94
|
+
|
|
95
|
+
## What Surety checks, and what it does not
|
|
96
|
+
|
|
97
|
+
The relay checks three things about each paid call: the status code, the time taken, and the shape of the JSON. It does not judge whether your answer was *good*. One relay, run by the Surety project, makes that call today, and its verdict moves money out of your bond.
|
|
98
|
+
|
|
99
|
+
On the current mainnet vault, one refund is capped at 5% of the minimum bond, and refunds against one provider stop for the day at 20% of its cover. A call priced above the first cap cannot be refunded.
|
|
100
|
+
|
|
101
|
+
MIT licence. Source and issues: https://github.com/j-6-z/surety
|
package/cli.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Command line for surety-provider.
|
|
3
|
+
//
|
|
4
|
+
// surety-provider init [folder] start a new bonded API from the template
|
|
5
|
+
// surety-provider check [file] time every endpoint against its promise (no payment)
|
|
6
|
+
// surety-provider bond <url> [usdc] list your hosted API and post its bond
|
|
7
|
+
// surety-provider try <endpoint-url> one real paid call through the relay
|
|
8
|
+
const fs = require("fs");
|
|
9
|
+
const path = require("path");
|
|
10
|
+
|
|
11
|
+
const USAGE = `surety-provider <command>
|
|
12
|
+
|
|
13
|
+
init [folder] Start a new bonded API in a folder (default: my-bonded-api)
|
|
14
|
+
check [file] Time every endpoint in your app against its own promise. No payment.
|
|
15
|
+
The file (default: ./app.js) must export the result of createBondedApi as "api".
|
|
16
|
+
bond <url> [usdc] List your hosted API on the vault and post its bond (default: the minimum).
|
|
17
|
+
Needs PRIVATE_KEY in .env or the environment.
|
|
18
|
+
try <endpoint-url> Make one real paid call through the Surety relay and print the verdict.
|
|
19
|
+
|
|
20
|
+
Runs on Monad testnet unless SURETY_NETWORK=mainnet. Docs: https://www.surety.buzz/kit/`;
|
|
21
|
+
|
|
22
|
+
/// Copies the starter files into a new folder. Refuses to write into a folder that has files in it.
|
|
23
|
+
function init(dir, { log = console.log } = {}) {
|
|
24
|
+
const target = path.resolve(dir || "my-bonded-api");
|
|
25
|
+
if (fs.existsSync(target) && fs.readdirSync(target).length) throw new Error(`${target} already has files in it. Pick an empty or new folder.`);
|
|
26
|
+
fs.mkdirSync(target, { recursive: true });
|
|
27
|
+
const from = path.join(__dirname, "template");
|
|
28
|
+
// npm will not ship files named .gitignore or .env.example reliably, so the template stores them undotted.
|
|
29
|
+
const names = { gitignore: ".gitignore", "env.example": ".env.example", vercelignore: ".vercelignore" };
|
|
30
|
+
for (const f of fs.readdirSync(from)) fs.copyFileSync(path.join(from, f), path.join(target, names[f] || f));
|
|
31
|
+
const pkgPath = path.join(target, "package.json");
|
|
32
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
|
|
33
|
+
pkg.name = path.basename(target).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "my-bonded-api";
|
|
34
|
+
pkg.dependencies["surety-provider"] = `^${require("./package.json").version}`;
|
|
35
|
+
fs.writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
|
36
|
+
log(`Created ${target}\n\nNext:\n cd ${path.relative(process.cwd(), target) || "."}\n npm install\n copy .env.example to .env and set PAY_TO_ADDRESS\n npm start`);
|
|
37
|
+
return target;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// Loads the user's app file and returns the object createBondedApi gave them.
|
|
41
|
+
function loadApi(file) {
|
|
42
|
+
const full = path.resolve(file || "app.js");
|
|
43
|
+
if (!fs.existsSync(full)) throw new Error(`No file at ${full}. Give the file that creates your API: surety-provider check ./app.js`);
|
|
44
|
+
const mod = require(full);
|
|
45
|
+
const api = mod && (mod.api || (mod.endpoints && mod.run ? mod : null));
|
|
46
|
+
if (!api) throw new Error(`${path.basename(full)} must export what createBondedApi returned, as "api":\n module.exports.api = api;`);
|
|
47
|
+
return api;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function main(argv, { log = console.log } = {}) {
|
|
51
|
+
const [command, ...rest] = argv;
|
|
52
|
+
if (!command || command === "help" || command === "--help" || command === "-h") {
|
|
53
|
+
log(USAGE);
|
|
54
|
+
return 0;
|
|
55
|
+
}
|
|
56
|
+
if (command === "--version" || command === "-v") {
|
|
57
|
+
log(require("./package.json").version);
|
|
58
|
+
return 0;
|
|
59
|
+
}
|
|
60
|
+
if (command === "init") {
|
|
61
|
+
init(rest[0], { log });
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
require("dotenv").config({ quiet: true });
|
|
66
|
+
} catch {
|
|
67
|
+
/* no .env support installed: the environment is used as it is */
|
|
68
|
+
}
|
|
69
|
+
if (command === "check") {
|
|
70
|
+
const failed = await require("./lib/check").report(loadApi(rest[0]), { log, tryCommand: "npx surety-provider try <endpoint-url>" });
|
|
71
|
+
return failed ? 1 : 0;
|
|
72
|
+
}
|
|
73
|
+
if (command === "bond") {
|
|
74
|
+
if (!rest[0]) throw new Error("Give the public address of your API: surety-provider bond https://your-api.example");
|
|
75
|
+
const { bondFromEnv, explain } = require("./lib/bond");
|
|
76
|
+
await bondFromEnv({ url: rest[0], amount: rest[1], log }).catch((e) => { throw new Error(explain(e)); });
|
|
77
|
+
return 0;
|
|
78
|
+
}
|
|
79
|
+
if (command === "try") {
|
|
80
|
+
await require("./lib/try").tryFromEnv({ target: rest[0], log, usage: "surety-provider try https://your-api.example/v1/block" });
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
throw new Error(`Unknown command "${command}".\n\n${USAGE}`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
module.exports = { main, init, loadApi, USAGE };
|
|
87
|
+
|
|
88
|
+
if (require.main === module) {
|
|
89
|
+
main(process.argv.slice(2)).then(
|
|
90
|
+
(code) => process.exit(code),
|
|
91
|
+
(e) => {
|
|
92
|
+
console.error(`STOPPED: ${e.shortMessage || e.message}`);
|
|
93
|
+
process.exit(1);
|
|
94
|
+
}
|
|
95
|
+
);
|
|
96
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Types for surety-provider.
|
|
2
|
+
import type { Application, Request } from "express";
|
|
3
|
+
import type { Signer } from "ethers";
|
|
4
|
+
|
|
5
|
+
/** One paid endpoint and the promise it is bonded against. */
|
|
6
|
+
export interface Endpoint {
|
|
7
|
+
/** HTTP method. Default "GET". */
|
|
8
|
+
method?: string;
|
|
9
|
+
/** Express-style path, e.g. "/v1/pool/:address". */
|
|
10
|
+
path: string;
|
|
11
|
+
description?: string;
|
|
12
|
+
/** Price for one call, e.g. "$0.001". Defaults to the API's price. */
|
|
13
|
+
price?: string;
|
|
14
|
+
/** THE PROMISE: answer within this many milliseconds, measured by the relay and including payment settlement. */
|
|
15
|
+
maxLatencyMs: number;
|
|
16
|
+
/** THE PROMISE: JSON Schema every 2xx answer must match. */
|
|
17
|
+
responseSchema?: object;
|
|
18
|
+
/** A real path `check` can call when `path` has a :parameter, e.g. "/v1/pool/0xabc". */
|
|
19
|
+
example?: string;
|
|
20
|
+
/** Request body `check` should send with the example. */
|
|
21
|
+
exampleBody?: unknown;
|
|
22
|
+
/** Set false to turn off the deadline that answers 504 (uncharged) before a late answer would cost your bond. */
|
|
23
|
+
guard?: boolean;
|
|
24
|
+
/** Runs before payment. Return a message to reject the call with 400, free of charge. */
|
|
25
|
+
validate?: (req: Request) => string | null | undefined;
|
|
26
|
+
/** THE WORK. Return the JSON answer. Throwing answers with an error, and the caller is not charged. */
|
|
27
|
+
handler: (req: Request) => unknown | Promise<unknown>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface BondedApiOptions {
|
|
31
|
+
/** Shown at "/". */
|
|
32
|
+
name?: string;
|
|
33
|
+
description?: string;
|
|
34
|
+
/** Wallet that receives the payments. `serve` falls back to PAY_TO_ADDRESS. */
|
|
35
|
+
payTo?: string;
|
|
36
|
+
endpoints: Endpoint[];
|
|
37
|
+
/** Default price per call. Default "$0.001". */
|
|
38
|
+
price?: string;
|
|
39
|
+
/** Public https address once hosted. `serve` falls back to PUBLIC_URL and the host's own variables. */
|
|
40
|
+
publicUrl?: string;
|
|
41
|
+
/** Milliseconds kept back for payment settlement. Default 2000. */
|
|
42
|
+
settleReserveMs?: number;
|
|
43
|
+
/** CAIP-2 network id. Default: Monad testnet, or mainnet when SURETY_NETWORK=mainnet. */
|
|
44
|
+
network?: string;
|
|
45
|
+
/** Payment token address on that network. */
|
|
46
|
+
usdc?: string;
|
|
47
|
+
facilitatorUrl?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The SLA document served at /.well-known/surety.json. */
|
|
51
|
+
export interface SlaDocument {
|
|
52
|
+
version: 1;
|
|
53
|
+
baseUrl: string;
|
|
54
|
+
payTo: string;
|
|
55
|
+
endpoints: Array<{ method: string; path: string; maxLatencyMs: number; responseSchema?: object }>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface BondedApi {
|
|
59
|
+
/** The Express app. Export it for hosts such as Vercel. */
|
|
60
|
+
app: Application;
|
|
61
|
+
sla(): SlaDocument;
|
|
62
|
+
slaUrl(): string;
|
|
63
|
+
endpoints: Array<Endpoint & { method: string; price: string; deadlineMs: number | null }>;
|
|
64
|
+
/** Runs one endpoint's handler under its deadline. */
|
|
65
|
+
run(endpoint: Endpoint, req: Request): Promise<unknown>;
|
|
66
|
+
settleReserveMs: number;
|
|
67
|
+
/** Starts listening. Resolves to the address it is reachable at. */
|
|
68
|
+
listen(port?: number, host?: string): Promise<string>;
|
|
69
|
+
close(): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface NetworkProfile {
|
|
73
|
+
key: "testnet" | "mainnet";
|
|
74
|
+
network: string;
|
|
75
|
+
usdc: string;
|
|
76
|
+
rpc: string;
|
|
77
|
+
facilitatorUrl: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Builds the paid API and its SLA document. Does not start listening. */
|
|
81
|
+
export function createBondedApi(options: BondedApiOptions & { payTo: string }): BondedApi;
|
|
82
|
+
/** createBondedApi and listen, reading PORT, PAY_TO_ADDRESS and the public address from the environment. */
|
|
83
|
+
export function serve(options: BondedApiOptions, how?: { port?: number; host?: string; log?: (m: string) => void }): Promise<BondedApi & { url: string }>;
|
|
84
|
+
/** The public https address of this server, from PUBLIC_URL or the host's own variables. */
|
|
85
|
+
export function publicUrlFromEnv(env?: NodeJS.ProcessEnv): string;
|
|
86
|
+
/** Testnet unless SURETY_NETWORK=mainnet. */
|
|
87
|
+
export function networkFromEnv(env?: NodeJS.ProcessEnv): NetworkProfile;
|
|
88
|
+
export const MONAD_TESTNET: Omit<NetworkProfile, "key">;
|
|
89
|
+
export const MONAD_MAINNET: Omit<NetworkProfile, "key">;
|
|
90
|
+
|
|
91
|
+
export interface BondResult {
|
|
92
|
+
provider: string;
|
|
93
|
+
active: boolean;
|
|
94
|
+
bond: bigint;
|
|
95
|
+
slaUrl: string;
|
|
96
|
+
vault: string;
|
|
97
|
+
callUrls: string[];
|
|
98
|
+
}
|
|
99
|
+
/** Lists a hosted API on the vault and tops its bond up to `amount` USDC (default: the vault minimum). */
|
|
100
|
+
export function bond(options: { url: string; wallet: Signer; suretyUrl?: string; amount?: string; vaultAddress?: string; log?: (m: string) => void }): Promise<BondResult>;
|
|
101
|
+
/** `bond` using PRIVATE_KEY and SURETY_NETWORK from the environment. */
|
|
102
|
+
export function bondFromEnv(options: { url: string; amount?: string; env?: NodeJS.ProcessEnv; log?: (m: string) => void }): Promise<BondResult>;
|
|
103
|
+
|
|
104
|
+
export interface CheckResult {
|
|
105
|
+
endpoint: string;
|
|
106
|
+
ok: boolean;
|
|
107
|
+
level: "ok" | "tight" | "fail";
|
|
108
|
+
worstMs?: number;
|
|
109
|
+
budgetMs?: number;
|
|
110
|
+
note: string;
|
|
111
|
+
}
|
|
112
|
+
/** Runs every handler a few times with no payment and compares it with its own promise. */
|
|
113
|
+
export function check(api: BondedApi, options?: { runs?: number }): Promise<CheckResult[]>;
|
|
114
|
+
/** `check`, printed. Resolves to the number of endpoints that did not keep their promise. */
|
|
115
|
+
export function report(api: BondedApi, options?: { log?: (m: string) => void; tryCommand?: string }): Promise<number>;
|
|
116
|
+
|
|
117
|
+
export interface TryResult {
|
|
118
|
+
status: number;
|
|
119
|
+
body: string;
|
|
120
|
+
verdict: string | null;
|
|
121
|
+
reason: string | null;
|
|
122
|
+
latencyMs: number;
|
|
123
|
+
claim: string | null;
|
|
124
|
+
claimTx: string | null;
|
|
125
|
+
}
|
|
126
|
+
/** One real paid call to `path` on `provider` through the relay. */
|
|
127
|
+
export function tryCall(options: { suretyUrl: string; provider: string; path: string; privateKey: string; network?: string; usdc?: string }): Promise<TryResult>;
|
|
128
|
+
/** `tryCall` for one endpoint address, paying from PRIVATE_KEY in the environment. */
|
|
129
|
+
export function tryFromEnv(options: { target: string; env?: NodeJS.ProcessEnv; log?: (m: string) => void; usage?: string }): Promise<TryResult>;
|
package/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// surety-provider: a paid x402 API on Monad with a bond behind it.
|
|
2
|
+
//
|
|
3
|
+
// const { serve } = require("surety-provider");
|
|
4
|
+
// serve({
|
|
5
|
+
// payTo: "0xYourWallet",
|
|
6
|
+
// endpoints: [{ path: "/v1/hello", maxLatencyMs: 4000, handler: () => ({ hello: "world" }) }],
|
|
7
|
+
// });
|
|
8
|
+
//
|
|
9
|
+
// Then post a bond so its calls are covered: npx surety-provider bond https://your-api.example
|
|
10
|
+
const surety = require("./lib/surety");
|
|
11
|
+
const { bond, bondFromEnv } = require("./lib/bond");
|
|
12
|
+
const { check, report } = require("./lib/check");
|
|
13
|
+
const { tryCall, tryFromEnv } = require("./lib/try");
|
|
14
|
+
|
|
15
|
+
module.exports = { ...surety, bond, bondFromEnv, check, report, tryCall, tryFromEnv };
|
package/lib/bond.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Post a bond for your hosted API so its calls are covered by Surety.
|
|
2
|
+
//
|
|
3
|
+
// npm run bond -- https://your-api.example bond the minimum
|
|
4
|
+
// npm run bond -- https://your-api.example 5 bond 5 USDC in total
|
|
5
|
+
//
|
|
6
|
+
// Run this on your own computer. It needs PRIVATE_KEY in .env: a wallet holding
|
|
7
|
+
// a little MON (for fees) and the USDC you are bonding. The hosted API never needs that key.
|
|
8
|
+
const { ethers } = require("ethers");
|
|
9
|
+
|
|
10
|
+
const VAULT_ABI = [
|
|
11
|
+
"function register(string)",
|
|
12
|
+
"function setMetadata(string)",
|
|
13
|
+
"function depositBond(uint256)",
|
|
14
|
+
"function isActive(address) view returns (bool)",
|
|
15
|
+
"function minProviderBond() view returns (uint256)",
|
|
16
|
+
"function providers(address) view returns (bool registered, uint64 bondReadyAt, uint64 claimCount, uint128 bond, uint128 bondPendingWithdraw, uint128 backingAssets, uint128 claimsPaid, uint256 backingShares, uint256 backingSharesPending, string metadataURI)",
|
|
17
|
+
];
|
|
18
|
+
const ERC20_ABI = [
|
|
19
|
+
"function approve(address, uint256) returns (bool)",
|
|
20
|
+
"function balanceOf(address) view returns (uint256)",
|
|
21
|
+
"function allowance(address, address) view returns (uint256)",
|
|
22
|
+
];
|
|
23
|
+
const fmt = (v) => ethers.formatUnits(v, 6);
|
|
24
|
+
const stop = (message) => Object.assign(new Error(message), { expected: true });
|
|
25
|
+
|
|
26
|
+
async function getJson(url, what, opts = {}) {
|
|
27
|
+
let res;
|
|
28
|
+
try {
|
|
29
|
+
res = await fetch(url, { signal: AbortSignal.timeout(15_000), ...opts });
|
|
30
|
+
} catch (e) {
|
|
31
|
+
throw stop(`Could not reach ${what} at ${url} (${e.cause?.code || e.message}).`);
|
|
32
|
+
}
|
|
33
|
+
if (res.status >= 300 && res.status < 400) throw stop(`${url} redirects to ${res.headers.get("location")}. Use the address it redirects to.`);
|
|
34
|
+
if (!res.ok) throw stop(`${what} at ${url} answered ${res.status}.`);
|
|
35
|
+
try {
|
|
36
|
+
return await res.json();
|
|
37
|
+
} catch {
|
|
38
|
+
throw stop(`${what} at ${url} did not answer with JSON.`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @param {object} c
|
|
44
|
+
* @param {string} c.url public address of your API
|
|
45
|
+
* @param {import("ethers").Signer} c.wallet connected to the payment network
|
|
46
|
+
* @param {string} [c.suretyUrl] the Surety relay you are joining
|
|
47
|
+
* @param {string} [c.amount] total bond wanted, in USDC (default: the vault minimum)
|
|
48
|
+
* @param {string} [c.vaultAddress] pin the vault instead of trusting the relay's answer
|
|
49
|
+
* @param {(m: string) => void} [c.log]
|
|
50
|
+
*/
|
|
51
|
+
async function bond(c) {
|
|
52
|
+
const log = c.log || console.log;
|
|
53
|
+
const suretyUrl = (c.suretyUrl || "https://www.surety.buzz").replace(/\/+$/, "");
|
|
54
|
+
let url = String(c.url || "").trim().replace(/\/+$/, "");
|
|
55
|
+
if (url && !/^https?:\/\//.test(url)) url = `https://${url}`;
|
|
56
|
+
if (!url) throw stop("Give the public address of your API: npm run bond -- https://your-api.example");
|
|
57
|
+
const slaUrl = `${url}/.well-known/surety.json`;
|
|
58
|
+
const me = await c.wallet.getAddress();
|
|
59
|
+
|
|
60
|
+
// 1. Your API is up and describes itself correctly.
|
|
61
|
+
const doc = await getJson(slaUrl, "your API", { redirect: "manual" });
|
|
62
|
+
if (doc.baseUrl !== url) {
|
|
63
|
+
throw stop(`Your API thinks its address is "${doc.baseUrl}", not ${url}. Set PUBLIC_URL to ${url} on your host and redeploy.`);
|
|
64
|
+
}
|
|
65
|
+
// 2. The relay can read it too. This is the same check it runs before covering a call.
|
|
66
|
+
const check = await getJson(`${suretyUrl}/bond/sla-check?url=${encodeURIComponent(slaUrl)}`, "Surety");
|
|
67
|
+
if (!check.ok) throw stop(`Surety could not accept your SLA document: ${check.error}`);
|
|
68
|
+
log(`SLA accepted: ${check.endpoints.length} endpoint(s), payments go to ${check.payTo}`);
|
|
69
|
+
|
|
70
|
+
// 3. Where the vault is, and where this wallet stands.
|
|
71
|
+
const net = await getJson(`${suretyUrl}/bond/account?address=${me}`, "Surety");
|
|
72
|
+
if (!net.ok) throw stop(`Surety could not read the vault: ${net.error}`);
|
|
73
|
+
const { chainId } = await c.wallet.provider.getNetwork();
|
|
74
|
+
if (Number(chainId) !== net.chainId) throw stop(`Your wallet is connected to chain ${chainId}, but this vault is on chain ${net.chainId}.`);
|
|
75
|
+
if (c.vaultAddress && ethers.getAddress(c.vaultAddress) !== ethers.getAddress(net.vault)) {
|
|
76
|
+
throw stop(`Surety reports vault ${net.vault}, but VAULT_ADDRESS is ${c.vaultAddress}. Stopping.`);
|
|
77
|
+
}
|
|
78
|
+
const vault = new ethers.Contract(net.vault, VAULT_ABI, c.wallet);
|
|
79
|
+
const usdc = new ethers.Contract(net.usdc, ERC20_ABI, c.wallet);
|
|
80
|
+
log(`Vault ${net.vault} on chain ${net.chainId}, wallet ${me}`);
|
|
81
|
+
|
|
82
|
+
// 4. List the API, or repoint an existing listing.
|
|
83
|
+
let p = await vault.providers(me);
|
|
84
|
+
if (!p.registered) {
|
|
85
|
+
await (await vault.register(slaUrl)).wait();
|
|
86
|
+
log("Listed your API on the vault.");
|
|
87
|
+
} else if (p.metadataURI !== slaUrl) {
|
|
88
|
+
await (await vault.setMetadata(slaUrl)).wait();
|
|
89
|
+
log("Pointed your listing at this address.");
|
|
90
|
+
} else {
|
|
91
|
+
log("Already listed at this address.");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// 5. Top the bond up to the target.
|
|
95
|
+
const minBond = await vault.minProviderBond();
|
|
96
|
+
const target = c.amount ? ethers.parseUnits(String(c.amount), 6) : minBond;
|
|
97
|
+
if (target < minBond) throw stop(`The minimum bond is ${fmt(minBond)} USDC.`);
|
|
98
|
+
p = await vault.providers(me);
|
|
99
|
+
const missing = target - p.bond;
|
|
100
|
+
if (missing > 0n) {
|
|
101
|
+
const balance = await usdc.balanceOf(me);
|
|
102
|
+
if (balance < missing) throw stop(`You need ${fmt(missing)} more USDC to bond, and this wallet holds ${fmt(balance)}.`);
|
|
103
|
+
if ((await usdc.allowance(me, net.vault)) < missing) {
|
|
104
|
+
await (await usdc.approve(net.vault, missing)).wait(); // exactly this much, nothing open-ended
|
|
105
|
+
}
|
|
106
|
+
await (await vault.depositBond(missing)).wait();
|
|
107
|
+
log(`Bonded ${fmt(missing)} USDC.`);
|
|
108
|
+
}
|
|
109
|
+
const [after, active] = await Promise.all([vault.providers(me), vault.isActive(me)]);
|
|
110
|
+
log(`Bond ${fmt(after.bond)} USDC. ${active ? "ACTIVE: your paid calls are covered." : "NOT ACTIVE: calls are not covered yet."}`);
|
|
111
|
+
|
|
112
|
+
const callUrls = check.endpoints.map((e) => `${e.method} ${suretyUrl}/call/${me}${e.path}`);
|
|
113
|
+
log(`\nAgents call you through the relay:`);
|
|
114
|
+
for (const line of callUrls) log(` ${line}`);
|
|
115
|
+
log(`Your record: ${suretyUrl}/trust/${me}`);
|
|
116
|
+
log(`Directory: ${suretyUrl}/providers/`);
|
|
117
|
+
return { provider: me, active, bond: after.bond, slaUrl, vault: net.vault, callUrls };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/// What to tell a person when bonding stops, in plain words.
|
|
121
|
+
function explain(e) {
|
|
122
|
+
return e.expected ? e.message
|
|
123
|
+
: e.code === "INSUFFICIENT_FUNDS" ? "This wallet has no MON to pay the network fee."
|
|
124
|
+
: e.shortMessage || e.message;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* bond() using the wallet key and network named in the environment (PRIVATE_KEY, SURETY_NETWORK,
|
|
129
|
+
* and optionally SURETY_URL, RPC_URL, VAULT_ADDRESS).
|
|
130
|
+
* @param {{url: string, amount?: string, env?: NodeJS.ProcessEnv, log?: (m: string) => void}} o
|
|
131
|
+
*/
|
|
132
|
+
async function bondFromEnv({ url, amount, env = process.env, log }) {
|
|
133
|
+
if (!env.PRIVATE_KEY) throw stop("Put your wallet key in .env as PRIVATE_KEY=... (copy .env.example to .env first).");
|
|
134
|
+
const key = env.PRIVATE_KEY.startsWith("0x") ? env.PRIVATE_KEY : `0x${env.PRIVATE_KEY}`;
|
|
135
|
+
const wallet = new ethers.Wallet(key, new ethers.JsonRpcProvider(require("./surety").networkFromEnv(env).rpc));
|
|
136
|
+
return bond({ url, amount, wallet, suretyUrl: env.SURETY_URL, vaultAddress: env.VAULT_ADDRESS, log });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
module.exports = { bond, bondFromEnv, explain };
|
|
140
|
+
|
|
141
|
+
if (require.main === module) {
|
|
142
|
+
require("dotenv").config();
|
|
143
|
+
bondFromEnv({ url: process.argv[2], amount: process.argv[3] }).then(
|
|
144
|
+
() => process.exit(0),
|
|
145
|
+
(e) => {
|
|
146
|
+
console.error(`STOPPED: ${explain(e)}`);
|
|
147
|
+
process.exit(1);
|
|
148
|
+
}
|
|
149
|
+
);
|
|
150
|
+
}
|
package/lib/check.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Time every endpoint against its own promise, before any money is involved.
|
|
2
|
+
//
|
|
3
|
+
// npm run check
|
|
4
|
+
//
|
|
5
|
+
// Runs each handler a few times on this computer (no payment, no network fee)
|
|
6
|
+
// and tells you whether the promise in app.js is one you can keep.
|
|
7
|
+
const Ajv = require("ajv");
|
|
8
|
+
|
|
9
|
+
const ajv = new Ajv({ allErrors: true, strict: false }); // the same settings the relay checks with
|
|
10
|
+
|
|
11
|
+
/// Fills a fake request from an example path: "/v1/shout/:word" + "/v1/shout/hello" -> params.word = "hello".
|
|
12
|
+
function fakeRequest(e) {
|
|
13
|
+
const example = e.example || (e.path.includes(":") ? null : e.path);
|
|
14
|
+
if (!example) return null;
|
|
15
|
+
const url = new URL(example, "http://check.local");
|
|
16
|
+
const want = e.path.split("/"), got = url.pathname.split("/");
|
|
17
|
+
if (want.length !== got.length) return null;
|
|
18
|
+
const params = {};
|
|
19
|
+
for (let i = 0; i < want.length; i++) {
|
|
20
|
+
if (want[i].startsWith(":")) params[want[i].slice(1)] = decodeURIComponent(got[i]);
|
|
21
|
+
else if (want[i] !== got[i]) return null;
|
|
22
|
+
}
|
|
23
|
+
return { method: e.method, path: url.pathname, url: url.pathname + url.search, params, query: Object.fromEntries(url.searchParams), headers: {}, body: e.exampleBody ?? {} };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {object} api what createBondedApi returned
|
|
28
|
+
* @param {object} [o] @param {number} [o.runs] times each handler is called (default 3)
|
|
29
|
+
* @returns {Promise<Array<{endpoint: string, ok: boolean, level: "ok"|"tight"|"fail", worstMs?: number, budgetMs?: number, note: string}>>}
|
|
30
|
+
*/
|
|
31
|
+
async function check(api, { runs = 3 } = {}) {
|
|
32
|
+
const results = [];
|
|
33
|
+
for (const e of api.endpoints) {
|
|
34
|
+
const endpoint = `${e.method} ${e.path}`;
|
|
35
|
+
const fail = (note, extra = {}) => results.push({ endpoint, ok: false, level: "fail", note, ...extra });
|
|
36
|
+
const req = fakeRequest(e);
|
|
37
|
+
if (!req) {
|
|
38
|
+
fail(`add example: "/a/real/path" to this endpoint so it can be tried`);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const problem = e.validate && e.validate(req);
|
|
42
|
+
if (problem) {
|
|
43
|
+
fail(`its own example is rejected by validate: ${problem}`);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
let validate = null;
|
|
47
|
+
if (e.responseSchema) {
|
|
48
|
+
try {
|
|
49
|
+
validate = ajv.compile(e.responseSchema);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
fail(`responseSchema is not valid JSON Schema: ${err.message}`);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// What the handler may use: the promise, less the time payment settlement takes.
|
|
56
|
+
const budgetMs = Math.max(e.maxLatencyMs - api.settleReserveMs, 0);
|
|
57
|
+
let worstMs = 0, error = null;
|
|
58
|
+
for (let i = 0; i < runs && !error; i++) {
|
|
59
|
+
const t = performance.now();
|
|
60
|
+
try {
|
|
61
|
+
const body = JSON.parse(JSON.stringify(await api.run(e, req) ?? null)); // as it would arrive over the wire
|
|
62
|
+
if (validate && !validate(body)) error = `answer does not match responseSchema: ${ajv.errorsText(validate.errors)}`;
|
|
63
|
+
} catch (err) {
|
|
64
|
+
error = err.message === "too_slow_not_charged" ? `took longer than the ${e.deadlineMs} ms it has before the kit gives up` : `handler failed: ${err.message}`;
|
|
65
|
+
}
|
|
66
|
+
worstMs = Math.max(worstMs, Math.round(performance.now() - t));
|
|
67
|
+
}
|
|
68
|
+
if (error) fail(error, { worstMs, budgetMs });
|
|
69
|
+
else if (budgetMs === 0) results.push({ endpoint, ok: true, level: "tight", worstMs, budgetMs, note: `promises ${e.maxLatencyMs} ms, less than payment settlement usually takes. Expect refunds` });
|
|
70
|
+
else if (worstMs > budgetMs * 0.6) results.push({ endpoint, ok: true, level: "tight", worstMs, budgetMs, note: `uses over 60% of its time. Raise maxLatencyMs or speed it up` });
|
|
71
|
+
else results.push({ endpoint, ok: true, level: "ok", worstMs, budgetMs, note: "comfortable" });
|
|
72
|
+
}
|
|
73
|
+
return results;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Runs check() and prints one verdict per endpoint. Returns how many did not keep their promise.
|
|
78
|
+
* @param {object} api what createBondedApi returned
|
|
79
|
+
* @param {{log?: (m: string) => void, tryCommand?: string}} [o]
|
|
80
|
+
*/
|
|
81
|
+
async function report(api, { log = console.log, tryCommand = "npm run try" } = {}) {
|
|
82
|
+
const results = await check(api);
|
|
83
|
+
const mark = { ok: "OK ", tight: "TIGHT", fail: "FAIL " };
|
|
84
|
+
for (const r of results) {
|
|
85
|
+
const time = r.worstMs === undefined ? "" : ` slowest ${r.worstMs} ms of ${r.budgetMs} ms`;
|
|
86
|
+
log(`${mark[r.level]} ${r.endpoint}${time}\n ${r.note}`);
|
|
87
|
+
}
|
|
88
|
+
const failed = results.filter((r) => !r.ok).length;
|
|
89
|
+
log(failed
|
|
90
|
+
? `\n${failed} endpoint(s) did not keep their promise. Fix them before you bond.`
|
|
91
|
+
: `\nEvery endpoint keeps its promise from this computer. Your host may be slower, so run "${tryCommand}" once it is live.`);
|
|
92
|
+
return failed;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
module.exports = { check, report, fakeRequest };
|
|
96
|
+
|
|
97
|
+
if (require.main === module) {
|
|
98
|
+
let api;
|
|
99
|
+
try {
|
|
100
|
+
api = require("./app").api;
|
|
101
|
+
} catch (e) {
|
|
102
|
+
console.error(`STOPPED: app.js could not start: ${e.message}`);
|
|
103
|
+
process.exit(1);
|
|
104
|
+
}
|
|
105
|
+
report(api).then((failed) => process.exit(failed ? 1 : 0));
|
|
106
|
+
}
|
package/lib/surety.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// Surety provider kit: turn a list of endpoints into a paid x402 API that
|
|
2
|
+
// publishes its own promise (the SLA document Surety checks every call against).
|
|
3
|
+
//
|
|
4
|
+
// You should not need to edit this file. Your endpoints live in app.js.
|
|
5
|
+
const express = require("express");
|
|
6
|
+
const { paymentMiddleware, x402ResourceServer } = require("@x402/express");
|
|
7
|
+
const { HTTPFacilitatorClient } = require("@x402/core/server");
|
|
8
|
+
const { ExactEvmScheme } = require("@x402/evm/exact/server");
|
|
9
|
+
|
|
10
|
+
const MONAD_TESTNET = {
|
|
11
|
+
network: "eip155:10143",
|
|
12
|
+
usdc: "0x534b2f3A21130d7a60830c2Df862319e593943A3",
|
|
13
|
+
rpc: "https://testnet-rpc.monad.xyz",
|
|
14
|
+
facilitatorUrl: "https://x402-facilitator.molandak.org",
|
|
15
|
+
};
|
|
16
|
+
const MONAD_MAINNET = {
|
|
17
|
+
network: "eip155:143",
|
|
18
|
+
usdc: "0x754704Bc059F8C67012fEd69BC8A327a5aafb603", // real USDC
|
|
19
|
+
rpc: "https://rpc.monad.xyz",
|
|
20
|
+
facilitatorUrl: "https://x402-facilitator.molandak.org",
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/// Testnet unless SURETY_NETWORK=mainnet. Mainnet means real money.
|
|
24
|
+
function networkFromEnv(env = process.env) {
|
|
25
|
+
const key = String(env.SURETY_NETWORK || "testnet").toLowerCase();
|
|
26
|
+
if (key !== "testnet" && key !== "mainnet") throw new Error(`SURETY_NETWORK must be "testnet" or "mainnet", not "${env.SURETY_NETWORK}".`);
|
|
27
|
+
const base = key === "mainnet" ? MONAD_MAINNET : MONAD_TESTNET;
|
|
28
|
+
return { ...base, key, rpc: env.RPC_URL || base.rpc };
|
|
29
|
+
}
|
|
30
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
31
|
+
|
|
32
|
+
/// The public https address of this server, from settings or from the host's own variables.
|
|
33
|
+
function publicUrlFromEnv(env = process.env) {
|
|
34
|
+
const host = env.VERCEL_PROJECT_PRODUCTION_URL || env.VERCEL_URL || env.RAILWAY_PUBLIC_DOMAIN;
|
|
35
|
+
return (env.PUBLIC_URL || env.RENDER_EXTERNAL_URL || (host && `https://${host}`) || "").replace(/\/+$/, "");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {object} o
|
|
40
|
+
* @param {string} o.name shown at "/"
|
|
41
|
+
* @param {string} o.payTo wallet that receives the payments
|
|
42
|
+
* @param {Array<{
|
|
43
|
+
* method?: string, path: string, description?: string, price?: string,
|
|
44
|
+
* maxLatencyMs: number, responseSchema?: object, example?: string, guard?: boolean,
|
|
45
|
+
* validate?: (req: import("express").Request) => string | null | undefined,
|
|
46
|
+
* handler: (req: import("express").Request) => any
|
|
47
|
+
* }>} o.endpoints
|
|
48
|
+
* @param {string} [o.description]
|
|
49
|
+
* @param {string} [o.price] default price per call, e.g. "$0.001"
|
|
50
|
+
* @param {string} [o.publicUrl] where the API is reachable; needed once it is hosted
|
|
51
|
+
* @param {number} [o.settleReserveMs] time kept back for payment settlement (default 2000). A handler still
|
|
52
|
+
* running when only this much of its promise is left answers 504 instead:
|
|
53
|
+
* the caller is not charged, so nothing comes out of your bond.
|
|
54
|
+
* @param {string} [o.network] @param {string} [o.usdc] @param {string} [o.facilitatorUrl]
|
|
55
|
+
*/
|
|
56
|
+
function createBondedApi(o) {
|
|
57
|
+
if (!ADDRESS.test(o.payTo || "")) throw new Error("payTo must be a wallet address (set PAY_TO_ADDRESS).");
|
|
58
|
+
if (!Array.isArray(o.endpoints) || o.endpoints.length === 0) throw new Error("Add at least one endpoint.");
|
|
59
|
+
const net = networkFromEnv();
|
|
60
|
+
const network = o.network || net.network;
|
|
61
|
+
const usdc = o.usdc || net.usdc;
|
|
62
|
+
const defaultPrice = o.price || "$0.001";
|
|
63
|
+
const settleReserveMs = o.settleReserveMs ?? 2000;
|
|
64
|
+
let baseUrl = (o.publicUrl || "").replace(/\/+$/, "");
|
|
65
|
+
|
|
66
|
+
const seen = new Set();
|
|
67
|
+
const endpoints = o.endpoints.map((e, i) => {
|
|
68
|
+
const method = String(e.method || "GET").toUpperCase();
|
|
69
|
+
const where = `Endpoint ${i + 1} (${method} ${e.path})`;
|
|
70
|
+
if (typeof e.path !== "string" || !e.path.startsWith("/")) throw new Error(`${where}: path must start with "/".`);
|
|
71
|
+
if (e.path.startsWith("/.well-known/") || e.path === "/" || e.path === "/health") throw new Error(`${where}: that path is reserved.`);
|
|
72
|
+
if (!Number.isFinite(e.maxLatencyMs) || e.maxLatencyMs <= 0) throw new Error(`${where}: maxLatencyMs must be a number of milliseconds.`);
|
|
73
|
+
if (typeof e.handler !== "function") throw new Error(`${where}: handler must be a function.`);
|
|
74
|
+
if (seen.has(`${method} ${e.path}`)) throw new Error(`${where}: listed twice.`);
|
|
75
|
+
seen.add(`${method} ${e.path}`);
|
|
76
|
+
// Promises shorter than the reserve cannot be guarded: there is no time left to give up in.
|
|
77
|
+
const deadlineMs = e.guard !== false && e.maxLatencyMs > settleReserveMs ? e.maxLatencyMs - settleReserveMs : null;
|
|
78
|
+
return { ...e, method, price: e.price || defaultPrice, deadlineMs };
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
const scheme = new ExactEvmScheme();
|
|
82
|
+
scheme.registerMoneyParser(async (amount, n) =>
|
|
83
|
+
n === network ? { amount: Math.round(amount * 1_000_000).toString(), asset: usdc, extra: { name: "USDC", version: "2" } } : null
|
|
84
|
+
);
|
|
85
|
+
const x402 = new x402ResourceServer(new HTTPFacilitatorClient({ url: o.facilitatorUrl || MONAD_TESTNET.facilitatorUrl })).register(network, scheme);
|
|
86
|
+
|
|
87
|
+
/// Runs one handler under its deadline. Used by the paid routes and by "npm run check".
|
|
88
|
+
const LATE = Symbol("late");
|
|
89
|
+
async function run(e, req) {
|
|
90
|
+
if (!e.deadlineMs) return e.handler(req);
|
|
91
|
+
let timer;
|
|
92
|
+
const late = new Promise((resolve) => { timer = setTimeout(resolve, e.deadlineMs, LATE); });
|
|
93
|
+
try {
|
|
94
|
+
const work = Promise.resolve().then(() => e.handler(req));
|
|
95
|
+
work.catch(() => {}); // a failure after the deadline has nowhere to go
|
|
96
|
+
const out = await Promise.race([work, late]);
|
|
97
|
+
if (out === LATE) throw Object.assign(new Error("too_slow_not_charged"), { status: 504 });
|
|
98
|
+
return out;
|
|
99
|
+
} finally {
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/// The promise Surety holds this API to. Served at /.well-known/surety.json.
|
|
105
|
+
const sla = () => ({
|
|
106
|
+
version: 1,
|
|
107
|
+
baseUrl,
|
|
108
|
+
payTo: o.payTo,
|
|
109
|
+
endpoints: endpoints.map((e) => ({
|
|
110
|
+
method: e.method,
|
|
111
|
+
path: e.path,
|
|
112
|
+
maxLatencyMs: e.maxLatencyMs,
|
|
113
|
+
...(e.responseSchema ? { responseSchema: e.responseSchema } : {}),
|
|
114
|
+
})),
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
const app = express();
|
|
118
|
+
app.disable("x-powered-by");
|
|
119
|
+
app.use(express.json({ limit: "100kb" }));
|
|
120
|
+
const cached = (res) => res.set("cache-control", "public, max-age=60");
|
|
121
|
+
app.get("/", (_req, res) =>
|
|
122
|
+
cached(res).json({
|
|
123
|
+
name: o.name || "Bonded x402 API",
|
|
124
|
+
...(o.description ? { description: o.description } : {}),
|
|
125
|
+
paymentNetwork: network,
|
|
126
|
+
endpoints: endpoints.map((e) => ({ method: e.method, path: e.path, price: e.price, maxLatencyMs: e.maxLatencyMs, description: e.description })),
|
|
127
|
+
sla: `${baseUrl}/.well-known/surety.json`,
|
|
128
|
+
})
|
|
129
|
+
);
|
|
130
|
+
app.get("/health", (_req, res) => res.json({ ok: true }));
|
|
131
|
+
app.get("/.well-known/surety.json", (_req, res) => cached(res).json(sla()));
|
|
132
|
+
|
|
133
|
+
// Bad input is rejected BEFORE the paywall, so nobody pays for a typo.
|
|
134
|
+
for (const e of endpoints) {
|
|
135
|
+
if (!e.validate) continue;
|
|
136
|
+
app[e.method.toLowerCase()](e.path, (req, res, next) => {
|
|
137
|
+
const problem = e.validate(req);
|
|
138
|
+
problem ? res.status(400).json({ error: problem }) : next();
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
app.use(
|
|
142
|
+
paymentMiddleware(
|
|
143
|
+
Object.fromEntries(
|
|
144
|
+
endpoints.map((e) => [
|
|
145
|
+
`${e.method} ${e.path}`,
|
|
146
|
+
{ accepts: { scheme: "exact", network, payTo: o.payTo, price: e.price }, description: e.description || e.path, mimeType: "application/json" },
|
|
147
|
+
])
|
|
148
|
+
),
|
|
149
|
+
x402
|
|
150
|
+
)
|
|
151
|
+
);
|
|
152
|
+
// A handler that throws answers with an error status. x402 only settles on success, so the caller is not charged.
|
|
153
|
+
for (const e of endpoints) {
|
|
154
|
+
app[e.method.toLowerCase()](e.path, async (req, res) => {
|
|
155
|
+
try {
|
|
156
|
+
res.json(await run(e, req));
|
|
157
|
+
} catch (err) {
|
|
158
|
+
res.status(err.status || 502).json({ error: err.status ? err.message : "upstream_error" });
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
app.use((_req, res) => res.status(404).json({ error: "not_found" }));
|
|
163
|
+
|
|
164
|
+
let httpServer;
|
|
165
|
+
const listen = (port = 0, host = "127.0.0.1") =>
|
|
166
|
+
new Promise((resolve) => {
|
|
167
|
+
httpServer = app.listen(port, host, () => {
|
|
168
|
+
if (!baseUrl) baseUrl = `http://127.0.0.1:${httpServer.address().port}`;
|
|
169
|
+
resolve(baseUrl);
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
return { app, sla, endpoints, run, settleReserveMs, listen, close: () => new Promise((r) => httpServer.close(r)), slaUrl: () => `${baseUrl}/.well-known/surety.json` };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* createBondedApi and start listening, in one call. Reads PORT, PAY_TO_ADDRESS and the
|
|
177
|
+
* public address from the environment when they are not given.
|
|
178
|
+
* @param {object} o the same options as createBondedApi
|
|
179
|
+
* @param {{port?: number, host?: string, log?: (m: string) => void}} [how]
|
|
180
|
+
* @returns {Promise<ReturnType<typeof createBondedApi> & {url: string}>}
|
|
181
|
+
*/
|
|
182
|
+
async function serve(o, how = {}) {
|
|
183
|
+
const log = how.log || console.log;
|
|
184
|
+
const api = createBondedApi({ payTo: process.env.PAY_TO_ADDRESS, publicUrl: publicUrlFromEnv(), ...o });
|
|
185
|
+
const url = await api.listen(how.port ?? Number(process.env.PORT || 4021), how.host || "0.0.0.0");
|
|
186
|
+
log(`Running at ${url}`);
|
|
187
|
+
log(`Your promise: ${url}/.well-known/surety.json`);
|
|
188
|
+
return Object.assign(api, { url });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
module.exports = { createBondedApi, serve, publicUrlFromEnv, networkFromEnv, MONAD_TESTNET, MONAD_MAINNET };
|
package/lib/try.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Make one real paid call to your API through the Surety relay and show the verdict.
|
|
2
|
+
//
|
|
3
|
+
// npm run try -- https://your-api.example/v1/block
|
|
4
|
+
//
|
|
5
|
+
// Pays from PRIVATE_KEY in .env (a fraction of a cent, no network fee).
|
|
6
|
+
const { privateKeyToAccount } = require("viem/accounts");
|
|
7
|
+
const { wrapFetchWithPayment, x402Client } = require("@x402/fetch");
|
|
8
|
+
const { ExactEvmScheme } = require("@x402/evm/exact/client");
|
|
9
|
+
const { networkFromEnv } = require("./surety");
|
|
10
|
+
|
|
11
|
+
/// Calls `path` on `provider` through the relay, paying from `privateKey`.
|
|
12
|
+
async function tryCall({ suretyUrl, provider, path, privateKey, network = networkFromEnv().network, usdc = networkFromEnv().usdc }) {
|
|
13
|
+
const account = privateKeyToAccount(privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`);
|
|
14
|
+
const client = new x402Client()
|
|
15
|
+
.register(network, new ExactEvmScheme(account))
|
|
16
|
+
.setSpendControls({ allowedAssets: [{ network, asset: usdc, maxAmountPerPayment: "100000" }] }); // never more than $0.10
|
|
17
|
+
const res = await wrapFetchWithPayment(fetch, client)(`${suretyUrl.replace(/\/+$/, "")}/call/${provider}${path}`);
|
|
18
|
+
const h = (name) => res.headers.get(`x-surety-${name}`);
|
|
19
|
+
return {
|
|
20
|
+
status: res.status, body: await res.text(),
|
|
21
|
+
verdict: h("verdict"), reason: h("reason"), latencyMs: Number(h("latency-ms")), claim: h("claim"), claimTx: h("claim-tx"),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* tryCall() for one endpoint address, paying from PRIVATE_KEY in the environment, with the result printed.
|
|
27
|
+
* @param {{target: string, env?: NodeJS.ProcessEnv, log?: (m: string) => void, usage?: string}} o
|
|
28
|
+
*/
|
|
29
|
+
async function tryFromEnv({ target, env = process.env, log = console.log, usage = "npm run try -- https://your-api.example/v1/block" }) {
|
|
30
|
+
let at;
|
|
31
|
+
try {
|
|
32
|
+
at = new URL(target);
|
|
33
|
+
} catch {
|
|
34
|
+
throw new Error(`Give the full address of one endpoint: ${usage}`);
|
|
35
|
+
}
|
|
36
|
+
if (!env.PRIVATE_KEY) throw new Error("Put your wallet key in .env as PRIVATE_KEY=...");
|
|
37
|
+
const provider = env.PROVIDER_ADDRESS || privateKeyToAccount(env.PRIVATE_KEY.startsWith("0x") ? env.PRIVATE_KEY : `0x${env.PRIVATE_KEY}`).address;
|
|
38
|
+
const net = networkFromEnv(env);
|
|
39
|
+
const r = await tryCall({ suretyUrl: env.SURETY_URL || "https://www.surety.buzz", provider, path: at.pathname + at.search, privateKey: env.PRIVATE_KEY, network: net.network, usdc: net.usdc });
|
|
40
|
+
log(`status ${r.status}`);
|
|
41
|
+
log(`verdict ${r.verdict} (${r.reason}), ${r.latencyMs} ms`);
|
|
42
|
+
log(`refund ${r.claim}${r.claimTx ? ` ${r.claimTx}` : ""}`);
|
|
43
|
+
log(`body ${r.body.slice(0, 400)}`);
|
|
44
|
+
return r;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
module.exports = { tryCall, tryFromEnv };
|
|
48
|
+
|
|
49
|
+
if (require.main === module) {
|
|
50
|
+
require("dotenv").config();
|
|
51
|
+
tryFromEnv({ target: process.argv[2] }).then(
|
|
52
|
+
() => process.exit(0),
|
|
53
|
+
(e) => {
|
|
54
|
+
console.error(`STOPPED: ${e.shortMessage || e.message}`);
|
|
55
|
+
process.exit(1);
|
|
56
|
+
}
|
|
57
|
+
);
|
|
58
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "surety-provider",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Launch a paid x402 API on Monad with a bond behind it. Failed calls are refunded to the caller on-chain.",
|
|
5
|
+
"keywords": ["x402", "monad", "ai-agents", "payments", "api", "surety", "sla", "refunds"],
|
|
6
|
+
"homepage": "https://www.surety.buzz/kit/",
|
|
7
|
+
"repository": { "type": "git", "url": "git+https://github.com/j-6-z/surety.git", "directory": "packages/provider" },
|
|
8
|
+
"bugs": { "url": "https://github.com/j-6-z/surety/issues" },
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"author": "Jay Turner",
|
|
11
|
+
"type": "commonjs",
|
|
12
|
+
"main": "index.js",
|
|
13
|
+
"types": "index.d.ts",
|
|
14
|
+
"bin": { "surety-provider": "cli.js" },
|
|
15
|
+
"files": ["index.js", "index.d.ts", "cli.js", "lib", "template", "README.md", "LICENSE"],
|
|
16
|
+
"engines": { "node": ">=18" },
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@x402/core": "^2.32.0",
|
|
19
|
+
"@x402/evm": "^2.32.0",
|
|
20
|
+
"@x402/express": "^2.32.0",
|
|
21
|
+
"@x402/fetch": "^2.32.0",
|
|
22
|
+
"ajv": "^8.20.0",
|
|
23
|
+
"dotenv": "^18.0.10",
|
|
24
|
+
"ethers": "^6.17.0",
|
|
25
|
+
"express": "^5.3.0",
|
|
26
|
+
"viem": "^2.58.4"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/template/app.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// YOUR API. Edit the endpoints below, then:
|
|
2
|
+
// npm start run it on this computer
|
|
3
|
+
// npm run check time every endpoint against its own promise
|
|
4
|
+
// npm run bond -- https://your-address post a bond so its calls are covered
|
|
5
|
+
require("dotenv").config({ quiet: true });
|
|
6
|
+
const { createBondedApi, publicUrlFromEnv } = require("surety-provider");
|
|
7
|
+
|
|
8
|
+
const api = createBondedApi({
|
|
9
|
+
name: "My bonded API",
|
|
10
|
+
description: "Replace this with one line about what your API sells.",
|
|
11
|
+
payTo: process.env.PAY_TO_ADDRESS, // the wallet your payments land in
|
|
12
|
+
publicUrl: publicUrlFromEnv(),
|
|
13
|
+
price: process.env.API_PRICE || "$0.001", // per call, unless an endpoint sets its own
|
|
14
|
+
|
|
15
|
+
endpoints: [
|
|
16
|
+
{
|
|
17
|
+
method: "GET",
|
|
18
|
+
path: "/v1/shout/:word",
|
|
19
|
+
description: "Returns the word in capitals",
|
|
20
|
+
// THE PROMISE. Answer slower than this, or in a different shape, and the caller is refunded
|
|
21
|
+
// from your bond. The clock includes payment settlement, so leave room.
|
|
22
|
+
maxLatencyMs: 4000,
|
|
23
|
+
responseSchema: { type: "object", required: ["shout"], properties: { shout: { type: "string" } } },
|
|
24
|
+
example: "/v1/shout/hello", // a real call "npm run check" can try
|
|
25
|
+
// Runs before payment. Return a message to reject the call for free.
|
|
26
|
+
validate: (req) => (/^[a-z]{1,32}$/i.test(req.params.word) ? null : "word must be 1 to 32 letters"),
|
|
27
|
+
// THE WORK. Return the answer. Throw to answer with an error (the caller is not charged).
|
|
28
|
+
handler: (req) => ({ shout: req.params.word.toUpperCase() }),
|
|
29
|
+
},
|
|
30
|
+
],
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
module.exports = api.app; // hosts like Vercel pick this up
|
|
34
|
+
module.exports.api = api; // "surety-provider check" reads this
|
|
35
|
+
|
|
36
|
+
if (require.main === module) {
|
|
37
|
+
api.listen(Number(process.env.PORT || 4021), "0.0.0.0").then((url) => {
|
|
38
|
+
console.log(`Running at ${url}`);
|
|
39
|
+
console.log(`Your promise: ${url}/.well-known/surety.json`);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Copy this file to .env and fill it in. Never commit .env.
|
|
2
|
+
|
|
3
|
+
# The wallet your API payments land in. Set this on your host too.
|
|
4
|
+
PAY_TO_ADDRESS=
|
|
5
|
+
|
|
6
|
+
# The public https address of your API, once it is hosted. Set this on your host too.
|
|
7
|
+
# (Vercel, Render and Railway are detected on their own if you leave it empty.)
|
|
8
|
+
PUBLIC_URL=
|
|
9
|
+
|
|
10
|
+
# ONLY on your own computer, for "npm run bond" and "npm run try". Never put this on your host.
|
|
11
|
+
# Use a testnet-only wallet with a little MON and some test USDC.
|
|
12
|
+
PRIVATE_KEY=
|
|
13
|
+
|
|
14
|
+
# Leave this out to use Monad testnet (test funds). Set it to mainnet for real USDC:
|
|
15
|
+
# set it here AND on your host. The vault contract is not audited.
|
|
16
|
+
# SURETY_NETWORK=mainnet
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "my-bonded-api",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "A paid x402 API on Monad, bonded on Surety",
|
|
6
|
+
"type": "commonjs",
|
|
7
|
+
"main": "app.js",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"start": "node app.js",
|
|
10
|
+
"check": "surety-provider check app.js",
|
|
11
|
+
"bond": "surety-provider bond",
|
|
12
|
+
"try": "surety-provider try"
|
|
13
|
+
},
|
|
14
|
+
"engines": { "node": ">=18" },
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"dotenv": "^18.0.10",
|
|
17
|
+
"surety-provider": "^0.1.0"
|
|
18
|
+
}
|
|
19
|
+
}
|