@redditech/provider-kit 0.0.0-stage → 0.2.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.
@@ -0,0 +1,38 @@
1
+ import type { ProviderChain } from "./chain.js";
2
+ import type { ProviderConfig } from "./config.js";
3
+ import type { ProviderKeyResult } from "./keys.js";
4
+ export type CheckStatus = "pass" | "warn" | "fail";
5
+ export interface DoctorCheck {
6
+ name: string;
7
+ status: CheckStatus;
8
+ detail: string;
9
+ /** What to do about a warning or failure. */
10
+ fix?: string;
11
+ }
12
+ /** Enough for transaction fees, with room for the rent of a token account. */
13
+ export declare const WALLET_MIN_LAMPORTS = 10000000n;
14
+ type FetchLike = (url: string, init?: {
15
+ method?: string;
16
+ headers?: Record<string, string>;
17
+ signal?: AbortSignal;
18
+ }) => Promise<{
19
+ ok: boolean;
20
+ status: number;
21
+ }>;
22
+ export interface DoctorInput {
23
+ config: ProviderConfig;
24
+ chain: ProviderChain;
25
+ key: ProviderKeyResult;
26
+ fetchImpl?: FetchLike;
27
+ /** True when the directory can be written. Defaults to a real check. */
28
+ canWrite?: (directory: string) => boolean;
29
+ }
30
+ export declare function runDoctor(input: DoctorInput): Promise<{
31
+ ok: boolean;
32
+ checks: DoctorCheck[];
33
+ }>;
34
+ export declare function formatDoctor(result: {
35
+ ok: boolean;
36
+ checks: DoctorCheck[];
37
+ }): string;
38
+ export {};
@@ -0,0 +1,163 @@
1
+ /**
2
+ * `rap-provider doctor`: a read-only preflight. It sends nothing and spends
3
+ * nothing. Each line says what was checked and, when it failed, what to do.
4
+ */
5
+ import { accessSync, constants, existsSync } from "node:fs";
6
+ import { dirname, resolve } from "node:path";
7
+ import { PublicKey } from "@solana/web3.js";
8
+ import { checkProviderCluster, checkTokenAccount, checkTreasuryReadiness, ESCROW_PROTOCOL_TREASURY, token2022MintPosture, treasuryTokenAccount } from "@redditech/x402-solana";
9
+ import { ADL_PATH, maxPerCall, providerAdlText } from "./adl.js";
10
+ /** Enough for transaction fees, with room for the rent of a token account. */
11
+ export const WALLET_MIN_LAMPORTS = 10000000n;
12
+ const TOKEN_2022_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
13
+ const sol = (lamports) => `${(Number(lamports) / 1e9).toFixed(4)} SOL`;
14
+ function defaultCanWrite(directory) {
15
+ let current = resolve(directory);
16
+ // The directory may not exist yet: the nearest existing parent must be writable.
17
+ while (!existsSync(current) && dirname(current) !== current)
18
+ current = dirname(current);
19
+ try {
20
+ accessSync(current, constants.W_OK);
21
+ return true;
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ export async function runDoctor(input) {
28
+ const { config, chain } = input;
29
+ const { terms } = config;
30
+ const fetchImpl = input.fetchImpl ?? fetch;
31
+ const checks = [];
32
+ const add = (check) => checks.push(check);
33
+ const done = () => ({ ok: checks.every((c) => c.status !== "fail"), checks });
34
+ add({ name: "Configuration", status: "pass", detail: `${config.name}: ${config.model}, ${terms.price.inputPerMillion} in / ${terms.price.outputPerMillion} out ${terms.price.currency} per million tokens, at most ${terms.maxOutputTokens} output tokens a call` });
35
+ const adl = providerAdlText(config).report;
36
+ add(adl.status === "pass"
37
+ ? { name: "ADL", status: "pass", detail: `ADL v0.3 Level 3, served at ${ADL_PATH}; at most ${maxPerCall(config)} ${terms.price.currency} a call` }
38
+ : { name: "ADL", status: "fail", detail: `the ADL document does not pass Level 3 (${adl.schemaDiagnostics.length} schema problems)`, fix: "Run rap-provider adl --json to see each problem." });
39
+ if (config.paused) {
40
+ add({ name: "Payments", status: "warn", detail: `paused for ${terms.price.currency}: no new locks are taken`, fix: `Remove ${terms.price.currency} from pausedCurrencies (and RAP_PROVIDER_PAUSED_CURRENCIES) and restart to take payments again.` });
41
+ }
42
+ // Nothing else read from this endpoint means anything until it is the right cluster.
43
+ const cluster = await checkProviderCluster(() => chain.readGenesisHash(), config.network, config.genesisHash);
44
+ if (!cluster.ok) {
45
+ add({
46
+ name: "RPC endpoint",
47
+ status: "fail",
48
+ detail: cluster.reason === "wrong_cluster" ? `the endpoint is not ${config.network}` : "the endpoint could not be read",
49
+ fix: cluster.reason === "wrong_cluster" ? `Point SOLANA_RPC_URL (or rpcUrl) at a ${config.network} endpoint.` : "Check SOLANA_RPC_URL (or rpcUrl) and your network connection.",
50
+ });
51
+ return done();
52
+ }
53
+ add({ name: "RPC endpoint", status: "pass", detail: `serves ${config.network}` });
54
+ try {
55
+ const program = await chain.readAccount(terms.programId);
56
+ add(program?.executable
57
+ ? { name: "Escrow program", status: "pass", detail: `deployed at ${terms.programId.toBase58()}` }
58
+ : { name: "Escrow program", status: "fail", detail: `no program at ${terms.programId.toBase58()} on ${config.network}`, fix: "The V1 program may not be deployed on this network yet. Use solana-devnet until the mainnet release." });
59
+ const wallet = await chain.readAccount(new PublicKey(config.wallet));
60
+ const lamports = wallet?.lamports ?? 0n;
61
+ add(lamports >= WALLET_MIN_LAMPORTS
62
+ ? { name: "Wallet balance", status: "pass", detail: `${sol(lamports)} for fees` }
63
+ : { name: "Wallet balance", status: "fail", detail: `${sol(lamports)} held, at least ${sol(WALLET_MIN_LAMPORTS)} needed for fees and account rent`, fix: config.network === "solana-devnet" ? `Fund ${config.wallet} at https://faucet.solana.com (devnet).` : `Send SOL to ${config.wallet}.` });
64
+ const tokenAccount = treasuryTokenAccount({ mint: terms.mint, tokenProgram: terms.tokenProgram }, terms.payee);
65
+ const held = await chain.readAccount(tokenAccount);
66
+ const createCommand = `spl-token create-account ${terms.mint.toBase58()} --owner ${config.wallet}${terms.tokenProgram.toBase58() === TOKEN_2022_PROGRAM ? ` --program-id ${TOKEN_2022_PROGRAM}` : ""} --url ${config.network === "solana-devnet" ? "devnet" : "mainnet-beta"}`;
67
+ const heldCheck = checkTokenAccount(tokenAccount, held, { mint: terms.mint, tokenProgram: terms.tokenProgram, owner: terms.payee });
68
+ let recoveryReady = false;
69
+ if (terms.payoutAccount) {
70
+ const recovery = checkTokenAccount(terms.payoutAccount, await chain.readAccount(terms.payoutAccount), { mint: terms.mint, tokenProgram: terms.tokenProgram, owner: terms.payee });
71
+ recoveryReady = recovery.ok;
72
+ add(recovery.ok
73
+ ? { name: "Recovery payout account", status: "pass", detail: `${terms.payoutAccount.toBase58()} can receive payouts if the usual account cannot` }
74
+ : { name: "Recovery payout account", status: "fail", detail: `${terms.payoutAccount.toBase58()}: ${recovery.detail}`, fix: `Set payoutAccount to a ${terms.price.currency} token account this wallet owns, or remove the setting.` });
75
+ }
76
+ if (heldCheck.ok) {
77
+ add({ name: `${terms.price.currency} token account`, status: "pass", detail: `${tokenAccount.toBase58()} receives payouts` });
78
+ }
79
+ else if (heldCheck.problem === "missing") {
80
+ add({ name: `${terms.price.currency} token account`, status: "fail", detail: `${tokenAccount.toBase58()} does not exist, so no payout can land`, fix: `Create it: ${createCommand}` });
81
+ }
82
+ else if (heldCheck.problem === "frozen" || heldCheck.problem === "memo_required") {
83
+ add({
84
+ name: `${terms.price.currency} token account`,
85
+ status: recoveryReady ? "warn" : "fail",
86
+ detail: `${tokenAccount.toBase58()} is ${heldCheck.detail}, so payouts to it fail`,
87
+ fix: recoveryReady ? "Payouts go to your recovery payout account until this is resolved." : heldCheck.problem === "frozen" ? `Ask the issuer to unfreeze it, or set payoutAccount to another ${terms.price.currency} token account this wallet owns.` : "Turn off required memos on it (spl-token disable-required-transfer-memos).",
88
+ });
89
+ }
90
+ else {
91
+ add({ name: `${terms.price.currency} token account`, status: "fail", detail: `${tokenAccount.toBase58()} is not this wallet's token account for the mint (${heldCheck.detail})`, fix: `Create it: ${createCommand}` });
92
+ }
93
+ const treasury = await checkTreasuryReadiness((address) => chain.readAccount(address), [{ symbol: terms.price.currency, mint: terms.mint, tokenProgram: terms.tokenProgram }], ESCROW_PROTOCOL_TREASURY);
94
+ const notReady = treasury.items.find((item) => !item.ok);
95
+ add(notReady
96
+ ? { name: "Protocol treasury", status: "fail", detail: `${notReady.name}: ${notReady.detail}`, fix: `The protocol treasury cannot receive ${terms.price.currency} fees on this network yet, and a settle does not create its account. This provider refuses calls in ${terms.price.currency} until it is ready. ${config.network === "solana-devnet" && notReady.detail.startsWith("missing") ? `On devnet anyone can create it once: spl-token create-account ${terms.mint.toBase58()} --owner ${ESCROW_PROTOCOL_TREASURY.toBase58()} --fee-payer <your keypair> --url devnet` : "Report it to the Reddi Agent Protocol team."}` }
97
+ : { name: "Protocol treasury", status: "pass", detail: `ready to receive the protocol fee in ${terms.price.currency}` });
98
+ if (terms.tokenProgram.toBase58() === TOKEN_2022_PROGRAM) {
99
+ const mint = await chain.readAccount(terms.mint);
100
+ if (!mint) {
101
+ add({ name: `${terms.price.currency} mint`, status: "fail", detail: "the mint account does not exist", fix: "Check the mint address in the config." });
102
+ }
103
+ else {
104
+ const posture = token2022MintPosture(mint.data, terms.mint);
105
+ add(posture.pausable?.paused
106
+ ? { name: `${terms.price.currency} mint`, status: "fail", detail: "the issuer has paused transfers", fix: "Wait until transfers resume, or price in another currency." }
107
+ : posture.transferHookProgram
108
+ ? { name: `${terms.price.currency} mint`, status: "warn", detail: `transfers run the issuer's hook program ${posture.transferHookProgram}`, fix: "Read docs/ESCROW-PAYOUT-SAFETY.md before taking payment in this currency." }
109
+ : { name: `${terms.price.currency} mint`, status: "pass", detail: "transfers are not paused and no transfer hook is set" });
110
+ }
111
+ }
112
+ }
113
+ catch {
114
+ add({ name: "Chain accounts", status: "fail", detail: "an account could not be read", fix: "Check the RPC endpoint and try again." });
115
+ return done();
116
+ }
117
+ add(input.key.ok
118
+ ? { name: "Signing key", status: "pass", detail: "the key file belongs to the configured wallet" }
119
+ : { name: "Signing key", status: "fail", detail: input.key.message, fix: "Point keypairPath (or RAP_PROVIDER_KEYPAIR_PATH) at the wallet's keypair file." });
120
+ if (config.upstream.mock) {
121
+ add({ name: "Model", status: config.network === "solana-mainnet-beta" ? "fail" : "warn", detail: "mock answers are on, so buyers would pay for canned text", fix: "Set upstream.mock to false and upstream.baseUrl to your model before you list." });
122
+ }
123
+ else {
124
+ try {
125
+ const response = await fetchImpl(`${config.upstream.baseUrl}/models`, { method: "GET", headers: config.upstream.apiKey ? { authorization: `Bearer ${config.upstream.apiKey}` } : {}, signal: AbortSignal.timeout(10_000) });
126
+ add(response.ok
127
+ ? { name: "Model", status: "pass", detail: `${config.upstream.baseUrl} answers` }
128
+ : { name: "Model", status: "fail", detail: `${config.upstream.baseUrl}/models answered with status ${response.status}`, fix: response.status === 401 || response.status === 403 ? `Set ${config.upstream.apiKeyEnv} to a valid API key.` : "Check upstream.baseUrl." });
129
+ }
130
+ catch {
131
+ add({ name: "Model", status: "fail", detail: `${config.upstream.baseUrl} could not be reached`, fix: "Check upstream.baseUrl and that the model server is running." });
132
+ }
133
+ }
134
+ const host = new URL(config.publicUrl).hostname;
135
+ const local = host === "localhost" || host === "127.0.0.1" || host === "[::1]";
136
+ if (local) {
137
+ add({ name: "Public address", status: config.network === "solana-mainnet-beta" ? "fail" : "warn", detail: `${config.publicUrl} is only reachable from this machine`, fix: "Set publicUrl to the https address buyers will use before you list." });
138
+ }
139
+ else {
140
+ try {
141
+ const response = await fetchImpl(`${config.publicUrl}/healthz`, { method: "GET", signal: AbortSignal.timeout(10_000) });
142
+ add(response.ok
143
+ ? { name: "Public address", status: "pass", detail: `${config.publicUrl} answers` }
144
+ : { name: "Public address", status: "warn", detail: `${config.publicUrl}/healthz answered with status ${response.status}`, fix: "Start the provider (rap-provider start) and check the address routes to it." });
145
+ }
146
+ catch {
147
+ add({ name: "Public address", status: "warn", detail: `${config.publicUrl} did not answer`, fix: "Start the provider (rap-provider start) and check the address routes to it." });
148
+ }
149
+ }
150
+ const replayDirectory = dirname(resolve(config.replayFile));
151
+ add((input.canWrite ?? defaultCanWrite)(replayDirectory)
152
+ ? { name: "Payment memory", status: "pass", detail: `accepted escrows are remembered in ${config.replayFile}` }
153
+ : { name: "Payment memory", status: "fail", detail: `${replayDirectory} cannot be written`, fix: "Set replayFile to a path this process can write, on a disk that survives restarts." });
154
+ return done();
155
+ }
156
+ const MARK = { pass: "ok ", warn: "warn", fail: "FAIL" };
157
+ export function formatDoctor(result) {
158
+ const lines = result.checks.flatMap((c) => [`${MARK[c.status]} ${c.name}: ${c.detail}`, ...(c.fix && c.status !== "pass" ? [` ${c.fix}`] : [])]);
159
+ const failed = result.checks.filter((c) => c.status === "fail").length;
160
+ const warned = result.checks.filter((c) => c.status === "warn").length;
161
+ lines.push("", failed > 0 ? `${failed} to fix before taking payments.` : warned > 0 ? `Ready, with ${warned} to look at.` : "Ready.");
162
+ return lines.join("\n");
163
+ }
@@ -0,0 +1,32 @@
1
+ import { type MeteredSessionLedger, type NonceReplayStore } from "@redditech/x402-solana";
2
+ import type { ProviderChain } from "./chain.js";
3
+ import { type PendingSettleStore } from "./pending.js";
4
+ import { type ProviderConfig } from "./config.js";
5
+ import type { Upstream } from "./upstream.js";
6
+ export declare const PROVIDER_RECEIPT_HEADER = "x-reddi-provider-receipt";
7
+ /** The closing receipt of a session, on the answer that settled it. */
8
+ export declare const SESSION_RECEIPT_HEADER = "x-reddi-session-receipt";
9
+ /** On an answer that asked to close the session: settled, declined, or pending (tried again shortly). */
10
+ export declare const SESSION_STATE_HEADER = "x-reddi-session-state";
11
+ export interface ProviderDeps {
12
+ chain: ProviderChain;
13
+ upstream: Upstream;
14
+ replayStore: NonceReplayStore;
15
+ /** The session ledger. Without it, session calls are refused. */
16
+ sessions?: MeteredSessionLedger;
17
+ /** Where single-call settles are recorded before they are sent. In memory when not given. */
18
+ pendingSettles?: PendingSettleStore;
19
+ /** Ed25519 signature by the provider wallet, for receipts. */
20
+ signMessage: (message: Uint8Array) => Uint8Array | Promise<Uint8Array>;
21
+ now?: () => Date;
22
+ log?: (event: Record<string, unknown>) => void;
23
+ }
24
+ /** What the listing and buyers read about this provider. No secrets. */
25
+ export declare function providerMetadata(config: ProviderConfig): Record<string, unknown>;
26
+ export type ProviderHandler = ((request: Request) => Promise<Response>) & {
27
+ /** Settles sessions that are closing, idle, or near their refund window. */
28
+ settleDueSessions(): Promise<{
29
+ status: string;
30
+ }[]>;
31
+ };
32
+ export declare function createProviderHandler(config: ProviderConfig, deps: ProviderDeps): ProviderHandler;