@absol-labs/agent 0.11.0 → 0.12.0-rc.1
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/README.md +42 -50
- package/dist/capability/invocation-capability.d.ts +2 -2
- package/dist/capability/probe-capability.d.ts +225 -0
- package/dist/capability/probe-capability.d.ts.map +1 -0
- package/dist/capability/probe-capability.js +248 -0
- package/dist/capability/probe-capability.js.map +1 -0
- package/dist/cli/args.d.ts +11 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +23 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/commands/claim.js +1 -1
- package/dist/cli/commands/claim.js.map +1 -1
- package/dist/cli/commands/close.d.ts.map +1 -1
- package/dist/cli/commands/close.js +35 -3
- package/dist/cli/commands/close.js.map +1 -1
- package/dist/cli/commands/invoke.d.ts +2 -0
- package/dist/cli/commands/invoke.d.ts.map +1 -1
- package/dist/cli/commands/invoke.js +2 -2
- package/dist/cli/commands/invoke.js.map +1 -1
- package/dist/cli/commands/mcp.d.ts.map +1 -1
- package/dist/cli/commands/mcp.js +15 -2
- package/dist/cli/commands/mcp.js.map +1 -1
- package/dist/cli/commands/open.d.ts.map +1 -1
- package/dist/cli/commands/open.js +58 -4
- package/dist/cli/commands/open.js.map +1 -1
- package/dist/cli/commands/pay.d.ts +19 -0
- package/dist/cli/commands/pay.d.ts.map +1 -0
- package/dist/cli/commands/pay.js +355 -0
- package/dist/cli/commands/pay.js.map +1 -0
- package/dist/cli/commands/reclaim-unverified.d.ts.map +1 -1
- package/dist/cli/commands/reclaim-unverified.js +3 -2
- package/dist/cli/commands/reclaim-unverified.js.map +1 -1
- package/dist/cli/commands/reclaim.d.ts +23 -2
- package/dist/cli/commands/reclaim.d.ts.map +1 -1
- package/dist/cli/commands/reclaim.js +184 -16
- package/dist/cli/commands/reclaim.js.map +1 -1
- package/dist/cli/commands/refund.d.ts +13 -0
- package/dist/cli/commands/refund.d.ts.map +1 -0
- package/dist/cli/commands/refund.js +224 -0
- package/dist/cli/commands/refund.js.map +1 -0
- package/dist/cli/commands/status.d.ts.map +1 -1
- package/dist/cli/commands/status.js +10 -1
- package/dist/cli/commands/status.js.map +1 -1
- package/dist/cli/commands/streams.js +8 -12
- package/dist/cli/commands/streams.js.map +1 -1
- package/dist/cli/commands/watch.d.ts.map +1 -1
- package/dist/cli/commands/watch.js +2 -1
- package/dist/cli/commands/watch.js.map +1 -1
- package/dist/cli/config.d.ts +44 -26
- package/dist/cli/config.d.ts.map +1 -1
- package/dist/cli/config.js +88 -38
- package/dist/cli/config.js.map +1 -1
- package/dist/cli/deps.d.ts +33 -0
- package/dist/cli/deps.d.ts.map +1 -1
- package/dist/cli/deps.js +37 -1
- package/dist/cli/deps.js.map +1 -1
- package/dist/cli/errors.d.ts.map +1 -1
- package/dist/cli/errors.js +21 -1
- package/dist/cli/errors.js.map +1 -1
- package/dist/cli/escape-hatch.d.ts +6 -4
- package/dist/cli/escape-hatch.d.ts.map +1 -1
- package/dist/cli/escape-hatch.js +6 -2
- package/dist/cli/escape-hatch.js.map +1 -1
- package/dist/cli/listings.d.ts +18 -0
- package/dist/cli/listings.d.ts.map +1 -1
- package/dist/cli/listings.js +22 -12
- package/dist/cli/listings.js.map +1 -1
- package/dist/cli/preflight.d.ts +20 -14
- package/dist/cli/preflight.d.ts.map +1 -1
- package/dist/cli/preflight.js +34 -20
- package/dist/cli/preflight.js.map +1 -1
- package/dist/cli/privy.d.ts.map +1 -1
- package/dist/cli/privy.js +4 -2
- package/dist/cli/privy.js.map +1 -1
- package/dist/cli/reclaimability.d.ts +82 -0
- package/dist/cli/reclaimability.d.ts.map +1 -0
- package/dist/cli/reclaimability.js +80 -0
- package/dist/cli/reclaimability.js.map +1 -0
- package/dist/cli/run.d.ts +2 -1
- package/dist/cli/run.d.ts.map +1 -1
- package/dist/cli/run.js +40 -11
- package/dist/cli/run.js.map +1 -1
- package/dist/cli/scan-range.d.ts +2 -2
- package/dist/cli/scan-range.js +2 -2
- package/dist/cli/status.d.ts +3 -1
- package/dist/cli/status.d.ts.map +1 -1
- package/dist/cli/status.js +15 -3
- package/dist/cli/status.js.map +1 -1
- package/dist/cli/wallet.d.ts +1 -1
- package/dist/cli/wallet.js +2 -2
- package/dist/cli/wallet.js.map +1 -1
- package/dist/discovery/rate-band.d.ts +74 -0
- package/dist/discovery/rate-band.d.ts.map +1 -0
- package/dist/discovery/rate-band.js +114 -0
- package/dist/discovery/rate-band.js.map +1 -0
- package/dist/escrow-generation.d.ts +81 -0
- package/dist/escrow-generation.d.ts.map +1 -0
- package/dist/escrow-generation.js +76 -0
- package/dist/escrow-generation.js.map +1 -0
- package/dist/frameworks/agentkit.d.ts +8 -4
- package/dist/frameworks/agentkit.d.ts.map +1 -1
- package/dist/frameworks/agentkit.js +27 -10
- package/dist/frameworks/agentkit.js.map +1 -1
- package/dist/frameworks/eliza.d.ts +3 -3
- package/dist/frameworks/eliza.d.ts.map +1 -1
- package/dist/frameworks/eliza.js +15 -6
- package/dist/frameworks/eliza.js.map +1 -1
- package/dist/frameworks/langchain.d.ts.map +1 -1
- package/dist/frameworks/langchain.js +8 -0
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/gateway/caller-auth-gateway.d.ts +83 -31
- package/dist/gateway/caller-auth-gateway.d.ts.map +1 -1
- package/dist/gateway/caller-auth-gateway.js +180 -27
- package/dist/gateway/caller-auth-gateway.js.map +1 -1
- package/dist/gateway/http-server.d.ts +111 -44
- package/dist/gateway/http-server.d.ts.map +1 -1
- package/dist/gateway/http-server.js +439 -155
- package/dist/gateway/http-server.js.map +1 -1
- package/dist/gateway/probe-auth.d.ts +112 -0
- package/dist/gateway/probe-auth.d.ts.map +1 -0
- package/dist/gateway/probe-auth.js +127 -0
- package/dist/gateway/probe-auth.js.map +1 -0
- package/dist/gateway/signed-rate-bounds.d.ts +51 -0
- package/dist/gateway/signed-rate-bounds.d.ts.map +1 -0
- package/dist/gateway/signed-rate-bounds.js +94 -0
- package/dist/gateway/signed-rate-bounds.js.map +1 -0
- package/dist/gateway/x402-opener-mode.d.ts +215 -0
- package/dist/gateway/x402-opener-mode.d.ts.map +1 -0
- package/dist/gateway/x402-opener-mode.js +639 -0
- package/dist/gateway/x402-opener-mode.js.map +1 -0
- package/dist/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -5
- package/dist/index.js.map +1 -1
- package/dist/mcp/server.d.ts +52 -1
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +228 -37
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/x402-tools.d.ts +104 -0
- package/dist/mcp/x402-tools.d.ts.map +1 -0
- package/dist/mcp/x402-tools.js +434 -0
- package/dist/mcp/x402-tools.js.map +1 -0
- package/dist/network.d.ts +119 -0
- package/dist/network.d.ts.map +1 -0
- package/dist/network.js +199 -0
- package/dist/network.js.map +1 -0
- package/dist/sdk/invoke.d.ts +4 -0
- package/dist/sdk/invoke.d.ts.map +1 -1
- package/dist/sdk/invoke.js +2 -5
- package/dist/sdk/invoke.js.map +1 -1
- package/dist/wallet/autonomous-wallet-broker.d.ts +3 -0
- package/dist/wallet/autonomous-wallet-broker.d.ts.map +1 -1
- package/dist/wallet/autonomous-wallet-broker.js +27 -23
- package/dist/wallet/autonomous-wallet-broker.js.map +1 -1
- package/dist/wallet/autonomous-wallet-protocol.d.ts +8 -2
- package/dist/wallet/autonomous-wallet-protocol.d.ts.map +1 -1
- package/dist/wallet/autonomous-wallet-protocol.js +9 -2
- package/dist/wallet/autonomous-wallet-protocol.js.map +1 -1
- package/dist/wallet/autonomous-wallet.d.ts.map +1 -1
- package/dist/wallet/autonomous-wallet.js +3 -2
- package/dist/wallet/autonomous-wallet.js.map +1 -1
- package/dist/wallet/broker-escrows.d.ts +222 -0
- package/dist/wallet/broker-escrows.d.ts.map +1 -0
- package/dist/wallet/broker-escrows.js +36 -0
- package/dist/wallet/broker-escrows.js.map +1 -0
- package/dist/wallet/lifecycle.d.ts +21 -5
- package/dist/wallet/lifecycle.d.ts.map +1 -1
- package/dist/wallet/lifecycle.js +32 -12
- package/dist/wallet/lifecycle.js.map +1 -1
- package/dist/wallet/privy-broker-server.d.ts.map +1 -1
- package/dist/wallet/privy-broker-server.js +31 -26
- package/dist/wallet/privy-broker-server.js.map +1 -1
- package/dist/wallet/privy-session-broker.d.ts +14 -5
- package/dist/wallet/privy-session-broker.d.ts.map +1 -1
- package/dist/wallet/privy-session-broker.js +29 -17
- package/dist/wallet/privy-session-broker.js.map +1 -1
- package/dist/wallet/privy-session-provider.d.ts +3 -1
- package/dist/wallet/privy-session-provider.d.ts.map +1 -1
- package/dist/wallet/privy-session-provider.js +5 -3
- package/dist/wallet/privy-session-provider.js.map +1 -1
- package/dist/wallet/provider.d.ts.map +1 -1
- package/dist/wallet/provider.js +15 -8
- package/dist/wallet/provider.js.map +1 -1
- package/dist/x402/facilitator.d.ts +3 -30
- package/dist/x402/facilitator.d.ts.map +1 -1
- package/dist/x402/facilitator.js +0 -27
- package/dist/x402/facilitator.js.map +1 -1
- package/dist/x402-buyer/guarded-fetch.d.ts +51 -0
- package/dist/x402-buyer/guarded-fetch.d.ts.map +1 -0
- package/dist/x402-buyer/guarded-fetch.js +147 -0
- package/dist/x402-buyer/guarded-fetch.js.map +1 -0
- package/dist/x402-buyer/index.d.ts +10 -0
- package/dist/x402-buyer/index.d.ts.map +1 -0
- package/dist/x402-buyer/index.js +10 -0
- package/dist/x402-buyer/index.js.map +1 -0
- package/dist/x402-buyer/pay.d.ts +135 -0
- package/dist/x402-buyer/pay.d.ts.map +1 -0
- package/dist/x402-buyer/pay.js +336 -0
- package/dist/x402-buyer/pay.js.map +1 -0
- package/dist/x402-opener/abi.d.ts +684 -0
- package/dist/x402-opener/abi.d.ts.map +1 -0
- package/dist/x402-opener/abi.js +880 -0
- package/dist/x402-opener/abi.js.map +1 -0
- package/dist/x402-opener/facilitator-entry.d.ts +3 -0
- package/dist/x402-opener/facilitator-entry.d.ts.map +1 -0
- package/dist/x402-opener/facilitator-entry.js +37 -0
- package/dist/x402-opener/facilitator-entry.js.map +1 -0
- package/dist/x402-opener/facilitator-server.d.ts +180 -0
- package/dist/x402-opener/facilitator-server.d.ts.map +1 -0
- package/dist/x402-opener/facilitator-server.js +696 -0
- package/dist/x402-opener/facilitator-server.js.map +1 -0
- package/dist/x402-opener/index.d.ts +14 -0
- package/dist/x402-opener/index.d.ts.map +1 -0
- package/dist/x402-opener/index.js +14 -0
- package/dist/x402-opener/index.js.map +1 -0
- package/dist/x402-opener/listing-resolver.d.ts +55 -0
- package/dist/x402-opener/listing-resolver.d.ts.map +1 -0
- package/dist/x402-opener/listing-resolver.js +125 -0
- package/dist/x402-opener/listing-resolver.js.map +1 -0
- package/dist/x402-opener/refund-relay.d.ts +240 -0
- package/dist/x402-opener/refund-relay.d.ts.map +1 -0
- package/dist/x402-opener/refund-relay.js +1240 -0
- package/dist/x402-opener/refund-relay.js.map +1 -0
- package/dist/x402-opener/relayer-queue.d.ts +14 -0
- package/dist/x402-opener/relayer-queue.d.ts.map +1 -0
- package/dist/x402-opener/relayer-queue.js +18 -0
- package/dist/x402-opener/relayer-queue.js.map +1 -0
- package/dist/x402-opener/scheme.d.ts +217 -0
- package/dist/x402-opener/scheme.d.ts.map +1 -0
- package/dist/x402-opener/scheme.js +749 -0
- package/dist/x402-opener/scheme.js.map +1 -0
- package/dist/x402-opener/terms.d.ts +105 -0
- package/dist/x402-opener/terms.d.ts.map +1 -0
- package/dist/x402-opener/terms.js +212 -0
- package/dist/x402-opener/terms.js.map +1 -0
- package/dist/zktls/reclaim.d.ts +2 -2
- package/dist/zktls/t2-delivery-proof.d.ts +6 -6
- package/docs/agent-layer.md +3 -2
- package/docs/autonomous-privy-wallet.md +188 -0
- package/docs/cli.md +184 -31
- package/docs/langchain.md +5 -0
- package/docs/mcp-reference.md +75 -5
- package/docs/probe-capability.md +191 -0
- package/docs/quickstart.md +36 -1
- package/docs/threat-model.md +20 -0
- package/docs/x402.md +628 -595
- package/package.json +19 -17
- package/src/capability/probe-capability.ts +355 -0
- package/src/cli/args.ts +29 -0
- package/src/cli/commands/claim.ts +1 -1
- package/src/cli/commands/close.ts +36 -3
- package/src/cli/commands/invoke.ts +5 -2
- package/src/cli/commands/mcp.ts +18 -2
- package/src/cli/commands/open.ts +75 -4
- package/src/cli/commands/pay.ts +442 -0
- package/src/cli/commands/reclaim-unverified.ts +8 -2
- package/src/cli/commands/reclaim.ts +252 -14
- package/src/cli/commands/refund.ts +277 -0
- package/src/cli/commands/status.ts +17 -1
- package/src/cli/commands/streams.ts +10 -14
- package/src/cli/commands/watch.ts +7 -1
- package/src/cli/config.ts +139 -52
- package/src/cli/deps.ts +74 -1
- package/src/cli/errors.ts +24 -1
- package/src/cli/escape-hatch.ts +19 -5
- package/src/cli/listings.ts +43 -10
- package/src/cli/preflight.ts +36 -21
- package/src/cli/privy.ts +4 -2
- package/src/cli/reclaimability.ts +154 -0
- package/src/cli/run.ts +54 -11
- package/src/cli/scan-range.ts +2 -2
- package/src/cli/status.ts +14 -1
- package/src/cli/wallet.ts +2 -2
- package/src/discovery/rate-band.ts +172 -0
- package/src/escrow-generation.ts +135 -0
- package/src/frameworks/agentkit.ts +45 -11
- package/src/frameworks/eliza.ts +27 -5
- package/src/frameworks/langchain.ts +14 -0
- package/src/gateway/caller-auth-gateway.ts +320 -68
- package/src/gateway/http-server.ts +629 -220
- package/src/gateway/probe-auth.ts +191 -0
- package/src/gateway/signed-rate-bounds.ts +164 -0
- package/src/gateway/x402-opener-mode.ts +974 -0
- package/src/index.ts +82 -19
- package/src/mcp/server.ts +319 -42
- package/src/mcp/x402-tools.ts +621 -0
- package/src/network.ts +302 -0
- package/src/sdk/invoke.ts +6 -5
- package/src/wallet/autonomous-wallet-broker.ts +46 -20
- package/src/wallet/autonomous-wallet-protocol.ts +11 -2
- package/src/wallet/autonomous-wallet.ts +4 -2
- package/src/wallet/broker-escrows.ts +66 -0
- package/src/wallet/lifecycle.ts +53 -18
- package/src/wallet/privy-broker-server.ts +35 -25
- package/src/wallet/privy-session-broker.ts +58 -25
- package/src/wallet/privy-session-provider.ts +7 -3
- package/src/wallet/provider.ts +20 -15
- package/src/x402/facilitator.ts +3 -43
- package/src/x402-buyer/guarded-fetch.ts +213 -0
- package/src/x402-buyer/index.ts +9 -0
- package/src/x402-buyer/pay.ts +517 -0
- package/src/x402-opener/abi.ts +881 -0
- package/src/x402-opener/facilitator-entry.ts +45 -0
- package/src/x402-opener/facilitator-server.ts +1014 -0
- package/src/x402-opener/index.ts +13 -0
- package/src/x402-opener/listing-resolver.ts +202 -0
- package/src/x402-opener/refund-relay.ts +1743 -0
- package/src/x402-opener/relayer-queue.ts +18 -0
- package/src/x402-opener/scheme.ts +1133 -0
- package/src/x402-opener/terms.ts +300 -0
- package/dist/gateway/x402-mode.d.ts +0 -123
- package/dist/gateway/x402-mode.d.ts.map +0 -1
- package/dist/gateway/x402-mode.js +0 -212
- package/dist/gateway/x402-mode.js.map +0 -1
- package/dist/x402/delivery-oracle.d.ts +0 -108
- package/dist/x402/delivery-oracle.d.ts.map +0 -1
- package/dist/x402/delivery-oracle.js +0 -174
- package/dist/x402/delivery-oracle.js.map +0 -1
- package/dist/x402/facilitator-server-entry.d.ts +0 -3
- package/dist/x402/facilitator-server-entry.d.ts.map +0 -1
- package/dist/x402/facilitator-server-entry.js +0 -27
- package/dist/x402/facilitator-server-entry.js.map +0 -1
- package/dist/x402/facilitator-server.d.ts +0 -73
- package/dist/x402/facilitator-server.d.ts.map +0 -1
- package/dist/x402/facilitator-server.js +0 -305
- package/dist/x402/facilitator-server.js.map +0 -1
- package/dist/x402/payment-requirements.d.ts +0 -106
- package/dist/x402/payment-requirements.d.ts.map +0 -1
- package/dist/x402/payment-requirements.js +0 -138
- package/dist/x402/payment-requirements.js.map +0 -1
- package/dist/x402/relayer.d.ts +0 -41
- package/dist/x402/relayer.d.ts.map +0 -1
- package/dist/x402/relayer.js +0 -64
- package/dist/x402/relayer.js.map +0 -1
- package/dist/x402/resource-index.d.ts +0 -75
- package/dist/x402/resource-index.d.ts.map +0 -1
- package/dist/x402/resource-index.js +0 -126
- package/dist/x402/resource-index.js.map +0 -1
- package/dist/x402/verified-delivery-facilitator.d.ts +0 -285
- package/dist/x402/verified-delivery-facilitator.d.ts.map +0 -1
- package/dist/x402/verified-delivery-facilitator.js +0 -423
- package/dist/x402/verified-delivery-facilitator.js.map +0 -1
- package/src/gateway/x402-mode.ts +0 -350
- package/src/x402/delivery-oracle.ts +0 -285
- package/src/x402/facilitator-server-entry.ts +0 -35
- package/src/x402/facilitator-server.ts +0 -445
- package/src/x402/payment-requirements.ts +0 -231
- package/src/x402/relayer.ts +0 -122
- package/src/x402/resource-index.ts +0 -228
- package/src/x402/verified-delivery-facilitator.ts +0 -744
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
CheckpointNotReadyError,
|
|
3
|
+
ReclaimFailedError,
|
|
4
|
+
SettlementWindowOpenError,
|
|
5
|
+
StreamNotInCheckpointError,
|
|
6
|
+
} from "@absol-labs/sdk";
|
|
2
7
|
|
|
3
8
|
import { booleanFlag, integerFlag } from "../args.js";
|
|
4
9
|
import { formatUsdc } from "../amounts.js";
|
|
@@ -12,6 +17,12 @@ import {
|
|
|
12
17
|
import { signRecoveryMandate } from "../mandate.js";
|
|
13
18
|
import { assertCanPayGas } from "../preflight.js";
|
|
14
19
|
import { writeClientOptions } from "../deps.js";
|
|
20
|
+
import {
|
|
21
|
+
describeAwaitingCheckpoint,
|
|
22
|
+
describeTerminalBlocker,
|
|
23
|
+
readReclaimBlocker,
|
|
24
|
+
type ReclaimBlocker,
|
|
25
|
+
} from "../reclaimability.js";
|
|
15
26
|
import { isPolicyEnforced, resolveCliWallet } from "../wallet.js";
|
|
16
27
|
import type { CommandContext, CommandSpec } from "../context.js";
|
|
17
28
|
import type { CliReadClient, CliWriteClient } from "../deps.js";
|
|
@@ -20,6 +31,9 @@ import type {
|
|
|
20
31
|
StreamProofTransactionResult,
|
|
21
32
|
} from "../../sdk/client.js";
|
|
22
33
|
import type { StreamV2 } from "@absol-labs/sdk";
|
|
34
|
+
import { streamEscrowV2Abi } from "@absol-labs/shared";
|
|
35
|
+
import { parseEventLogs, type Log } from "viem";
|
|
36
|
+
import { escrowGenerationFor } from "../../escrow-generation.js";
|
|
23
37
|
|
|
24
38
|
/**
|
|
25
39
|
* How long to keep retrying a reclaim that is blocked only by an open
|
|
@@ -56,7 +70,24 @@ export const reclaimCommand: CommandSpec = {
|
|
|
56
70
|
const { account } = wallet;
|
|
57
71
|
const read = deps.createReadClient(config);
|
|
58
72
|
await assertTestnetRpc(config, () => read.getChainId());
|
|
59
|
-
|
|
73
|
+
|
|
74
|
+
// Name the condition from chain state BEFORE anything is built or spent.
|
|
75
|
+
// The public endpoint's revert data is not dependable enough to tell
|
|
76
|
+
// "already reclaimed" from "still running" from "not checkpointed yet", and
|
|
77
|
+
// those three have nothing in common but the word "reverted". See
|
|
78
|
+
// `../reclaimability.ts`.
|
|
79
|
+
const blocker = await readReclaimBlocker(read, streamId, deps.nowSeconds());
|
|
80
|
+
// `--close-first` exists precisely to clear a running stream, so it is the
|
|
81
|
+
// one caller allowed past that refusal. Nothing gets past "already
|
|
82
|
+
// reclaimed": there is no money left to take, with or without a close.
|
|
83
|
+
if (blocker !== null && !(closeFirst && blocker.kind === "running")) {
|
|
84
|
+
throwIfTerminal(blocker, streamId);
|
|
85
|
+
if (blocker.kind === "awaiting-checkpoint") {
|
|
86
|
+
out.note(describeAwaitingCheckpoint(blocker));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
await assertCanPayGas(read, account.address, config.network);
|
|
60
91
|
|
|
61
92
|
const write = deps.createWriteClient(
|
|
62
93
|
config,
|
|
@@ -106,6 +137,19 @@ export const reclaimCommand: CommandSpec = {
|
|
|
106
137
|
`closed in ${closeResult.txHash} — waiting for it to land …`,
|
|
107
138
|
);
|
|
108
139
|
await awaitClosed(read, streamId, deps.sleep, closeResult.txHash);
|
|
140
|
+
// A stream closed before any checkpoint covers its stop time is the
|
|
141
|
+
// ORDINARY outcome of a short trial run, not an exotic one — and it
|
|
142
|
+
// is the state `--close-first` leaves behind by construction. Say
|
|
143
|
+
// what is being waited for, so the retries below read as the
|
|
144
|
+
// advertised wait rather than as a command that has stalled.
|
|
145
|
+
const afterClose = await readReclaimBlocker(
|
|
146
|
+
read,
|
|
147
|
+
streamId,
|
|
148
|
+
deps.nowSeconds(),
|
|
149
|
+
);
|
|
150
|
+
if (afterClose?.kind === "awaiting-checkpoint") {
|
|
151
|
+
out.note(describeAwaitingCheckpoint(afterClose));
|
|
152
|
+
}
|
|
109
153
|
}
|
|
110
154
|
}
|
|
111
155
|
}
|
|
@@ -122,6 +166,15 @@ export const reclaimCommand: CommandSpec = {
|
|
|
122
166
|
attempts,
|
|
123
167
|
intervalMs: interval * 1_000,
|
|
124
168
|
sleep: deps.sleep,
|
|
169
|
+
isRetryable: async (error) =>
|
|
170
|
+
await isWaitingForCheckpoint(
|
|
171
|
+
error,
|
|
172
|
+
read,
|
|
173
|
+
streamId,
|
|
174
|
+
deps.nowSeconds(),
|
|
175
|
+
),
|
|
176
|
+
explainFailure: async (error) =>
|
|
177
|
+
await explainReclaimFailure(error, read, streamId, deps.nowSeconds()),
|
|
125
178
|
onRetry: (attempt, reason) =>
|
|
126
179
|
out.note(
|
|
127
180
|
`reclaim blocked: no checkpoint covers the stream's stop time yet (attempt ${attempt}/${attempts}) — ${reason}`,
|
|
@@ -131,18 +184,31 @@ export const reclaimCommand: CommandSpec = {
|
|
|
131
184
|
// give-up message names the path that needs no proof, and says whether
|
|
132
185
|
// it is open yet.
|
|
133
186
|
exhaustedHint: async () =>
|
|
134
|
-
await describeLastResort(
|
|
187
|
+
await describeLastResort(
|
|
188
|
+
read,
|
|
189
|
+
streamId,
|
|
190
|
+
deps.nowSeconds(),
|
|
191
|
+
escrowGenerationFor(config.chainId, config.escrow),
|
|
192
|
+
),
|
|
135
193
|
},
|
|
136
194
|
);
|
|
137
195
|
|
|
138
196
|
// Read the settled figure back only once the node we are reading from has
|
|
139
|
-
// actually applied the reclaim.
|
|
197
|
+
// actually applied the reclaim. The public RPC is load-balanced, so an
|
|
140
198
|
// immediate read can land on a lagged node and report `settledCumulative: 0`
|
|
141
199
|
// for a stream that just settled a non-zero amount — printing "settled to
|
|
142
200
|
// operator 0 USDC" when it was not zero. Poll for `reclaimed` (which the
|
|
143
201
|
// transaction we just landed sets) so the number beside it is from the same
|
|
144
202
|
// post-reclaim state. Bounded, and falls back to the last value read.
|
|
145
203
|
const stream = await readSettledStream(read, streamId, deps.sleep);
|
|
204
|
+
// The refund comes from the reclaim's own BuyerReclaimed event, never from
|
|
205
|
+
// a post-reclaim read: reclaim overwrites `deposit` with the operator's
|
|
206
|
+
// entitlement, so deposit − settled reads 0 after every reclaim.
|
|
207
|
+
const refunded = refundFromReceipt(
|
|
208
|
+
result.reclaimResult.receipt,
|
|
209
|
+
config.escrow,
|
|
210
|
+
streamId,
|
|
211
|
+
);
|
|
146
212
|
out.result({
|
|
147
213
|
streamId,
|
|
148
214
|
txHash: result.reclaimResult.txHash,
|
|
@@ -152,6 +218,14 @@ export const reclaimCommand: CommandSpec = {
|
|
|
152
218
|
// asked for".
|
|
153
219
|
closeSkippedAlreadyClosed: closeFirst ? alreadyClosed : null,
|
|
154
220
|
settledCumulative: stream?.settledCumulative ?? null,
|
|
221
|
+
// What the reclaim sent back: everything not settled to the operator.
|
|
222
|
+
// Only reported once the read reflects the reclaim, so a lagged node can
|
|
223
|
+
// never print a refund figure computed from pre-reclaim state.
|
|
224
|
+
refundedAmount: refunded,
|
|
225
|
+
// For an x402 stream the refund goes to the opener's payer, whoever sent
|
|
226
|
+
// the (permissionless) reclaim.
|
|
227
|
+
opener: stream?.opener ?? null,
|
|
228
|
+
refundedTo: stream === null ? null : (stream.payer ?? stream.buyer),
|
|
155
229
|
});
|
|
156
230
|
out.print("Reclaimed.");
|
|
157
231
|
out.table([
|
|
@@ -166,6 +240,22 @@ export const reclaimCommand: CommandSpec = {
|
|
|
166
240
|
? []
|
|
167
241
|
: ([
|
|
168
242
|
["settled to operator", formatUsdc(stream.settledCumulative)],
|
|
243
|
+
...(refunded === null
|
|
244
|
+
? []
|
|
245
|
+
: ([
|
|
246
|
+
[
|
|
247
|
+
(stream.opener ?? null) === null
|
|
248
|
+
? "returned to buyer"
|
|
249
|
+
: "returned to payer",
|
|
250
|
+
formatUsdc(refunded),
|
|
251
|
+
],
|
|
252
|
+
] as const)),
|
|
253
|
+
...((stream.opener ?? null) === null
|
|
254
|
+
? []
|
|
255
|
+
: ([
|
|
256
|
+
["via opener", stream.opener as string],
|
|
257
|
+
["refunded to payer", stream.payer],
|
|
258
|
+
] as const)),
|
|
169
259
|
] as const)),
|
|
170
260
|
]);
|
|
171
261
|
},
|
|
@@ -207,7 +297,7 @@ function isAlreadyClosed(error: unknown): boolean {
|
|
|
207
297
|
* Block until the node we read from reports the stream as closed.
|
|
208
298
|
*
|
|
209
299
|
* The close transaction's own receipt is awaited inside the SDK, but
|
|
210
|
-
*
|
|
300
|
+
* the public RPC is load-balanced: the receipt can come back from one node
|
|
211
301
|
* while the very next `simulateContract` lands on another that has not imported
|
|
212
302
|
* the block yet. That node simulates `reclaim` against PRE-close state and
|
|
213
303
|
* reverts `StreamNotReclaimable()`. Confirming the close through the same read
|
|
@@ -243,8 +333,16 @@ export async function awaitClosed(
|
|
|
243
333
|
* time. That is not an error condition — it is the normal ordering of a
|
|
244
334
|
* checkpoint rail, and it happens on the FIRST attempt essentially every time.
|
|
245
335
|
* A CLI that surfaced the raw revert would teach every user that reclaim is
|
|
246
|
-
* broken, so the wait is built in and narrated.
|
|
247
|
-
*
|
|
336
|
+
* broken, so the wait is built in and narrated.
|
|
337
|
+
*
|
|
338
|
+
* What counts as "wait for the next checkpoint" is decided by `isRetryable`,
|
|
339
|
+
* NOT by this function. It used to be `instanceof SettlementWindowOpenError`
|
|
340
|
+
* alone, which missed the two ways the wait actually shows up in practice: the
|
|
341
|
+
* ORACLE refusing a proof for a stream it has not checkpointed yet (the SDK
|
|
342
|
+
* fetches the proof before it ever simulates, so the escrow's revert never
|
|
343
|
+
* happens), and the endpoint returning revert data the ABI cannot decode. Both
|
|
344
|
+
* killed the advertised retry on its first attempt — the second one right
|
|
345
|
+
* after `--close-first` had already spent the buyer's close.
|
|
248
346
|
*/
|
|
249
347
|
export async function reclaimWithBoundedRetry(
|
|
250
348
|
write: CliWriteClient,
|
|
@@ -253,6 +351,10 @@ export async function reclaimWithBoundedRetry(
|
|
|
253
351
|
readonly attempts: number;
|
|
254
352
|
readonly intervalMs: number;
|
|
255
353
|
readonly sleep: (ms: number) => Promise<void>;
|
|
354
|
+
/** True when this failure is the checkpoint wait and will clear on its own. */
|
|
355
|
+
readonly isRetryable: (error: unknown) => Promise<boolean>;
|
|
356
|
+
/** Turn a failure that will NOT clear into something worth reading. */
|
|
357
|
+
readonly explainFailure: (error: unknown) => Promise<unknown>;
|
|
256
358
|
readonly onRetry: (attempt: number, reason: string) => void;
|
|
257
359
|
/** What to tell the buyer once the budget is spent. See `describeLastResort`. */
|
|
258
360
|
readonly exhaustedHint?: () => Promise<string>;
|
|
@@ -263,7 +365,8 @@ export async function reclaimWithBoundedRetry(
|
|
|
263
365
|
try {
|
|
264
366
|
return await write.reclaimStream(await buildInput());
|
|
265
367
|
} catch (error) {
|
|
266
|
-
if (!
|
|
368
|
+
if (!(await options.isRetryable(error)))
|
|
369
|
+
throw await options.explainFailure(error);
|
|
267
370
|
lastError = error;
|
|
268
371
|
if (attempt === options.attempts) break;
|
|
269
372
|
options.onRetry(attempt, describeError(error));
|
|
@@ -299,25 +402,123 @@ async function describeLastResort(
|
|
|
299
402
|
read: CliReadClient,
|
|
300
403
|
streamId: `0x${string}`,
|
|
301
404
|
fallbackNowSeconds: number,
|
|
405
|
+
generation: string,
|
|
302
406
|
): Promise<string> {
|
|
303
407
|
const [stream, grace] = await Promise.all([
|
|
304
408
|
read.getStreamV2(streamId),
|
|
305
409
|
read.escapeGraceSeconds(),
|
|
306
410
|
]);
|
|
307
411
|
const now = await readChainNow(read, fallbackNowSeconds);
|
|
308
|
-
const window = escapeHatchWindow(stream, grace, now.seconds);
|
|
412
|
+
const window = escapeHatchWindow(stream, grace, now.seconds, generation);
|
|
309
413
|
const escapeCommand = `metrik reclaim-unverified ${streamId} --forfeit-unclaimed`;
|
|
310
414
|
return window.ready
|
|
311
415
|
? `the funds are not lost. The no-proof escape hatch is OPEN (${describeEscapeHatch(window)}): \`${escapeCommand}\` takes them back without the oracle — at the cost of forfeiting whatever the operator earned but has not yet claimed. Retrying this command only helps if the oracle comes back.`
|
|
312
416
|
: `the funds are not lost, but retrying only helps if the oracle comes back — this path needs a proof from it. The no-proof escape hatch ${describeEscapeHatch(window)}; from then on \`${escapeCommand}\` takes them back without the oracle, forfeiting whatever the operator earned but has not yet claimed.`;
|
|
313
417
|
}
|
|
314
418
|
|
|
419
|
+
/** Raise a blocker that will not clear on its own as a named CliError. */
|
|
420
|
+
function throwIfTerminal(
|
|
421
|
+
blocker: ReclaimBlocker,
|
|
422
|
+
streamId: `0x${string}`,
|
|
423
|
+
cause?: unknown,
|
|
424
|
+
): void {
|
|
425
|
+
const terminal = describeTerminalBlocker(blocker, streamId);
|
|
426
|
+
if (terminal === null) return;
|
|
427
|
+
throw new CliError(terminal.message, {
|
|
428
|
+
exitCode: 4,
|
|
429
|
+
hint: terminal.hint,
|
|
430
|
+
...(cause === undefined ? {} : { cause }),
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Is this failure the checkpoint wait, i.e. will it clear on its own?
|
|
436
|
+
*
|
|
437
|
+
* Three shapes, in increasing order of how little the endpoint told us:
|
|
438
|
+
*
|
|
439
|
+
* 1. `SettlementWindowOpenError` — the escrow said so and the ABI decoded it.
|
|
440
|
+
* 2. `StreamNotInCheckpointError` / `CheckpointNotReadyError` — the ORACLE has
|
|
441
|
+
* no proof for this stream yet, so the SDK never reached the escrow at all.
|
|
442
|
+
* This is the state `--close-first` creates by construction on a stream
|
|
443
|
+
* closed before its first covering checkpoint, and treating it as fatal is
|
|
444
|
+
* what stranded a buyer's deposit in escrow for three minutes of manual
|
|
445
|
+
* retries while the CLI's own help promised it would wait.
|
|
446
|
+
* 3. A reclaim revert the ABI could not decode. Nothing in the error names the
|
|
447
|
+
* condition, so ask the chain instead — the state is authoritative and the
|
|
448
|
+
* answer is the same one the pre-flight computes.
|
|
449
|
+
*
|
|
450
|
+
* Case 3 is deliberately narrowed to `ReclaimFailedError`: an unrelated failure
|
|
451
|
+
* (no gas, a dead RPC) must still fail on its first attempt rather than burn
|
|
452
|
+
* twelve of them.
|
|
453
|
+
*/
|
|
454
|
+
async function isWaitingForCheckpoint(
|
|
455
|
+
error: unknown,
|
|
456
|
+
read: Pick<
|
|
457
|
+
CliReadClient,
|
|
458
|
+
"getStreamV2" | "latestCheckpointCheckedAt" | "latestBlockTimestamp"
|
|
459
|
+
>,
|
|
460
|
+
streamId: `0x${string}`,
|
|
461
|
+
nowSeconds: number,
|
|
462
|
+
): Promise<boolean> {
|
|
463
|
+
if (isSettlementWindowOpen(error)) return true;
|
|
464
|
+
if (hasNoCheckpointProofYet(error)) return true;
|
|
465
|
+
if (!isReclaimRevert(error)) return false;
|
|
466
|
+
const blocker = await readReclaimBlocker(read, streamId, nowSeconds).catch(
|
|
467
|
+
() => null,
|
|
468
|
+
);
|
|
469
|
+
return blocker?.kind === "awaiting-checkpoint";
|
|
470
|
+
}
|
|
471
|
+
|
|
315
472
|
/**
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
*
|
|
473
|
+
* The oracle could not supply a proof yet: it has no leaf for this stream in
|
|
474
|
+
* the latest checkpoint (404), or no internally consistent checkpoint is ready
|
|
475
|
+
* (503). Both resolve when the next checkpoint lands, ~15-22s apart.
|
|
319
476
|
*/
|
|
320
|
-
function
|
|
477
|
+
function hasNoCheckpointProofYet(error: unknown): boolean {
|
|
478
|
+
for (let current: unknown = error, depth = 0; depth < 8; depth++) {
|
|
479
|
+
if (
|
|
480
|
+
current instanceof StreamNotInCheckpointError ||
|
|
481
|
+
current instanceof CheckpointNotReadyError
|
|
482
|
+
) {
|
|
483
|
+
return true;
|
|
484
|
+
}
|
|
485
|
+
if (!(current instanceof Error) || current.cause === undefined)
|
|
486
|
+
return false;
|
|
487
|
+
current = current.cause;
|
|
488
|
+
}
|
|
489
|
+
return false;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** True when the escrow rejected the reclaim, whatever the reason decoded to. */
|
|
493
|
+
function isReclaimRevert(error: unknown): boolean {
|
|
494
|
+
for (let current: unknown = error, depth = 0; depth < 8; depth++) {
|
|
495
|
+
if (current instanceof ReclaimFailedError) return true;
|
|
496
|
+
if (!(current instanceof Error) || current.cause === undefined)
|
|
497
|
+
return false;
|
|
498
|
+
current = current.cause;
|
|
499
|
+
}
|
|
500
|
+
return false;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* Name a failure that will not clear.
|
|
505
|
+
*
|
|
506
|
+
* `StreamNotReclaimable()` means exactly one thing when the ABI decodes it: the
|
|
507
|
+
* stream is neither closed nor past its expiry. When it does NOT decode — the
|
|
508
|
+
* live failure mode on the public endpoint — the chain is asked the same
|
|
509
|
+
* question, so "already reclaimed" and "still running" are still told apart and
|
|
510
|
+
* still say which command fixes them. The raw error is kept as the `cause`
|
|
511
|
+
* either way.
|
|
512
|
+
*/
|
|
513
|
+
async function explainReclaimFailure(
|
|
514
|
+
error: unknown,
|
|
515
|
+
read: Pick<
|
|
516
|
+
CliReadClient,
|
|
517
|
+
"getStreamV2" | "latestCheckpointCheckedAt" | "latestBlockTimestamp"
|
|
518
|
+
>,
|
|
519
|
+
streamId: `0x${string}`,
|
|
520
|
+
nowSeconds: number,
|
|
521
|
+
): Promise<unknown> {
|
|
321
522
|
if (!(error instanceof Error)) return error;
|
|
322
523
|
for (let current: unknown = error, depth = 0; depth < 8; depth++) {
|
|
323
524
|
if (!(current instanceof Error)) break;
|
|
@@ -326,7 +527,7 @@ function explainReclaimFailure(error: unknown): unknown {
|
|
|
326
527
|
"the stream is still running, so there is nothing to reclaim yet",
|
|
327
528
|
{
|
|
328
529
|
exitCode: 4,
|
|
329
|
-
hint:
|
|
530
|
+
hint: `stop the clock first — \`metrik close ${streamId}\`, or re-run this command with --close-first — or wait for the stream to expire.`,
|
|
330
531
|
cause: error,
|
|
331
532
|
},
|
|
332
533
|
);
|
|
@@ -334,6 +535,18 @@ function explainReclaimFailure(error: unknown): unknown {
|
|
|
334
535
|
if (current.cause === undefined) break;
|
|
335
536
|
current = current.cause;
|
|
336
537
|
}
|
|
538
|
+
if (isReclaimRevert(error)) {
|
|
539
|
+
const blocker = await readReclaimBlocker(read, streamId, nowSeconds).catch(
|
|
540
|
+
() => null,
|
|
541
|
+
);
|
|
542
|
+
if (blocker !== null) {
|
|
543
|
+
try {
|
|
544
|
+
throwIfTerminal(blocker, streamId, error);
|
|
545
|
+
} catch (named) {
|
|
546
|
+
return named;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
337
550
|
return error;
|
|
338
551
|
}
|
|
339
552
|
|
|
@@ -359,6 +572,31 @@ const SETTLED_READ_ATTEMPTS = 5;
|
|
|
359
572
|
// `--interval`), so the two waits are tellable apart in tests and in logs.
|
|
360
573
|
const SETTLED_READ_INTERVAL_MS = 500;
|
|
361
574
|
|
|
575
|
+
/**
|
|
576
|
+
* The amount the reclaim returned, decoded from its BuyerReclaimed event (same
|
|
577
|
+
* signature on V2 and V3). Null when the receipt carries no matching log, so
|
|
578
|
+
* the CLI prints nothing rather than a guessed figure.
|
|
579
|
+
*/
|
|
580
|
+
export function refundFromReceipt(
|
|
581
|
+
receipt: { logs?: readonly Log[] } | undefined,
|
|
582
|
+
escrow: string,
|
|
583
|
+
streamId: `0x${string}`,
|
|
584
|
+
): bigint | null {
|
|
585
|
+
const logs = receipt?.logs;
|
|
586
|
+
if (!Array.isArray(logs)) return null;
|
|
587
|
+
const events = parseEventLogs({
|
|
588
|
+
abi: streamEscrowV2Abi,
|
|
589
|
+
eventName: "BuyerReclaimed",
|
|
590
|
+
logs: logs.filter(
|
|
591
|
+
(log) => log.address?.toLowerCase() === escrow.toLowerCase(),
|
|
592
|
+
),
|
|
593
|
+
});
|
|
594
|
+
const match = events.find(
|
|
595
|
+
(event) => event.args.streamId.toLowerCase() === streamId.toLowerCase(),
|
|
596
|
+
);
|
|
597
|
+
return match === undefined ? null : match.args.amount;
|
|
598
|
+
}
|
|
599
|
+
|
|
362
600
|
async function readSettledStream(
|
|
363
601
|
read: { getStreamV2(streamId: `0x${string}`): Promise<StreamV2> },
|
|
364
602
|
streamId: `0x${string}`,
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
RefundClient,
|
|
3
|
+
RefundRelayResult,
|
|
4
|
+
RefundStatus,
|
|
5
|
+
X402PayerSigner,
|
|
6
|
+
} from "@absol-labs/sdk/x402";
|
|
7
|
+
|
|
8
|
+
import { verifyMandateOwnerSignature } from "../../mandates/mandate.js";
|
|
9
|
+
import { booleanFlag, integerFlag, stringFlag } from "../args.js";
|
|
10
|
+
import { formatUsdc } from "../amounts.js";
|
|
11
|
+
import { assertTestnetRpc, parseBytes32 } from "../config.js";
|
|
12
|
+
import type { CliX402 } from "../deps.js";
|
|
13
|
+
import { CliError, configError, usageError } from "../errors.js";
|
|
14
|
+
import { signRecoveryMandate } from "../mandate.js";
|
|
15
|
+
import { isPrivyWalletSource, resolveCliWallet } from "../wallet.js";
|
|
16
|
+
import type { CommandContext, CommandSpec } from "../context.js";
|
|
17
|
+
|
|
18
|
+
/** Environment fallback for `--refund-url`. */
|
|
19
|
+
export const REFUND_URL_ENV = "METRIK_AGENT_REFUND_URL";
|
|
20
|
+
|
|
21
|
+
const DEFAULT_ATTEMPTS = 5;
|
|
22
|
+
const DEFAULT_MAX_WAIT_SECONDS = 60;
|
|
23
|
+
|
|
24
|
+
export const refundCommand: CommandSpec = {
|
|
25
|
+
name: "refund",
|
|
26
|
+
summary:
|
|
27
|
+
"Recover the unearned part of an x402 payment through the gasless refund relay",
|
|
28
|
+
usage:
|
|
29
|
+
"metrik refund <streamId> --refund-url <url> [--close] [--reclaim] [--attempts 5] [--max-wait 60]",
|
|
30
|
+
flags: ["refund-url", "close", "reclaim", "attempts", "max-wait"],
|
|
31
|
+
// `--close` signs the payer's EIP-712 Close (off-chain); the RELAY broadcasts
|
|
32
|
+
// and pays the gas. `--reclaim` needs no wallet at all: `opener.reclaim` is
|
|
33
|
+
// permissionless and always pays `payerOf(streamId)`.
|
|
34
|
+
signs: false,
|
|
35
|
+
requiresKey: false,
|
|
36
|
+
async run(context: CommandContext): Promise<void> {
|
|
37
|
+
const { args, config, env, out, deps } = context;
|
|
38
|
+
if (deps.x402 === undefined) {
|
|
39
|
+
throw new CliError(
|
|
40
|
+
"this CLI build has no x402 dependency wired (CliDependencies.x402)",
|
|
41
|
+
{ exitCode: 4 },
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
const x402: CliX402 = deps.x402;
|
|
45
|
+
const [streamIdArg] = args.positionals;
|
|
46
|
+
if (streamIdArg === undefined) {
|
|
47
|
+
throw usageError("metrik refund requires a <streamId>");
|
|
48
|
+
}
|
|
49
|
+
const streamId = parseBytes32(streamIdArg, "<streamId>");
|
|
50
|
+
const refundUrl = resolveRefundUrl(
|
|
51
|
+
stringFlag(args, "refund-url") ?? env[REFUND_URL_ENV],
|
|
52
|
+
streamId,
|
|
53
|
+
);
|
|
54
|
+
const doClose = booleanFlag(args, "close");
|
|
55
|
+
const doReclaim = booleanFlag(args, "reclaim");
|
|
56
|
+
const attempts = integerFlag(args, "attempts") ?? DEFAULT_ATTEMPTS;
|
|
57
|
+
const maxWait = integerFlag(args, "max-wait") ?? DEFAULT_MAX_WAIT_SECONDS;
|
|
58
|
+
if (attempts < 1) throw usageError("--attempts must be at least 1");
|
|
59
|
+
|
|
60
|
+
const read = deps.createReadClient(config);
|
|
61
|
+
await assertTestnetRpc(config, () => read.getChainId());
|
|
62
|
+
// Bind the relay to the stream AS THE CHAIN SEES IT: the opener comes from
|
|
63
|
+
// `factory.isOpener(buyer)` on-chain, never from the relay's answer.
|
|
64
|
+
const stream = await read.getStreamV2(streamId);
|
|
65
|
+
const opener = stream.opener ?? null;
|
|
66
|
+
if (opener === null) {
|
|
67
|
+
throw configError(
|
|
68
|
+
`stream ${streamId} was not opened by an x402 opener, so the refund relay does not serve it`,
|
|
69
|
+
`the buyer is ${stream.buyer}, an ordinary wallet: use \`metrik close ${streamId}\` and \`metrik reclaim ${streamId}\` with that wallet.`,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const refunds = await x402.refundClient(config, {
|
|
74
|
+
refundUrl,
|
|
75
|
+
streamId,
|
|
76
|
+
opener,
|
|
77
|
+
maxAttempts: attempts,
|
|
78
|
+
maxDelayMs: maxWait * 1_000,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
let closeResult: RefundRelayResult | null = null;
|
|
82
|
+
if (doClose) {
|
|
83
|
+
const wallet = await resolveCliWallet(env, {
|
|
84
|
+
purpose: "capability",
|
|
85
|
+
note: out.note,
|
|
86
|
+
rpcUrl: config.rpcUrl,
|
|
87
|
+
});
|
|
88
|
+
if (isPrivyWalletSource(wallet.source)) {
|
|
89
|
+
throw configError(
|
|
90
|
+
"metrik refund --close cannot sign with a Privy wallet",
|
|
91
|
+
"the payer signs the opener's EIP-712 Close, which the Privy broker's typed-data policy does not allow. Use the key that paid.",
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
// Buyer recovery: authorized on the mandate OWNER's signature alone, like
|
|
95
|
+
// `metrik close` — never on caps or expiry, so nothing can strand the
|
|
96
|
+
// payer's own money. The SDK then refuses a signer that is not
|
|
97
|
+
// `payerOf(streamId)` before anything is signed for the relay.
|
|
98
|
+
const mandate = await signRecoveryMandate(wallet.account, config.chainId);
|
|
99
|
+
const decision = await verifyMandateOwnerSignature(mandate);
|
|
100
|
+
if (!decision.allowed) {
|
|
101
|
+
throw new CliError(`mandate denied: ${decision.reason}`, {
|
|
102
|
+
exitCode: 3,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
closeResult = await relay(() =>
|
|
106
|
+
refunds.close({
|
|
107
|
+
signer: wallet.account as unknown as X402PayerSigner,
|
|
108
|
+
}),
|
|
109
|
+
);
|
|
110
|
+
out.note(
|
|
111
|
+
`close relayed in ${closeResult.transaction}${closeResult.verified ? " (receipt verified on-chain)" : ""}`,
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
let reclaimResult: RefundRelayResult | null = null;
|
|
116
|
+
if (doReclaim) {
|
|
117
|
+
reclaimResult = await relay(() => refunds.reclaim());
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const status = await relay(() => refunds.status());
|
|
121
|
+
out.result({
|
|
122
|
+
streamId,
|
|
123
|
+
opener,
|
|
124
|
+
payer: status.payer,
|
|
125
|
+
status: status.status,
|
|
126
|
+
reclaimed: status.reclaimed,
|
|
127
|
+
reclaimable: status.reclaimable,
|
|
128
|
+
next: status.next,
|
|
129
|
+
close:
|
|
130
|
+
closeResult === null
|
|
131
|
+
? null
|
|
132
|
+
: {
|
|
133
|
+
transaction: closeResult.transaction,
|
|
134
|
+
verified: closeResult.verified,
|
|
135
|
+
},
|
|
136
|
+
reclaim:
|
|
137
|
+
reclaimResult === null
|
|
138
|
+
? null
|
|
139
|
+
: {
|
|
140
|
+
transaction: reclaimResult.transaction,
|
|
141
|
+
amount: reclaimResult.amount,
|
|
142
|
+
verified: reclaimResult.verified,
|
|
143
|
+
},
|
|
144
|
+
refundIsAutomatic: false,
|
|
145
|
+
});
|
|
146
|
+
out.print(`x402 stream ${streamId}`);
|
|
147
|
+
out.table(statusRows(status, closeResult, reclaimResult));
|
|
148
|
+
out.print("");
|
|
149
|
+
out.print(nextStep(status, streamId, refundUrl));
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Accepts the relay's full stream URL, a `{streamId}` template, or the relay's
|
|
155
|
+
* base origin (`https://relay.example` -> `https://relay.example/streams/<id>`).
|
|
156
|
+
*/
|
|
157
|
+
export function resolveRefundUrl(
|
|
158
|
+
raw: string | undefined,
|
|
159
|
+
streamId: `0x${string}`,
|
|
160
|
+
): string {
|
|
161
|
+
if (raw === undefined || raw.trim().length === 0) {
|
|
162
|
+
throw usageError(
|
|
163
|
+
`metrik refund needs the seller's refund relay: pass --refund-url (printed by \`metrik pay\`) or set ${REFUND_URL_ENV}`,
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
const value = raw.trim();
|
|
167
|
+
if (value.includes("{streamId}")) return value;
|
|
168
|
+
let url: URL;
|
|
169
|
+
try {
|
|
170
|
+
url = new URL(value);
|
|
171
|
+
} catch {
|
|
172
|
+
throw usageError(
|
|
173
|
+
`--refund-url must be an absolute http(s) URL (got "${value}")`,
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
if (/\/streams\/0x[0-9a-fA-F]{64}\/?$/.test(url.pathname)) return value;
|
|
177
|
+
url.pathname = `${url.pathname.replace(/\/+$/, "")}/streams/${streamId}`;
|
|
178
|
+
return url.toString();
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function relay<T>(task: () => Promise<T>): Promise<T> {
|
|
182
|
+
try {
|
|
183
|
+
return await task();
|
|
184
|
+
} catch (error) {
|
|
185
|
+
throw explainRefundFailure(error);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function explainRefundFailure(error: unknown): unknown {
|
|
190
|
+
if (!(error instanceof Error)) return error;
|
|
191
|
+
switch (error.name) {
|
|
192
|
+
case "RefundNotReadyError": {
|
|
193
|
+
const retryAt = (error as { retryAt?: number | null }).retryAt;
|
|
194
|
+
return new CliError(error.message, {
|
|
195
|
+
exitCode: 3,
|
|
196
|
+
hint:
|
|
197
|
+
retryAt === undefined || retryAt === null
|
|
198
|
+
? "the relay is not ready to reclaim yet (the settlement window is open). Re-run later with --reclaim."
|
|
199
|
+
: `the relay can reclaim from ${new Date(retryAt * 1000).toISOString()}. Re-run then with --reclaim (or raise --max-wait to wait here).`,
|
|
200
|
+
cause: error,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
case "RefundRelayError":
|
|
204
|
+
return new CliError(error.message, {
|
|
205
|
+
exitCode: 3,
|
|
206
|
+
hint: `relay refusal${(error as { code?: string }).code === undefined ? "" : ` (${(error as { code?: string }).code})`}. The payer can always recover on-chain without the relay: \`metrik close\` (as the payer, needs gas) and \`metrik reclaim\` (anyone).`,
|
|
207
|
+
cause: error,
|
|
208
|
+
});
|
|
209
|
+
case "NotStreamPayerError":
|
|
210
|
+
return new CliError(error.message, {
|
|
211
|
+
exitCode: 3,
|
|
212
|
+
hint: "only the address that paid (payerOf(streamId)) can sign the close. Nothing was signed.",
|
|
213
|
+
cause: error,
|
|
214
|
+
});
|
|
215
|
+
default:
|
|
216
|
+
return error;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function statusRows(
|
|
221
|
+
status: RefundStatus,
|
|
222
|
+
closeResult: RefundRelayResult | null,
|
|
223
|
+
reclaimResult: RefundRelayResult | null,
|
|
224
|
+
): (readonly [string, string])[] {
|
|
225
|
+
const rows: (readonly [string, string])[] = [
|
|
226
|
+
[
|
|
227
|
+
"status",
|
|
228
|
+
status.reclaimed ? `${status.status} (reclaimed)` : status.status,
|
|
229
|
+
],
|
|
230
|
+
["payer", status.payer],
|
|
231
|
+
["opener", status.opener],
|
|
232
|
+
[
|
|
233
|
+
"reclaimable",
|
|
234
|
+
status.reclaimable === null ? "-" : formatUsdc(status.reclaimable),
|
|
235
|
+
],
|
|
236
|
+
["next", status.next.action],
|
|
237
|
+
];
|
|
238
|
+
if (closeResult !== null) {
|
|
239
|
+
rows.push([
|
|
240
|
+
"close tx",
|
|
241
|
+
`${closeResult.transaction}${closeResult.verified ? " (verified)" : " (relay-reported)"}`,
|
|
242
|
+
]);
|
|
243
|
+
}
|
|
244
|
+
if (reclaimResult !== null) {
|
|
245
|
+
rows.push([
|
|
246
|
+
"reclaim tx",
|
|
247
|
+
`${reclaimResult.transaction}${reclaimResult.verified ? " (verified)" : " (relay-reported)"}`,
|
|
248
|
+
]);
|
|
249
|
+
if (reclaimResult.amount !== null) {
|
|
250
|
+
rows.push(["refunded to payer", formatUsdc(reclaimResult.amount)]);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return rows;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function nextStep(
|
|
257
|
+
status: RefundStatus,
|
|
258
|
+
streamId: `0x${string}`,
|
|
259
|
+
refundUrl: string,
|
|
260
|
+
): string {
|
|
261
|
+
if (status.reclaimed) {
|
|
262
|
+
return "Reclaimed: the unearned remainder was returned to the payer.";
|
|
263
|
+
}
|
|
264
|
+
const base = `metrik refund ${streamId} --refund-url ${refundUrl}`;
|
|
265
|
+
switch (status.next.action) {
|
|
266
|
+
case "close":
|
|
267
|
+
return `Refunds are NOT automatic. The stream is still running: stop it with ${base} --close --reclaim`;
|
|
268
|
+
case "reclaim":
|
|
269
|
+
return `Refunds are NOT automatic. Reclaim the unearned remainder with ${base} --reclaim`;
|
|
270
|
+
case "wait":
|
|
271
|
+
return `Refunds are NOT automatic, and the settlement window is still open${status.next.retryAt === undefined ? "" : ` until ${new Date(status.next.retryAt * 1000).toISOString()}`}. Then run ${base} --reclaim`;
|
|
272
|
+
default:
|
|
273
|
+
return `Refunds are NOT automatic. The relay says: ${status.next.message ?? status.next.action}.`;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export type { RefundClient };
|