@dvmkit/dvm-cli 0.16.0 → 0.17.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/dist/{chunk-LDYMUQZE.js → chunk-DE7TEOUR.js} +2229 -2090
- package/dist/{chunk-WRIXUSMR.js → chunk-ESQ6DCS3.js} +3 -3
- package/dist/{chunk-WSLZBJ52.js → chunk-OEWENVJ7.js} +4 -4
- package/dist/{chunk-NSA2RJ2T.js → chunk-R6FZT6S2.js} +1 -1
- package/dist/{chunk-2TNH4ME5.js → chunk-REIUNZQX.js} +1 -1
- package/dist/{chunk-U2PODYIS.js → chunk-THTPKBZX.js} +1 -0
- package/dist/{chunk-H6WQ4S6K.js → chunk-VLD7OKSH.js} +5 -5
- package/dist/{chunk-CEBEPXQ7.js → chunk-ZGBCVQF2.js} +2 -2
- package/dist/{client-S5PTHG25.js → client-3JOMNAIQ.js} +2 -2
- package/dist/dvm.js +329 -162
- package/dist/{internal-3SIUYRWP.js → internal-L362ZUWL.js} +1 -1
- package/dist/{lifecycle-7NHL5ATK.js → lifecycle-BH4OA5I3.js} +2 -2
- package/dist/{pocket-refill-3CA4PFXG.js → pocket-refill-5BEM22UM.js} +8 -8
- package/dist/{tempo-lifecycle-GAM3DJ63.js → tempo-lifecycle-WGTX6MJR.js} +4 -4
- package/dist/{tempo-wallet-JTARPYLN.js → tempo-wallet-OTB2YSWE.js} +3 -3
- package/dist/{wallet-QKAKRLPI.js → wallet-73EJBUSO.js} +3 -3
- package/package.json +2 -1
- package/skills/dvm/calling.md +2 -0
|
@@ -3,7 +3,15 @@ import { createRequire as __dvmCreateRequire } from "node:module";
|
|
|
3
3
|
const require = __dvmCreateRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
5
|
connectedTempoAccount
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-OEWENVJ7.js";
|
|
7
|
+
import {
|
|
8
|
+
loadX402Wallet,
|
|
9
|
+
x402NetworkLabel
|
|
10
|
+
} from "./chunk-VLD7OKSH.js";
|
|
11
|
+
import {
|
|
12
|
+
isCreditPosture,
|
|
13
|
+
loadConfig
|
|
14
|
+
} from "./chunk-ESQ6DCS3.js";
|
|
7
15
|
import {
|
|
8
16
|
addOutputWarnings,
|
|
9
17
|
costAnchor,
|
|
@@ -18,15 +26,7 @@ import {
|
|
|
18
26
|
resolveBtcUsdRate,
|
|
19
27
|
tryResolveBtcUsdRate,
|
|
20
28
|
tryX402Payment
|
|
21
|
-
} from "./chunk-
|
|
22
|
-
import {
|
|
23
|
-
loadX402Wallet,
|
|
24
|
-
x402NetworkLabel
|
|
25
|
-
} from "./chunk-H6WQ4S6K.js";
|
|
26
|
-
import {
|
|
27
|
-
isCreditPosture,
|
|
28
|
-
loadConfig
|
|
29
|
-
} from "./chunk-WRIXUSMR.js";
|
|
29
|
+
} from "./chunk-R6FZT6S2.js";
|
|
30
30
|
import {
|
|
31
31
|
BUDGET_FILE,
|
|
32
32
|
CONFIG_DIR,
|
|
@@ -83,6 +83,7 @@ import {
|
|
|
83
83
|
fundingModeForTempoIntent,
|
|
84
84
|
fundingModeForX402Flavour,
|
|
85
85
|
getLastKnownBtcRate,
|
|
86
|
+
getTempoUsdcBalance,
|
|
86
87
|
getWallet,
|
|
87
88
|
isCreditFundRail,
|
|
88
89
|
isDrawFundingReceipt,
|
|
@@ -182,7 +183,7 @@ import {
|
|
|
182
183
|
x402PendingUnsettled,
|
|
183
184
|
x402RequiredFromError,
|
|
184
185
|
x402VoucherPendingState
|
|
185
|
-
} from "./chunk-
|
|
186
|
+
} from "./chunk-THTPKBZX.js";
|
|
186
187
|
import {
|
|
187
188
|
Challenge_exports,
|
|
188
189
|
Credential_exports
|
|
@@ -192,6 +193,8 @@ import {
|
|
|
192
193
|
X402_BATCH_SETTLEMENT_SCHEME,
|
|
193
194
|
X402_EXACT_SCHEME,
|
|
194
195
|
decodePayment,
|
|
196
|
+
ensureAddress,
|
|
197
|
+
getX402Balance,
|
|
195
198
|
isAbortError,
|
|
196
199
|
isValidEvmPrivateKey,
|
|
197
200
|
microToSats,
|
|
@@ -2936,2308 +2939,2440 @@ function bookCreditPayment(jobId, intent) {
|
|
|
2936
2939
|
}, true);
|
|
2937
2940
|
}
|
|
2938
2941
|
|
|
2939
|
-
// src/lib/
|
|
2942
|
+
// src/lib/favorites.ts
|
|
2943
|
+
var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
|
|
2940
2944
|
import {
|
|
2941
|
-
appendFileSync,
|
|
2942
2945
|
closeSync as closeSync4,
|
|
2943
|
-
|
|
2946
|
+
fchmodSync,
|
|
2947
|
+
fsyncSync as fsyncSync4,
|
|
2944
2948
|
openSync as openSync4,
|
|
2945
2949
|
readFileSync as readFileSync4,
|
|
2946
|
-
|
|
2947
|
-
statSync
|
|
2950
|
+
renameSync as renameSync2,
|
|
2951
|
+
statSync,
|
|
2952
|
+
unlinkSync as unlinkSync2,
|
|
2953
|
+
writeFileSync as writeFileSync4
|
|
2948
2954
|
} from "fs";
|
|
2949
|
-
import {
|
|
2950
|
-
var
|
|
2951
|
-
function
|
|
2952
|
-
|
|
2953
|
-
|
|
2955
|
+
import { dirname as dirname2 } from "path";
|
|
2956
|
+
var DEFAULT_FILE_MODE = 384;
|
|
2957
|
+
function loadFavorites() {
|
|
2958
|
+
let raw;
|
|
2959
|
+
try {
|
|
2960
|
+
raw = readFileSync4(FAVORITES_FILE, "utf8");
|
|
2961
|
+
} catch (error) {
|
|
2962
|
+
if (nodeErrorCode(error) === "ENOENT") return {};
|
|
2963
|
+
throw unreadableFavorites(error);
|
|
2964
|
+
}
|
|
2965
|
+
try {
|
|
2966
|
+
const parsed = JSON.parse(raw);
|
|
2967
|
+
if (!isFavoritesMap(parsed)) throw new Error("invalid favorites shape");
|
|
2968
|
+
return parsed;
|
|
2969
|
+
} catch (error) {
|
|
2970
|
+
throw unreadableFavorites(error);
|
|
2971
|
+
}
|
|
2954
2972
|
}
|
|
2955
|
-
function
|
|
2956
|
-
return
|
|
2973
|
+
async function saveFavorite(alias, fav) {
|
|
2974
|
+
return withFavoritesLock(() => {
|
|
2975
|
+
const favs = loadFavorites();
|
|
2976
|
+
const existed = Object.hasOwn(favs, alias);
|
|
2977
|
+
favs[alias] = fav;
|
|
2978
|
+
writeFavorites(favs);
|
|
2979
|
+
return existed;
|
|
2980
|
+
});
|
|
2957
2981
|
}
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
-
|
|
2977
|
-
|
|
2978
|
-
});
|
|
2979
|
-
if (newMessages.length === 0) return;
|
|
2980
|
-
ensureConfigSubdir(MESSAGES_DIR);
|
|
2981
|
-
const lines = newMessages.map((message) => JSON.stringify(message)).join("\n") + "\n";
|
|
2982
|
-
appendFileSync(this.filePath, lines);
|
|
2983
|
-
this.syncFromDisk();
|
|
2982
|
+
async function removeFavorite(alias) {
|
|
2983
|
+
return withFavoritesLock(() => {
|
|
2984
|
+
const favs = loadFavorites();
|
|
2985
|
+
if (!Object.hasOwn(favs, alias)) return false;
|
|
2986
|
+
const { [alias]: _, ...rest } = favs;
|
|
2987
|
+
writeFavorites(rest);
|
|
2988
|
+
return true;
|
|
2989
|
+
});
|
|
2990
|
+
}
|
|
2991
|
+
function resolveEndpoint(input) {
|
|
2992
|
+
if (!input.startsWith("@")) return input;
|
|
2993
|
+
const alias = input.slice(1);
|
|
2994
|
+
const favs = loadFavorites();
|
|
2995
|
+
const fav = Object.hasOwn(favs, alias) ? favs[alias] : void 0;
|
|
2996
|
+
if (!fav) {
|
|
2997
|
+
throw new DvmError(
|
|
2998
|
+
"unknown_favorite",
|
|
2999
|
+
`No favorite named "${alias}".`,
|
|
3000
|
+
"Run 'dvm fav list' to see saved favorites, or 'dvm fav add <endpoint>' to save one."
|
|
3001
|
+
);
|
|
2984
3002
|
}
|
|
2985
|
-
|
|
2986
|
-
|
|
2987
|
-
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
if (changedFile || shrank || changedSinceRead && !this.checkpointMatches()) {
|
|
2996
|
-
this.reset(identity);
|
|
3003
|
+
return fav.endpoint;
|
|
3004
|
+
}
|
|
3005
|
+
function deriveAlias(endpoint) {
|
|
3006
|
+
try {
|
|
3007
|
+
const hostname = new URL(endpoint).hostname;
|
|
3008
|
+
if (hostname.endsWith(".dvmkit.ai")) {
|
|
3009
|
+
const prefix = hostname.replace(".dvmkit.ai", "");
|
|
3010
|
+
const dashIdx = prefix.indexOf("--");
|
|
3011
|
+
if (dashIdx !== -1) return prefix.slice(dashIdx + 2);
|
|
3012
|
+
return prefix;
|
|
2997
3013
|
}
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
const bytes = readRange(this.filePath, this.offset, snapshot.size);
|
|
3002
|
-
this.offset += bytes.byteLength;
|
|
3003
|
-
this.consume(bytes);
|
|
3004
|
-
this.checkpoint = trailingBytes(this.checkpoint, bytes, CHECKPOINT_BYTES);
|
|
3014
|
+
return hostname.replace(/\.[^.]+$/, "").replace(/\./g, "-");
|
|
3015
|
+
} catch {
|
|
3016
|
+
return endpoint.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
|
|
3005
3017
|
}
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3018
|
+
}
|
|
3019
|
+
async function withFavoritesLock(fn) {
|
|
3020
|
+
ensureConfigDir();
|
|
3021
|
+
let release;
|
|
3022
|
+
try {
|
|
3023
|
+
release = await import_proper_lockfile2.default.lock(FAVORITES_FILE, {
|
|
3024
|
+
lockfilePath: `${FAVORITES_FILE}.lock`,
|
|
3025
|
+
realpath: false,
|
|
3026
|
+
stale: 3e4,
|
|
3027
|
+
retries: { retries: 10, factor: 1, minTimeout: 100, maxTimeout: 100 }
|
|
3028
|
+
});
|
|
3029
|
+
} catch {
|
|
3030
|
+
throw new DvmError(
|
|
3031
|
+
"favorites_locked",
|
|
3032
|
+
"Another dvm process is updating saved favorites.",
|
|
3033
|
+
"Wait a moment and retry."
|
|
3012
3034
|
);
|
|
3013
|
-
return actual.equals(this.checkpoint);
|
|
3014
3035
|
}
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
this.pending = combined;
|
|
3020
|
-
this.parseLine(this.pending);
|
|
3021
|
-
return;
|
|
3022
|
-
}
|
|
3023
|
-
const complete = combined.subarray(0, finalNewline).toString("utf8");
|
|
3024
|
-
for (const line of complete.split("\n")) this.parseLine(line);
|
|
3025
|
-
this.pending = combined.subarray(finalNewline + 1);
|
|
3026
|
-
this.parseLine(this.pending);
|
|
3036
|
+
try {
|
|
3037
|
+
return await fn();
|
|
3038
|
+
} finally {
|
|
3039
|
+
await release().catch(() => void 0);
|
|
3027
3040
|
}
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3041
|
+
}
|
|
3042
|
+
function writeFavorites(favorites) {
|
|
3043
|
+
const mode = favoritesFileMode();
|
|
3044
|
+
const temporary = `${FAVORITES_FILE}.${String(process.pid)}.${randomSuffix()}.tmp`;
|
|
3045
|
+
const contents = JSON.stringify(favorites, null, 2) + "\n";
|
|
3046
|
+
let fd;
|
|
3047
|
+
try {
|
|
3048
|
+
fd = openSync4(temporary, "wx", mode);
|
|
3049
|
+
fchmodSync(fd, mode);
|
|
3050
|
+
writeFileSync4(fd, contents);
|
|
3051
|
+
fsyncSync4(fd);
|
|
3052
|
+
closeSync4(fd);
|
|
3053
|
+
fd = void 0;
|
|
3054
|
+
renameSync2(temporary, FAVORITES_FILE);
|
|
3055
|
+
fsyncDirectory3(dirname2(FAVORITES_FILE));
|
|
3056
|
+
} catch (error) {
|
|
3057
|
+
if (fd !== void 0) {
|
|
3058
|
+
try {
|
|
3059
|
+
closeSync4(fd);
|
|
3060
|
+
} catch {
|
|
3061
|
+
}
|
|
3035
3062
|
}
|
|
3036
|
-
}
|
|
3037
|
-
reset(identity) {
|
|
3038
|
-
this.seqs.clear();
|
|
3039
|
-
this.identity = identity;
|
|
3040
|
-
this.offset = 0;
|
|
3041
|
-
this.pending = Buffer.alloc(0);
|
|
3042
|
-
this.checkpoint = Buffer.alloc(0);
|
|
3043
|
-
this.modifiedAt = 0;
|
|
3044
|
-
}
|
|
3045
|
-
};
|
|
3046
|
-
function loadMessages(jobId, after) {
|
|
3047
|
-
const filePath = messageFilePath(jobId);
|
|
3048
|
-
if (!existsSync4(filePath)) return [];
|
|
3049
|
-
const content = readFileSync4(filePath, "utf-8").trim();
|
|
3050
|
-
if (!content) return [];
|
|
3051
|
-
const messages = [];
|
|
3052
|
-
for (const line of content.split("\n")) {
|
|
3053
|
-
if (!line.trim()) continue;
|
|
3054
3063
|
try {
|
|
3055
|
-
|
|
3056
|
-
if (after === void 0 || msg.seq > after) {
|
|
3057
|
-
messages.push(msg);
|
|
3058
|
-
}
|
|
3064
|
+
unlinkSync2(temporary);
|
|
3059
3065
|
} catch {
|
|
3060
3066
|
}
|
|
3067
|
+
throw error;
|
|
3061
3068
|
}
|
|
3062
|
-
return messages;
|
|
3063
3069
|
}
|
|
3064
|
-
function
|
|
3065
|
-
return join3(MESSAGES_DIR, `${jobId}.jsonl`);
|
|
3066
|
-
}
|
|
3067
|
-
function statFile(filePath) {
|
|
3070
|
+
function favoritesFileMode() {
|
|
3068
3071
|
try {
|
|
3069
|
-
return statSync(
|
|
3072
|
+
return statSync(FAVORITES_FILE).mode & 511;
|
|
3070
3073
|
} catch (error) {
|
|
3071
|
-
if (error
|
|
3074
|
+
if (nodeErrorCode(error) === "ENOENT") return DEFAULT_FILE_MODE;
|
|
3072
3075
|
throw error;
|
|
3073
3076
|
}
|
|
3074
3077
|
}
|
|
3075
|
-
function
|
|
3076
|
-
|
|
3077
|
-
|
|
3078
|
-
function sameIdentity(left, right) {
|
|
3079
|
-
return left.dev === right.dev && left.ino === right.ino;
|
|
3080
|
-
}
|
|
3081
|
-
function readRange(filePath, start, end) {
|
|
3082
|
-
const expected = Math.max(0, end - start);
|
|
3083
|
-
const buffer = Buffer.allocUnsafe(expected);
|
|
3084
|
-
const fd = openSync4(filePath, "r");
|
|
3085
|
-
let total = 0;
|
|
3078
|
+
function fsyncDirectory3(path) {
|
|
3079
|
+
if (process.platform === "win32") return;
|
|
3080
|
+
const fd = openSync4(path, "r");
|
|
3086
3081
|
try {
|
|
3087
|
-
|
|
3088
|
-
const read = readSync(fd, buffer, total, expected - total, start + total);
|
|
3089
|
-
if (read === 0) break;
|
|
3090
|
-
total += read;
|
|
3091
|
-
}
|
|
3082
|
+
fsyncSync4(fd);
|
|
3092
3083
|
} finally {
|
|
3093
3084
|
closeSync4(fd);
|
|
3094
3085
|
}
|
|
3095
|
-
return total === expected ? buffer : buffer.subarray(0, total);
|
|
3096
|
-
}
|
|
3097
|
-
function trailingBytes(previous, next, limit) {
|
|
3098
|
-
if (next.length >= limit) return Buffer.from(next.subarray(next.length - limit));
|
|
3099
|
-
const combined = Buffer.concat([previous, next]);
|
|
3100
|
-
return Buffer.from(combined.subarray(Math.max(0, combined.length - limit)));
|
|
3101
3086
|
}
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
function maxSeq(msgs, fallback) {
|
|
3105
|
-
if (msgs.length === 0) return fallback;
|
|
3106
|
-
return Math.max(...msgs.map((m) => m.seq));
|
|
3087
|
+
function randomSuffix() {
|
|
3088
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
3107
3089
|
}
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
...
|
|
3116
|
-
|
|
3117
|
-
|
|
3090
|
+
function unreadableFavorites(error) {
|
|
3091
|
+
return new DvmError(
|
|
3092
|
+
"favorites_unreadable",
|
|
3093
|
+
"Saved favorites are corrupt or unreadable.",
|
|
3094
|
+
`The original file at ${FAVORITES_FILE} was left unchanged. Restore it from a backup, or move it aside before rebuilding favorites.`,
|
|
3095
|
+
{
|
|
3096
|
+
path: FAVORITES_FILE,
|
|
3097
|
+
...nodeErrorCode(error) ? { error_code: nodeErrorCode(error) } : {}
|
|
3098
|
+
}
|
|
3099
|
+
);
|
|
3118
3100
|
}
|
|
3119
|
-
function
|
|
3120
|
-
|
|
3101
|
+
function nodeErrorCode(error) {
|
|
3102
|
+
if (!(error instanceof Error) || !("code" in error)) return void 0;
|
|
3103
|
+
const code = error.code;
|
|
3104
|
+
return typeof code === "string" && /^E[A-Z0-9_]{1,63}$/.test(code) ? code : void 0;
|
|
3121
3105
|
}
|
|
3122
|
-
function
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3106
|
+
function isFavoritesMap(value) {
|
|
3107
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
3108
|
+
return Object.values(value).every(isFavorite);
|
|
3109
|
+
}
|
|
3110
|
+
function isFavorite(value) {
|
|
3111
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
3112
|
+
const candidate = value;
|
|
3113
|
+
return typeof candidate.endpoint === "string" && typeof candidate.addedAt === "number" && Number.isFinite(candidate.addedAt) && (candidate.name === void 0 || typeof candidate.name === "string");
|
|
3128
3114
|
}
|
|
3129
3115
|
|
|
3130
|
-
// src/lib/
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3116
|
+
// src/lib/job-access.ts
|
|
3117
|
+
function resolveJobAccess(jobId, opts) {
|
|
3118
|
+
const endpoint = opts.endpoint ?? process.env.DVM_JOB_ENDPOINT;
|
|
3119
|
+
const stored = loadJob(jobId, endpoint === void 0 ? void 0 : resolveEndpoint(endpoint));
|
|
3120
|
+
return resolveJobAccessWithRecord(jobId, opts, stored);
|
|
3121
|
+
}
|
|
3122
|
+
function resolveJobAccessWithRecord(jobId, opts, record) {
|
|
3123
|
+
const endpointOverride = opts.endpoint ?? process.env.DVM_JOB_ENDPOINT;
|
|
3124
|
+
const tokenOverride = opts.jobToken ?? process.env.DVM_JOB_TOKEN;
|
|
3125
|
+
const endpointOverridden = endpointOverride !== void 0;
|
|
3126
|
+
const tokenOverridden = tokenOverride !== void 0;
|
|
3127
|
+
const foreign = record !== null && endpointOverride !== void 0 && !sameEndpoint(resolveEndpoint(endpointOverride), record.endpoint);
|
|
3128
|
+
const stored = foreign ? null : record;
|
|
3129
|
+
const rawEndpoint = endpointOverride ?? stored?.endpoint;
|
|
3130
|
+
const jobToken = tokenOverride ?? stored?.jobToken;
|
|
3131
|
+
if (!stored && rawEndpoint === void 0 && jobToken === void 0) {
|
|
3140
3132
|
throw new DvmError(
|
|
3141
|
-
"
|
|
3142
|
-
`
|
|
3143
|
-
"Pass
|
|
3133
|
+
"job_access_required",
|
|
3134
|
+
`Job ${jobId} is not in the local store, and no portable job access was supplied.`,
|
|
3135
|
+
"Pass --endpoint <url> and --job-token <hex>, or set DVM_JOB_ENDPOINT and DVM_JOB_TOKEN."
|
|
3144
3136
|
);
|
|
3145
3137
|
}
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
|
|
3138
|
+
if (rawEndpoint === void 0) {
|
|
3139
|
+
throw new DvmError(
|
|
3140
|
+
"job_endpoint_required",
|
|
3141
|
+
`No provider endpoint is available for job ${jobId}.`,
|
|
3142
|
+
"Pass --endpoint <url> or set DVM_JOB_ENDPOINT."
|
|
3143
|
+
);
|
|
3144
|
+
}
|
|
3145
|
+
if (foreign && jobToken === void 0) {
|
|
3146
|
+
throw foreignJobTokenRequired(jobId, record.endpoint, resolveEndpoint(endpointOverride));
|
|
3147
|
+
}
|
|
3148
|
+
if (!stored && jobToken === void 0) {
|
|
3149
|
+
throw new DvmError(
|
|
3150
|
+
"job_token_required",
|
|
3151
|
+
`No job token is available for job ${jobId}.`,
|
|
3152
|
+
"Pass --job-token <hex> or set DVM_JOB_TOKEN."
|
|
3153
|
+
);
|
|
3154
|
+
}
|
|
3155
|
+
if (tokenOverridden && !isJobToken(jobToken)) {
|
|
3156
|
+
throw new DvmError(
|
|
3157
|
+
"invalid_job_token",
|
|
3158
|
+
"The supplied job token is not a 64-character hexadecimal value.",
|
|
3159
|
+
"Copy the job_token returned when the job was submitted; the value is never printed by this command."
|
|
3160
|
+
);
|
|
3161
|
+
}
|
|
3162
|
+
return {
|
|
3163
|
+
stored,
|
|
3164
|
+
ref: { endpoint: validateProviderEndpoint(resolveEndpoint(rawEndpoint)) },
|
|
3165
|
+
...jobToken !== void 0 ? { jobToken } : {},
|
|
3166
|
+
overridden: endpointOverridden || tokenOverridden,
|
|
3167
|
+
endpointOverridden
|
|
3168
|
+
};
|
|
3150
3169
|
}
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3158
|
-
|
|
3159
|
-
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
3160
|
-
return DEFAULT_INFLIGHT_PROOF_TIMEOUT_SEC;
|
|
3170
|
+
function resolveStoredJobAccess(jobId, opts) {
|
|
3171
|
+
const stored = loadJob(jobId);
|
|
3172
|
+
if (!stored || hasPendingAcceptedJobAccess(jobId, stored.endpoint)) {
|
|
3173
|
+
throw new DvmError(
|
|
3174
|
+
"job_payment_state_required",
|
|
3175
|
+
`Cannot pay job ${jobId} without its local payment state.`,
|
|
3176
|
+
"Inspect with 'dvm status <job_id> --messages', retaining your endpoint options. Fold recovery records and restore unambiguous local payment state before paying; portable access alone cannot establish it."
|
|
3177
|
+
);
|
|
3161
3178
|
}
|
|
3162
|
-
return
|
|
3179
|
+
return { ...resolveJobAccessWithRecord(jobId, opts, stored), stored };
|
|
3163
3180
|
}
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
const parsed = Number(raw);
|
|
3170
|
-
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
3171
|
-
return DEFAULT_MELT_INFLIGHT_TIMEOUT_SEC;
|
|
3181
|
+
async function withJobTokenRedaction(jobToken, action) {
|
|
3182
|
+
try {
|
|
3183
|
+
return await action();
|
|
3184
|
+
} catch (err) {
|
|
3185
|
+
throw redactJobTokenFromError(err, jobToken);
|
|
3172
3186
|
}
|
|
3173
|
-
return parsed;
|
|
3174
3187
|
}
|
|
3175
|
-
function
|
|
3176
|
-
return
|
|
3188
|
+
function redactJobTokenFromError(err, jobToken) {
|
|
3189
|
+
if (!jobToken || !(err instanceof DvmError)) return err;
|
|
3190
|
+
const redact = (value) => value.replaceAll(jobToken, "[REDACTED]");
|
|
3191
|
+
return new DvmError(
|
|
3192
|
+
redact(err.code),
|
|
3193
|
+
redact(err.message),
|
|
3194
|
+
err.hint === void 0 ? void 0 : redact(err.hint),
|
|
3195
|
+
err.data === void 0 ? void 0 : redactRecord(err.data, redact),
|
|
3196
|
+
err.display === void 0 ? void 0 : redact(err.display),
|
|
3197
|
+
err.proseSources
|
|
3198
|
+
);
|
|
3177
3199
|
}
|
|
3178
|
-
function
|
|
3179
|
-
const
|
|
3180
|
-
|
|
3200
|
+
function foreignJobTokenRequired(jobId, localEndpoint, endpoint) {
|
|
3201
|
+
const row = evidenceRowWithToken(jobId, endpoint);
|
|
3202
|
+
return new DvmError(
|
|
3203
|
+
"job_token_required",
|
|
3204
|
+
`Local job ${jobId} belongs to ${localEndpoint}. Its job token was issued there and is not sent to ${endpoint}.`,
|
|
3205
|
+
row ? `The job token for ${jobId} at ${endpoint} is job_token_bearer_secret on evidence row ${row} in 'dvm wallet submissions'. Pass it with --job-token or DVM_JOB_TOKEN.` : `Pass the job token ${endpoint} issued for ${jobId} with --job-token or DVM_JOB_TOKEN. No evidence row in 'dvm wallet submissions' holds one for it.`,
|
|
3206
|
+
{
|
|
3207
|
+
job_id: jobId,
|
|
3208
|
+
local_endpoint: localEndpoint,
|
|
3209
|
+
endpoint,
|
|
3210
|
+
...row ? { ambiguity_id: row } : {}
|
|
3211
|
+
}
|
|
3181
3212
|
);
|
|
3182
|
-
return { ...wallet, proofs: next };
|
|
3183
3213
|
}
|
|
3184
|
-
function
|
|
3185
|
-
|
|
3186
|
-
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
return
|
|
3190
|
-
}
|
|
3191
|
-
return
|
|
3214
|
+
function evidenceRowWithToken(jobId, endpoint) {
|
|
3215
|
+
let records;
|
|
3216
|
+
try {
|
|
3217
|
+
({ records } = listSubmissionEvidence());
|
|
3218
|
+
} catch {
|
|
3219
|
+
return void 0;
|
|
3220
|
+
}
|
|
3221
|
+
return records.filter(
|
|
3222
|
+
(record) => record.job_token !== void 0 && sameEndpoint(record.endpoint, endpoint) && [record.header_job_id, record.body_job_id, record.accepted_job_id].includes(jobId)
|
|
3223
|
+
).at(-1)?.ambiguity_id;
|
|
3192
3224
|
}
|
|
3193
|
-
function
|
|
3194
|
-
|
|
3195
|
-
|
|
3196
|
-
|
|
3197
|
-
|
|
3198
|
-
|
|
3199
|
-
|
|
3200
|
-
|
|
3225
|
+
function isJobToken(value) {
|
|
3226
|
+
return value !== void 0 && /^[0-9a-fA-F]{64}$/.test(value);
|
|
3227
|
+
}
|
|
3228
|
+
function validateProviderEndpoint(value) {
|
|
3229
|
+
try {
|
|
3230
|
+
const url = new URL(value);
|
|
3231
|
+
if ((url.protocol === "http:" || url.protocol === "https:") && url.hostname) return value;
|
|
3232
|
+
} catch {
|
|
3233
|
+
}
|
|
3234
|
+
throw new DvmError(
|
|
3235
|
+
"invalid_endpoint",
|
|
3236
|
+
"The supplied job endpoint is not a valid HTTP(S) provider URL.",
|
|
3237
|
+
"Pass a full URL such as https://provider.example, or a favorite alias such as @provider."
|
|
3201
3238
|
);
|
|
3202
|
-
|
|
3203
|
-
|
|
3204
|
-
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3239
|
+
}
|
|
3240
|
+
function redactRecord(record, redact) {
|
|
3241
|
+
return Object.fromEntries(
|
|
3242
|
+
Object.entries(record).map(([key, value]) => [key, redactValue(value, redact)])
|
|
3243
|
+
);
|
|
3244
|
+
}
|
|
3245
|
+
function redactValue(value, redact) {
|
|
3246
|
+
if (typeof value === "string") return redact(value);
|
|
3247
|
+
if (Array.isArray(value)) return value.map((entry) => redactValue(entry, redact));
|
|
3248
|
+
if (value && typeof value === "object") {
|
|
3249
|
+
return redactRecord(value, redact);
|
|
3250
|
+
}
|
|
3251
|
+
return value;
|
|
3213
3252
|
}
|
|
3214
3253
|
|
|
3215
|
-
// src/lib/
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
var PERCALL_LOCKTIME_ENV = "DVM_PERCALL_LOCKTIME_SEC";
|
|
3219
|
-
function perCallLocktimeSeconds(minLocktimeSeconds) {
|
|
3220
|
-
const raw = process.env[PERCALL_LOCKTIME_ENV];
|
|
3221
|
-
const parsed = raw ? Number(raw) : NaN;
|
|
3222
|
-
const base = Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : DEFAULT_PERCALL_LOCKTIME_SECONDS;
|
|
3223
|
-
const floor = typeof minLocktimeSeconds === "number" && Number.isFinite(minLocktimeSeconds) ? Math.max(0, Math.floor(minLocktimeSeconds)) : 0;
|
|
3224
|
-
return Math.max(base, floor);
|
|
3254
|
+
// src/lib/draw-funding.ts
|
|
3255
|
+
function isImplicitCreditId(creditId) {
|
|
3256
|
+
return creditId.startsWith("imp:");
|
|
3225
3257
|
}
|
|
3226
|
-
var
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
|
|
3230
|
-
|
|
3258
|
+
var MISMATCH_FIELDS = {
|
|
3259
|
+
credit_id_mismatch: "credit_id",
|
|
3260
|
+
job_id_mismatch: "job_id",
|
|
3261
|
+
draw_id_mismatch: "draw_id",
|
|
3262
|
+
fund_id_mismatch: "fund_id",
|
|
3263
|
+
caller_pubkey_mismatch: "caller_pubkey"
|
|
3231
3264
|
};
|
|
3232
|
-
function
|
|
3233
|
-
|
|
3234
|
-
const match = /^(\d+)([smhd])$/.exec(trimmed);
|
|
3235
|
-
if (!match) {
|
|
3236
|
-
throw new DvmError(
|
|
3237
|
-
"invalid_locktime",
|
|
3238
|
-
`Could not parse "${raw}" as a locktime.`,
|
|
3239
|
-
"Pass a positive integer followed by `s`, `m`, `h`, or `d` \u2014 e.g. `30d`, `12h`, `90m`."
|
|
3240
|
-
);
|
|
3241
|
-
}
|
|
3242
|
-
const n = Number(match[1]);
|
|
3243
|
-
if (!Number.isFinite(n) || n <= 0) {
|
|
3244
|
-
throw new DvmError(
|
|
3245
|
-
"invalid_locktime",
|
|
3246
|
-
`Locktime must be a positive number; got "${raw}".`,
|
|
3247
|
-
"Pass a positive integer followed by `s`, `m`, `h`, or `d` \u2014 e.g. `30d`, `12h`, `90m`."
|
|
3248
|
-
);
|
|
3249
|
-
}
|
|
3250
|
-
const suffix = match[2];
|
|
3251
|
-
const seconds = n * SUFFIXES[suffix];
|
|
3252
|
-
return seconds;
|
|
3265
|
+
function nextAction(job) {
|
|
3266
|
+
return `Nothing is owed or lost: the job's terminal receipt still decides the charge. Refresh your credit balances with \`dvm credit balance ${shellQuoteArg(job.endpoint)}\` once the job ends; if this repeats, report job ${JSON.stringify(job.id)} and the reason to the provider.`;
|
|
3253
3267
|
}
|
|
3254
|
-
function
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
if (seconds % SUFFIXES.m === 0) return `${seconds / SUFFIXES.m}m`;
|
|
3259
|
-
return `${seconds}s`;
|
|
3268
|
+
function invalidFunding(job, receipt, reason, expected) {
|
|
3269
|
+
const field = MISMATCH_FIELDS[reason];
|
|
3270
|
+
const detail = field ? `The provider signed ${field} ${JSON.stringify(String(receipt[field]))}; this job expects ${JSON.stringify(expected[field])}.` : "The provider's funding evidence failed verification.";
|
|
3271
|
+
return { kind: "invalid", reason, hint: `${detail} ${nextAction(job)}` };
|
|
3260
3272
|
}
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
|
|
3264
|
-
|
|
3273
|
+
function verdictReason(verdict) {
|
|
3274
|
+
if (verdict.status === "verified" || verdict.status === "verified_unattested") return void 0;
|
|
3275
|
+
return (verdict.status === "invalid" ? verdict.reason : void 0) ?? verdict.status;
|
|
3276
|
+
}
|
|
3277
|
+
function checkFunding(job, receipt, fundId) {
|
|
3278
|
+
if (!isDrawFundingReceipt(receipt)) return { kind: "not_applicable" };
|
|
3279
|
+
const binding = job.creditBinding;
|
|
3280
|
+
if (!binding || "unbound" in binding) {
|
|
3281
|
+
if (isImplicitCreditId(receipt.credit_id)) {
|
|
3282
|
+
const expected2 = { job_id: job.id, ...fundId ? { fund_id: fundId } : {} };
|
|
3283
|
+
const reason2 = verdictReason(verifyDrawFundingReceiptChain({
|
|
3284
|
+
receipt,
|
|
3285
|
+
builder: job.builderAnchor,
|
|
3286
|
+
expectedJobId: job.id,
|
|
3287
|
+
...fundId ? { expectedFundId: fundId } : {}
|
|
3288
|
+
}));
|
|
3289
|
+
return reason2 ? invalidFunding(job, receipt, reason2, expected2) : { kind: "not_applicable" };
|
|
3290
|
+
}
|
|
3265
3291
|
return {
|
|
3266
|
-
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
hint: "Pass --max-cashu-principal-sats with a value such as 20 or 100."
|
|
3270
|
-
}
|
|
3292
|
+
kind: "invalid",
|
|
3293
|
+
reason: "no_bound_draw",
|
|
3294
|
+
hint: `The provider signed funding for credit ${JSON.stringify(receipt.credit_id)}, but this job records no draw on it, so the local balance of that credit was not reconciled. ${nextAction(job)}`
|
|
3271
3295
|
};
|
|
3272
3296
|
}
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3297
|
+
const expected = {
|
|
3298
|
+
job_id: job.id,
|
|
3299
|
+
credit_id: binding.creditId,
|
|
3300
|
+
draw_id: binding.drawId,
|
|
3301
|
+
caller_pubkey: binding.callerPubkey,
|
|
3302
|
+
...fundId ? { fund_id: fundId } : {}
|
|
3303
|
+
};
|
|
3304
|
+
const reason = verdictReason(verifyDrawFundingReceiptChain({
|
|
3305
|
+
receipt,
|
|
3306
|
+
builder: job.builderAnchor,
|
|
3307
|
+
expectedJobId: job.id,
|
|
3308
|
+
expectedCreditId: binding.creditId,
|
|
3309
|
+
expectedDrawId: binding.drawId,
|
|
3310
|
+
expectedCallerPubkey: binding.callerPubkey,
|
|
3311
|
+
...fundId ? { expectedFundId: fundId } : {}
|
|
3312
|
+
}));
|
|
3313
|
+
return reason ? invalidFunding(job, receipt, reason, expected) : { kind: "verified", receipt };
|
|
3314
|
+
}
|
|
3315
|
+
function verifiedFunding(job, receipt) {
|
|
3316
|
+
const check = checkFunding(job, receipt);
|
|
3317
|
+
return check.kind === "verified" ? check.receipt : void 0;
|
|
3318
|
+
}
|
|
3319
|
+
function captureDrawFundingReceipts(jobId, receipts, opts) {
|
|
3320
|
+
if (!receipts?.length || !loadJob(jobId)) return;
|
|
3321
|
+
try {
|
|
3322
|
+
mutateCreditPayment(jobId, (job) => {
|
|
3323
|
+
if (opts?.endpoint && !sameEndpoint(job.endpoint, opts.endpoint)) return;
|
|
3324
|
+
for (const raw of receipts) {
|
|
3325
|
+
const check = checkFunding(job, raw, opts?.fundId);
|
|
3326
|
+
if (check.kind === "not_applicable") continue;
|
|
3327
|
+
if (check.kind === "invalid") {
|
|
3328
|
+
const display = `mid-job funding evidence did not verify (${check.reason}); credit comparisons remain unchanged. Hint: ${check.hint}`;
|
|
3329
|
+
const added = addOutputWarnings([{ code: "draw_funding_unverified", job_id: job.id, reason: check.reason, hint: check.hint, display }]);
|
|
3330
|
+
if (added.length) info(`Warning: ${display}`);
|
|
3331
|
+
continue;
|
|
3332
|
+
}
|
|
3333
|
+
const { receipt } = check;
|
|
3334
|
+
const held = (Array.isArray(job.drawFundingReceipts) ? job.drawFundingReceipts : []).filter((entry) => verifiedFunding(job, entry) !== void 0);
|
|
3335
|
+
if (!held.some((entry) => entry.fund_id === receipt.fund_id)) {
|
|
3336
|
+
held.push(receipt);
|
|
3337
|
+
job.drawFundingReceipts = held;
|
|
3338
|
+
}
|
|
3282
3339
|
}
|
|
3283
|
-
};
|
|
3340
|
+
}, true);
|
|
3341
|
+
} catch (error) {
|
|
3342
|
+
info(`Warning: could not store mid-job funding evidence: ${error instanceof Error ? error.message : String(error)}`);
|
|
3284
3343
|
}
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
3290
|
-
|
|
3291
|
-
|
|
3292
|
-
|
|
3293
|
-
|
|
3294
|
-
|
|
3295
|
-
|
|
3296
|
-
|
|
3297
|
-
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
|
|
3344
|
+
}
|
|
3345
|
+
function jobDrawFundings(jobId, endpoint, callerPubkey, credit) {
|
|
3346
|
+
const job = loadJob(jobId);
|
|
3347
|
+
const binding = job?.creditBinding;
|
|
3348
|
+
if (!job || !sameEndpoint(job.endpoint, endpoint) || !binding || "unbound" in binding || binding.callerPubkey !== callerPubkey || binding.creditId !== credit.credit_id || binding.drawId !== credit.draw_id) return [];
|
|
3349
|
+
return (Array.isArray(job.drawFundingReceipts) ? job.drawFundingReceipts : []).filter((receipt) => verifiedFunding(job, receipt) !== void 0).map((receipt) => ({ receipt, builder: job.builderAnchor }));
|
|
3350
|
+
}
|
|
3351
|
+
|
|
3352
|
+
// src/lib/messages/store.ts
|
|
3353
|
+
import {
|
|
3354
|
+
appendFileSync,
|
|
3355
|
+
closeSync as closeSync5,
|
|
3356
|
+
existsSync as existsSync4,
|
|
3357
|
+
openSync as openSync5,
|
|
3358
|
+
readFileSync as readFileSync5,
|
|
3359
|
+
readSync,
|
|
3360
|
+
statSync as statSync2
|
|
3361
|
+
} from "fs";
|
|
3362
|
+
import { join as join3 } from "path";
|
|
3363
|
+
var CHECKPOINT_BYTES = 64;
|
|
3364
|
+
function appendMessages(jobId, messages) {
|
|
3365
|
+
if (messages.length === 0) return;
|
|
3366
|
+
createMessageAppendSession(jobId).append(messages);
|
|
3367
|
+
}
|
|
3368
|
+
function createMessageAppendSession(jobId) {
|
|
3369
|
+
return new FileMessageAppendSession(messageFilePath(jobId));
|
|
3370
|
+
}
|
|
3371
|
+
var FileMessageAppendSession = class {
|
|
3372
|
+
constructor(filePath) {
|
|
3373
|
+
this.filePath = filePath;
|
|
3374
|
+
this.syncFromDisk();
|
|
3301
3375
|
}
|
|
3302
|
-
|
|
3303
|
-
|
|
3304
|
-
|
|
3305
|
-
|
|
3306
|
-
|
|
3307
|
-
|
|
3308
|
-
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
|
|
3376
|
+
filePath;
|
|
3377
|
+
seqs = /* @__PURE__ */ new Set();
|
|
3378
|
+
identity;
|
|
3379
|
+
offset = 0;
|
|
3380
|
+
pending = Buffer.alloc(0);
|
|
3381
|
+
checkpoint = Buffer.alloc(0);
|
|
3382
|
+
modifiedAt = 0;
|
|
3383
|
+
append(messages) {
|
|
3384
|
+
if (messages.length === 0) return;
|
|
3385
|
+
this.syncFromDisk();
|
|
3386
|
+
const selectedSeqs = new Set(this.seqs);
|
|
3387
|
+
const newMessages = messages.filter((message) => {
|
|
3388
|
+
if (selectedSeqs.has(message.seq)) return false;
|
|
3389
|
+
selectedSeqs.add(message.seq);
|
|
3390
|
+
return true;
|
|
3391
|
+
});
|
|
3392
|
+
if (newMessages.length === 0) return;
|
|
3393
|
+
ensureConfigSubdir(MESSAGES_DIR);
|
|
3394
|
+
const lines = newMessages.map((message) => JSON.stringify(message)).join("\n") + "\n";
|
|
3395
|
+
appendFileSync(this.filePath, lines);
|
|
3396
|
+
this.syncFromDisk();
|
|
3397
|
+
}
|
|
3398
|
+
syncFromDisk() {
|
|
3399
|
+
const snapshot = statFile(this.filePath);
|
|
3400
|
+
if (!snapshot) {
|
|
3401
|
+
this.reset();
|
|
3402
|
+
return;
|
|
3319
3403
|
}
|
|
3320
|
-
|
|
3321
|
-
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
|
|
3325
|
-
|
|
3326
|
-
}
|
|
3327
|
-
};
|
|
3404
|
+
const identity = fileIdentity(snapshot);
|
|
3405
|
+
const changedFile = !this.identity || !sameIdentity(this.identity, identity);
|
|
3406
|
+
const shrank = snapshot.size < this.offset;
|
|
3407
|
+
const changedSinceRead = snapshot.size !== this.offset || Math.max(snapshot.mtimeMs, snapshot.ctimeMs) !== this.modifiedAt;
|
|
3408
|
+
if (changedFile || shrank || changedSinceRead && !this.checkpointMatches()) {
|
|
3409
|
+
this.reset(identity);
|
|
3328
3410
|
}
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
|
|
3411
|
+
this.identity = identity;
|
|
3412
|
+
this.modifiedAt = Math.max(snapshot.mtimeMs, snapshot.ctimeMs);
|
|
3413
|
+
if (snapshot.size <= this.offset) return;
|
|
3414
|
+
const bytes = readRange(this.filePath, this.offset, snapshot.size);
|
|
3415
|
+
this.offset += bytes.byteLength;
|
|
3416
|
+
this.consume(bytes);
|
|
3417
|
+
this.checkpoint = trailingBytes(this.checkpoint, bytes, CHECKPOINT_BYTES);
|
|
3418
|
+
}
|
|
3419
|
+
checkpointMatches() {
|
|
3420
|
+
if (this.checkpoint.length === 0 || this.offset < this.checkpoint.length) return true;
|
|
3421
|
+
const actual = readRange(
|
|
3422
|
+
this.filePath,
|
|
3423
|
+
this.offset - this.checkpoint.length,
|
|
3424
|
+
this.offset
|
|
3425
|
+
);
|
|
3426
|
+
return actual.equals(this.checkpoint);
|
|
3427
|
+
}
|
|
3428
|
+
consume(bytes) {
|
|
3429
|
+
const combined = Buffer.concat([this.pending, bytes]);
|
|
3430
|
+
const finalNewline = combined.lastIndexOf(10);
|
|
3431
|
+
if (finalNewline === -1) {
|
|
3432
|
+
this.pending = combined;
|
|
3433
|
+
this.parseLine(this.pending);
|
|
3434
|
+
return;
|
|
3332
3435
|
}
|
|
3333
|
-
const
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
cashu_token: reserveToken,
|
|
3369
|
-
...reserveContext ? { context: reserveContext } : {}
|
|
3370
|
-
};
|
|
3371
|
-
const marked = markProofsInFlight(swept.wallet, proofKeys, untilMs);
|
|
3372
|
-
saveAgentWallet({
|
|
3373
|
-
...marked,
|
|
3374
|
-
pending_submissions: [...marked.pending_submissions, submission]
|
|
3375
|
-
});
|
|
3376
|
-
return {
|
|
3377
|
-
kind: "reserve",
|
|
3378
|
-
inner: {
|
|
3379
|
-
lockPrivkey: initial.lock_privkey,
|
|
3380
|
-
lockPubkey: initial.lock_pubkey,
|
|
3381
|
-
selectedProofs: reserveSelection.selected,
|
|
3382
|
-
selectedKeys: proofKeys,
|
|
3383
|
-
mint: reserveSelection.mint,
|
|
3384
|
-
requestId: requestId2,
|
|
3385
|
-
submission,
|
|
3386
|
-
fromReserve: true
|
|
3387
|
-
}
|
|
3388
|
-
};
|
|
3436
|
+
const complete = combined.subarray(0, finalNewline).toString("utf8");
|
|
3437
|
+
for (const line of complete.split("\n")) this.parseLine(line);
|
|
3438
|
+
this.pending = combined.subarray(finalNewline + 1);
|
|
3439
|
+
this.parseLine(this.pending);
|
|
3440
|
+
}
|
|
3441
|
+
parseLine(line) {
|
|
3442
|
+
const text = line.toString().trim();
|
|
3443
|
+
if (!text) return;
|
|
3444
|
+
try {
|
|
3445
|
+
const message = JSON.parse(text);
|
|
3446
|
+
this.seqs.add(message.seq);
|
|
3447
|
+
} catch {
|
|
3448
|
+
}
|
|
3449
|
+
}
|
|
3450
|
+
reset(identity) {
|
|
3451
|
+
this.seqs.clear();
|
|
3452
|
+
this.identity = identity;
|
|
3453
|
+
this.offset = 0;
|
|
3454
|
+
this.pending = Buffer.alloc(0);
|
|
3455
|
+
this.checkpoint = Buffer.alloc(0);
|
|
3456
|
+
this.modifiedAt = 0;
|
|
3457
|
+
}
|
|
3458
|
+
};
|
|
3459
|
+
function loadMessages(jobId, after) {
|
|
3460
|
+
const filePath = messageFilePath(jobId);
|
|
3461
|
+
if (!existsSync4(filePath)) return [];
|
|
3462
|
+
const content = readFileSync5(filePath, "utf-8").trim();
|
|
3463
|
+
if (!content) return [];
|
|
3464
|
+
const messages = [];
|
|
3465
|
+
for (const line of content.split("\n")) {
|
|
3466
|
+
if (!line.trim()) continue;
|
|
3467
|
+
try {
|
|
3468
|
+
const msg = JSON.parse(line);
|
|
3469
|
+
if (after === void 0 || msg.seq > after) {
|
|
3470
|
+
messages.push(msg);
|
|
3389
3471
|
}
|
|
3472
|
+
} catch {
|
|
3390
3473
|
}
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3474
|
+
}
|
|
3475
|
+
return messages;
|
|
3476
|
+
}
|
|
3477
|
+
function messageFilePath(jobId) {
|
|
3478
|
+
return join3(MESSAGES_DIR, `${jobId}.jsonl`);
|
|
3479
|
+
}
|
|
3480
|
+
function statFile(filePath) {
|
|
3481
|
+
try {
|
|
3482
|
+
return statSync2(filePath);
|
|
3483
|
+
} catch (error) {
|
|
3484
|
+
if (error.code === "ENOENT") return void 0;
|
|
3485
|
+
throw error;
|
|
3486
|
+
}
|
|
3487
|
+
}
|
|
3488
|
+
function fileIdentity(stats) {
|
|
3489
|
+
return { dev: stats.dev, ino: stats.ino };
|
|
3490
|
+
}
|
|
3491
|
+
function sameIdentity(left, right) {
|
|
3492
|
+
return left.dev === right.dev && left.ino === right.ino;
|
|
3493
|
+
}
|
|
3494
|
+
function readRange(filePath, start, end) {
|
|
3495
|
+
const expected = Math.max(0, end - start);
|
|
3496
|
+
const buffer = Buffer.allocUnsafe(expected);
|
|
3497
|
+
const fd = openSync5(filePath, "r");
|
|
3498
|
+
let total = 0;
|
|
3499
|
+
try {
|
|
3500
|
+
while (total < expected) {
|
|
3501
|
+
const read = readSync(fd, buffer, total, expected - total, start + total);
|
|
3502
|
+
if (read === 0) break;
|
|
3503
|
+
total += read;
|
|
3399
3504
|
}
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
candidateMints: covering.mints,
|
|
3403
|
-
lockPrivkey: initial.lock_privkey,
|
|
3404
|
-
lockPubkey: initial.lock_pubkey
|
|
3405
|
-
};
|
|
3406
|
-
});
|
|
3407
|
-
if ("error" in lock1) return lock1;
|
|
3408
|
-
if (lock1.kind === "reserve") {
|
|
3409
|
-
const inner2 = lock1.inner;
|
|
3410
|
-
const cashuToken2 = inner2.submission.cashu_token ?? ki({
|
|
3411
|
-
mint: inner2.mint,
|
|
3412
|
-
proofs: toCashuProofs(inner2.selectedProofs)
|
|
3413
|
-
});
|
|
3414
|
-
return {
|
|
3415
|
-
cashuToken: cashuToken2,
|
|
3416
|
-
requestId: inner2.requestId,
|
|
3417
|
-
mint: inner2.mint,
|
|
3418
|
-
totalSats: inner2.submission.amount_sats,
|
|
3419
|
-
endpoint: args.endpoint,
|
|
3420
|
-
intendedLockPubkey: args.cashuP2pk.lock_pubkey,
|
|
3421
|
-
fromReserve: true,
|
|
3422
|
-
...inner2.submission.context?.binding_fingerprint ? { submissionBindingFingerprint: inner2.submission.context.binding_fingerprint } : {}
|
|
3423
|
-
};
|
|
3505
|
+
} finally {
|
|
3506
|
+
closeSync5(fd);
|
|
3424
3507
|
}
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
3428
|
-
|
|
3429
|
-
|
|
3430
|
-
|
|
3431
|
-
|
|
3432
|
-
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3508
|
+
return total === expected ? buffer : buffer.subarray(0, total);
|
|
3509
|
+
}
|
|
3510
|
+
function trailingBytes(previous, next, limit) {
|
|
3511
|
+
if (next.length >= limit) return Buffer.from(next.subarray(next.length - limit));
|
|
3512
|
+
const combined = Buffer.concat([previous, next]);
|
|
3513
|
+
return Buffer.from(combined.subarray(Math.max(0, combined.length - limit)));
|
|
3514
|
+
}
|
|
3515
|
+
|
|
3516
|
+
// src/lib/messages/index.ts
|
|
3517
|
+
function maxSeq(msgs, fallback) {
|
|
3518
|
+
if (msgs.length === 0) return fallback;
|
|
3519
|
+
return Math.max(...msgs.map((m) => m.seq));
|
|
3520
|
+
}
|
|
3521
|
+
|
|
3522
|
+
// src/lib/provider-output.ts
|
|
3523
|
+
function providerFields(value, fields = Object.keys(value)) {
|
|
3524
|
+
return {
|
|
3525
|
+
...value,
|
|
3526
|
+
_provider_fields: [.../* @__PURE__ */ new Set([
|
|
3527
|
+
...Array.isArray(value._provider_fields) ? value._provider_fields : [],
|
|
3528
|
+
...fields.filter((field) => field !== "_provider_fields" && value[field] !== void 0)
|
|
3529
|
+
])]
|
|
3530
|
+
};
|
|
3531
|
+
}
|
|
3532
|
+
function guidanceJobArg(jobId) {
|
|
3533
|
+
return /^[A-Za-z0-9_-]+$/.test(jobId) ? shellQuoteArg(jobId) : "'<job_id>'";
|
|
3534
|
+
}
|
|
3535
|
+
function providerJobJson(data, providerJob = true) {
|
|
3536
|
+
const action = data.next_action;
|
|
3537
|
+
json(providerFields({
|
|
3538
|
+
...data,
|
|
3539
|
+
...providerJob && action && typeof action === "object" ? { next_action: providerFields(action, ["job_id"]) } : {}
|
|
3540
|
+
}, [...providerJob ? ["jobId"] : [], "capability", "identifier"]));
|
|
3541
|
+
}
|
|
3542
|
+
|
|
3543
|
+
// src/lib/wallet-agent/journal-file.ts
|
|
3544
|
+
var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
|
|
3545
|
+
import { closeSync as closeSync6, existsSync as existsSync5, fsyncSync as fsyncSync5, openSync as openSync6, readFileSync as readFileSync6, renameSync as renameSync3, writeFileSync as writeFileSync5 } from "fs";
|
|
3546
|
+
import { dirname as dirname3, join as join4 } from "path";
|
|
3547
|
+
function journalFile(name) {
|
|
3548
|
+
const file = () => join4(dirname3(JOBS_FILE), name);
|
|
3549
|
+
function read() {
|
|
3550
|
+
if (!existsSync5(file())) return [];
|
|
3436
3551
|
try {
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3552
|
+
const parsed = JSON.parse(readFileSync6(file(), "utf8"));
|
|
3553
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
3554
|
+
} catch {
|
|
3555
|
+
return [];
|
|
3556
|
+
}
|
|
3557
|
+
}
|
|
3558
|
+
function withLock(change) {
|
|
3559
|
+
ensureConfigDir();
|
|
3560
|
+
if (!existsSync5(file())) writeFileSync5(file(), "[]\n", { mode: 384, flag: "a" });
|
|
3561
|
+
let release;
|
|
3562
|
+
for (let attempt = 0; !release; attempt++) {
|
|
3563
|
+
try {
|
|
3564
|
+
release = import_proper_lockfile3.default.lockSync(file(), { realpath: false });
|
|
3565
|
+
} catch (error) {
|
|
3566
|
+
if (attempt >= 40) throw error;
|
|
3567
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
|
|
3568
|
+
}
|
|
3441
3569
|
}
|
|
3442
|
-
let reserveSats;
|
|
3443
3570
|
try {
|
|
3444
|
-
|
|
3445
|
-
}
|
|
3446
|
-
|
|
3447
|
-
continue;
|
|
3571
|
+
return change();
|
|
3572
|
+
} finally {
|
|
3573
|
+
release();
|
|
3448
3574
|
}
|
|
3449
|
-
|
|
3450
|
-
|
|
3451
|
-
|
|
3452
|
-
|
|
3453
|
-
|
|
3454
|
-
|
|
3455
|
-
|
|
3456
|
-
}
|
|
3457
|
-
|
|
3458
|
-
const fresh = loadAgentWallet();
|
|
3459
|
-
if (!fresh) {
|
|
3460
|
-
return {
|
|
3461
|
-
error: {
|
|
3462
|
-
code: "no_agent_wallet",
|
|
3463
|
-
message: "Agent wallet vanished between locks.",
|
|
3464
|
-
hint: "Run: dvm wallet init"
|
|
3465
|
-
}
|
|
3466
|
-
};
|
|
3467
|
-
}
|
|
3468
|
-
if (strict) {
|
|
3469
|
-
const pending = strictWalletStateReason(fresh);
|
|
3470
|
-
if (pending) return strictSpendFailure(pending);
|
|
3471
|
-
}
|
|
3472
|
-
const swept = strict ? { wallet: fresh, reverted: 0 } : sweepStaleInFlight(fresh, now());
|
|
3473
|
-
const selection = selectProofsForSpend({
|
|
3474
|
-
proofs: swept.wallet.proofs,
|
|
3475
|
-
mintAllowlist: [mint],
|
|
3476
|
-
amountSats: args.amountSats,
|
|
3477
|
-
swapReserveSats: reserveSats
|
|
3478
|
-
});
|
|
3479
|
-
if ("error" in selection) {
|
|
3480
|
-
if (swept.reverted > 0) saveAgentWallet(swept.wallet);
|
|
3481
|
-
return { error: selection.error };
|
|
3482
|
-
}
|
|
3483
|
-
const selectedFeeSats = reserveSats(selection.selected);
|
|
3484
|
-
if (args.maxCashuFeeSats !== void 0 && selectedFeeSats > args.maxCashuFeeSats) {
|
|
3485
|
-
return {
|
|
3486
|
-
error: {
|
|
3487
|
-
code: "cashu_fee_cap_exceeded",
|
|
3488
|
-
message: `Cashu fees at ${mint} would be ${selectedFeeSats} sats, over the ${args.maxCashuFeeSats}-sat --max-cashu-fee-sats limit.`,
|
|
3489
|
-
hint: "Raise --max-cashu-fee-sats only after approval, or fund an accepted mint with a lower swap fee."
|
|
3490
|
-
}
|
|
3491
|
-
};
|
|
3492
|
-
}
|
|
3493
|
-
const proofKeys = new Set(selection.selected.map((p) => proofKey(p)));
|
|
3494
|
-
const untilMs = now() + timeoutSec * 1e3;
|
|
3495
|
-
const feeContext = contextWithInitialCashuFee(
|
|
3496
|
-
submitContext,
|
|
3497
|
-
args.maxCashuFeeSats,
|
|
3498
|
-
selectedFeeSats
|
|
3499
|
-
);
|
|
3500
|
-
const submission = {
|
|
3501
|
-
endpoint: args.endpoint,
|
|
3502
|
-
request_id: requestId,
|
|
3503
|
-
intended_lock_pubkey: args.cashuP2pk.lock_pubkey,
|
|
3504
|
-
mint: selection.mint,
|
|
3505
|
-
amount_sats: args.amountSats,
|
|
3506
|
-
...args.maxCashuFeeSats !== void 0 ? { max_cashu_fee_sats: args.maxCashuFeeSats } : {},
|
|
3507
|
-
initial_cashu_fee_sats: selectedFeeSats,
|
|
3508
|
-
output_proofs: [],
|
|
3509
|
-
created_at: new Date(now()).toISOString(),
|
|
3510
|
-
...feeContext ? { context: feeContext } : {},
|
|
3511
|
-
...refundClause ? {
|
|
3512
|
-
canonical_id: refundClause.canonicalId,
|
|
3513
|
-
refund_pubkey: refundClause.refundPubkey,
|
|
3514
|
-
t_expire: refundClause.tExpireSec * 1e3
|
|
3515
|
-
} : {}
|
|
3516
|
-
};
|
|
3517
|
-
const marked = markProofsInFlight(swept.wallet, proofKeys, untilMs);
|
|
3518
|
-
saveAgentWallet({
|
|
3519
|
-
...marked,
|
|
3520
|
-
pending_submissions: [...marked.pending_submissions, submission]
|
|
3521
|
-
});
|
|
3522
|
-
return {
|
|
3523
|
-
lockPrivkey: fresh.lock_privkey,
|
|
3524
|
-
lockPubkey: fresh.lock_pubkey,
|
|
3525
|
-
selectedProofs: selection.selected,
|
|
3526
|
-
selectedKeys: proofKeys,
|
|
3527
|
-
mint: selection.mint,
|
|
3528
|
-
requestId,
|
|
3529
|
-
submission,
|
|
3530
|
-
fromReserve: false
|
|
3531
|
-
};
|
|
3532
|
-
});
|
|
3533
|
-
if ("error" in lock2) {
|
|
3534
|
-
if (lock2.error.code === "no_agent_wallet") return lock2;
|
|
3535
|
-
if (lock2.error.code === "cashu_fee_cap_exceeded") {
|
|
3536
|
-
lastFeeCapError = lock2.error;
|
|
3537
|
-
attempts.push({ mint, reason: "fee_cap_exceeded", message: lock2.error.message });
|
|
3538
|
-
continue;
|
|
3539
|
-
}
|
|
3540
|
-
const selectError = lock2.error;
|
|
3541
|
-
lastSelectError = selectError;
|
|
3542
|
-
attempts.push({ mint, reason: selectError.code, message: selectError.message });
|
|
3543
|
-
continue;
|
|
3544
|
-
}
|
|
3545
|
-
const swapBuilder = candidateWallet.ops.send(lock2.submission.amount_sats, toCashuProofs(lock2.selectedProofs)).asP2PK({
|
|
3546
|
-
pubkey: args.cashuP2pk.lock_pubkey,
|
|
3547
|
-
...refundClause ? { locktime: refundClause.tExpireSec, refundKeys: [refundClause.refundPubkey] } : {}
|
|
3548
|
-
}).keepAsP2PK({ pubkey: lock2.lockPubkey }).privkey(lock2.lockPrivkey).includeFees(true);
|
|
3549
|
-
let preview;
|
|
3550
|
-
try {
|
|
3551
|
-
preview = await swapBuilder.prepare();
|
|
3552
|
-
} catch (err) {
|
|
3553
|
-
attempts.push({ mint, reason: "swap_rejected", message: errorText(err) });
|
|
3554
|
-
await rollbackAttempt(requestId, lock2.selectedKeys);
|
|
3555
|
-
if (hasNextCandidate) continue;
|
|
3556
|
-
break;
|
|
3557
|
-
}
|
|
3558
|
-
const initialCashuFeeSats = reserveSats(preview.inputs);
|
|
3559
|
-
const preparedContext = contextWithInitialCashuFee(
|
|
3560
|
-
lock2.submission.context,
|
|
3561
|
-
args.maxCashuFeeSats,
|
|
3562
|
-
initialCashuFeeSats
|
|
3563
|
-
);
|
|
3564
|
-
const preparedSubmission = {
|
|
3565
|
-
...lock2.submission,
|
|
3566
|
-
initial_cashu_fee_sats: initialCashuFeeSats,
|
|
3567
|
-
...preparedContext ? { context: preparedContext } : {}
|
|
3568
|
-
};
|
|
3569
|
-
const inputSecrets = new Set(preview.inputs.map((proof) => proof.secret));
|
|
3570
|
-
const swapping = {
|
|
3571
|
-
keyset_id: preview.keysetId,
|
|
3572
|
-
input_proofs: lock2.selectedProofs.filter((proof) => inputSecrets.has(proof.secret)),
|
|
3573
|
-
unselected_proofs: lock2.selectedProofs.filter((proof) => !inputSecrets.has(proof.secret)),
|
|
3574
|
-
send_outputs: serializeOutputData(preview.sendOutputs ?? []),
|
|
3575
|
-
keep_outputs: serializeOutputData(preview.keepOutputs ?? [])
|
|
3576
|
-
};
|
|
3577
|
-
await withWalletLock(() => {
|
|
3578
|
-
const fresh = loadAgentWallet();
|
|
3579
|
-
if (!fresh) return;
|
|
3580
|
-
saveAgentWallet({
|
|
3581
|
-
...fresh,
|
|
3582
|
-
pending_submissions: fresh.pending_submissions.map(
|
|
3583
|
-
(submission) => submission.request_id === requestId ? {
|
|
3584
|
-
...submission,
|
|
3585
|
-
initial_cashu_fee_sats: initialCashuFeeSats,
|
|
3586
|
-
...preparedContext ? { context: preparedContext } : {},
|
|
3587
|
-
swapping
|
|
3588
|
-
} : submission
|
|
3589
|
-
)
|
|
3590
|
-
});
|
|
3591
|
-
});
|
|
3592
|
-
try {
|
|
3593
|
-
const result = await candidateWallet.completeSwap(preview, lock2.lockPrivkey);
|
|
3594
|
-
inner = { ...lock2, submission: preparedSubmission };
|
|
3595
|
-
sendProofs = result.send;
|
|
3596
|
-
keepProofs = result.keep;
|
|
3597
|
-
break;
|
|
3598
|
-
} catch (err) {
|
|
3599
|
-
attempts.push({ mint, reason: "swap_rejected", message: errorText(err) });
|
|
3600
|
-
if (err instanceof te) {
|
|
3601
|
-
await rollbackAttempt(requestId, lock2.selectedKeys);
|
|
3602
|
-
if (hasNextCandidate) continue;
|
|
3603
|
-
break;
|
|
3604
|
-
}
|
|
3605
|
-
inputsLeftInFlight = true;
|
|
3606
|
-
break;
|
|
3575
|
+
}
|
|
3576
|
+
function write(entries) {
|
|
3577
|
+
const temporary = `${file()}.${process.pid}.tmp`;
|
|
3578
|
+
const fd = openSync6(temporary, "w", 384);
|
|
3579
|
+
try {
|
|
3580
|
+
writeFileSync5(fd, JSON.stringify(entries, null, 2) + "\n");
|
|
3581
|
+
fsyncSync5(fd);
|
|
3582
|
+
} finally {
|
|
3583
|
+
closeSync6(fd);
|
|
3607
3584
|
}
|
|
3585
|
+
renameSync3(temporary, file());
|
|
3608
3586
|
}
|
|
3609
|
-
|
|
3610
|
-
return {
|
|
3611
|
-
error: exhaustedError(attempts, lastSelectError, lastFeeCapError, inputsLeftInFlight)
|
|
3612
|
-
};
|
|
3613
|
-
const cashuToken = ki({ mint: inner.mint, proofs: sendProofs });
|
|
3614
|
-
const boundContext = bindCashuTokenToSubmissionContext(inner.submission.context, cashuToken);
|
|
3615
|
-
const agentOutputs = sendProofs.map(
|
|
3616
|
-
(p) => toAgentProof(p, inner.mint, args.cashuP2pk.lock_pubkey)
|
|
3617
|
-
);
|
|
3618
|
-
const agentKeep = keepProofs.map((p) => toAgentProof(p, inner.mint, inner.lockPubkey));
|
|
3619
|
-
await withWalletLock(() => {
|
|
3620
|
-
const fresh = loadAgentWallet();
|
|
3621
|
-
if (!fresh) return;
|
|
3622
|
-
const next = {
|
|
3623
|
-
...fresh,
|
|
3624
|
-
proofs: [...fresh.proofs.filter((p) => !inner.selectedKeys.has(proofKey(p))), ...agentKeep],
|
|
3625
|
-
pending_submissions: fresh.pending_submissions.map(
|
|
3626
|
-
(s) => s.request_id === inner.requestId ? {
|
|
3627
|
-
...s,
|
|
3628
|
-
output_proofs: agentOutputs,
|
|
3629
|
-
swapping: void 0,
|
|
3630
|
-
cashu_token: cashuToken,
|
|
3631
|
-
...boundContext ? { context: boundContext } : {},
|
|
3632
|
-
// What a later reclaim needs. Only the swap path
|
|
3633
|
-
// writes these: reserve-direct entries ship proofs that still
|
|
3634
|
-
// live in `wallet.proofs[]`, and `release` / the in-flight
|
|
3635
|
-
// revert already own their recovery.
|
|
3636
|
-
...refundClause ? {
|
|
3637
|
-
canonical_id: refundClause.canonicalId,
|
|
3638
|
-
refund_pubkey: refundClause.refundPubkey,
|
|
3639
|
-
t_expire: refundClause.tExpireSec * 1e3
|
|
3640
|
-
} : {}
|
|
3641
|
-
} : s
|
|
3642
|
-
)
|
|
3643
|
-
};
|
|
3644
|
-
saveAgentWallet(next);
|
|
3645
|
-
});
|
|
3646
|
-
return {
|
|
3647
|
-
cashuToken,
|
|
3648
|
-
requestId: inner.requestId,
|
|
3649
|
-
mint: inner.mint,
|
|
3650
|
-
totalSats: inner.submission.amount_sats,
|
|
3651
|
-
endpoint: args.endpoint,
|
|
3652
|
-
intendedLockPubkey: args.cashuP2pk.lock_pubkey,
|
|
3653
|
-
...attempts.length > 0 ? { attempts: successfulSpendAttempts(attempts) } : {},
|
|
3654
|
-
...boundContext?.binding_fingerprint ? { submissionBindingFingerprint: boundContext.binding_fingerprint } : {}
|
|
3655
|
-
};
|
|
3656
|
-
}
|
|
3657
|
-
function successfulSpendAttempts(attempts) {
|
|
3658
|
-
const messages = {
|
|
3659
|
-
unreachable: "Mint could not be loaded.",
|
|
3660
|
-
keys_unavailable: "Mint did not provide an active keyset.",
|
|
3661
|
-
swap_disabled: "Mint advertises swaps switched off (NUT-3 disabled).",
|
|
3662
|
-
fee_cap_exceeded: "Mint swap fee exceeds the approved limit.",
|
|
3663
|
-
insufficient_balance: "Mint balance cannot cover the price and swap fee.",
|
|
3664
|
-
no_eligible_mint: "Mint no longer has eligible proofs for this payment.",
|
|
3665
|
-
swap_rejected: "Mint swap could not be prepared or was definitely refused."
|
|
3666
|
-
};
|
|
3667
|
-
return attempts.map(({ mint, reason }) => {
|
|
3668
|
-
let safeMint;
|
|
3669
|
-
try {
|
|
3670
|
-
new URL(mint);
|
|
3671
|
-
safeMint = redactUrl(mint).replace(/\/$/u, "").slice(0, 2048);
|
|
3672
|
-
} catch {
|
|
3673
|
-
safeMint = "[invalid mint URL]";
|
|
3674
|
-
}
|
|
3675
|
-
return { mint: safeMint, reason, message: messages[reason] };
|
|
3676
|
-
});
|
|
3677
|
-
}
|
|
3678
|
-
function principalCapFailure(principalSats, maxCashuPrincipalSats) {
|
|
3679
|
-
return {
|
|
3680
|
-
error: {
|
|
3681
|
-
code: "cashu_principal_cap_exceeded",
|
|
3682
|
-
message: `Cashu principal of ${principalSats} sats is over the ${maxCashuPrincipalSats}-sat --max-cashu-principal-sats limit.`,
|
|
3683
|
-
hint: "Raise --max-cashu-principal-sats only after approval, or retry when the approved dollar amount needs fewer sats."
|
|
3684
|
-
}
|
|
3685
|
-
};
|
|
3587
|
+
return { read, withLock, write };
|
|
3686
3588
|
}
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
|
|
3691
|
-
|
|
3692
|
-
|
|
3693
|
-
|
|
3589
|
+
|
|
3590
|
+
// src/lib/wallet-keyset-fees.ts
|
|
3591
|
+
var fees = journalFile("wallet-keyset-fees.json");
|
|
3592
|
+
function rememberKeysetFees(mint, wallet) {
|
|
3593
|
+
try {
|
|
3594
|
+
const rows = wallet.keyChain.getKeysets().map((keyset) => ({
|
|
3595
|
+
mint,
|
|
3596
|
+
id: keyset.id,
|
|
3597
|
+
ppk: keyset.fee
|
|
3598
|
+
})).filter((row) => Number.isFinite(row.ppk) && row.ppk >= 0);
|
|
3599
|
+
if (!rows.length) return;
|
|
3600
|
+
fees.withLock(() => fees.write([
|
|
3601
|
+
...fees.read().filter((row) => !rows.some((next) => next.mint === row.mint && next.id === row.id)),
|
|
3602
|
+
...rows
|
|
3603
|
+
]));
|
|
3604
|
+
} catch {
|
|
3605
|
+
}
|
|
3694
3606
|
}
|
|
3695
|
-
function
|
|
3696
|
-
|
|
3697
|
-
|
|
3698
|
-
|
|
3699
|
-
|
|
3700
|
-
|
|
3701
|
-
|
|
3702
|
-
|
|
3703
|
-
|
|
3704
|
-
return strictSpendFailure("Strict Cashu per-call mode requires one matching job context.");
|
|
3705
|
-
return null;
|
|
3607
|
+
function localInputFee(mint, ids) {
|
|
3608
|
+
const rows = fees.read();
|
|
3609
|
+
let ppk = 0;
|
|
3610
|
+
for (const id of ids) {
|
|
3611
|
+
const row = rows.find((entry) => entry.mint === mint && entry.id === id);
|
|
3612
|
+
if (!row || !Number.isFinite(row.ppk) || row.ppk < 0) return void 0;
|
|
3613
|
+
ppk += row.ppk;
|
|
3614
|
+
}
|
|
3615
|
+
return Math.ceil(ppk / 1e3);
|
|
3706
3616
|
}
|
|
3707
|
-
|
|
3708
|
-
|
|
3709
|
-
|
|
3710
|
-
|
|
3711
|
-
|
|
3712
|
-
|
|
3713
|
-
|
|
3714
|
-
|
|
3617
|
+
|
|
3618
|
+
// src/lib/wallet-agent/spend.ts
|
|
3619
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
3620
|
+
|
|
3621
|
+
// src/lib/wallet-agent/builder-handle.ts
|
|
3622
|
+
var BUILDER_RESERVE_PREFIX = "builder/";
|
|
3623
|
+
function extractBuilderHandle(endpoint) {
|
|
3624
|
+
let url;
|
|
3625
|
+
try {
|
|
3626
|
+
url = new URL(endpoint);
|
|
3627
|
+
} catch {
|
|
3628
|
+
throw new DvmError(
|
|
3629
|
+
"invalid_endpoint",
|
|
3630
|
+
`Could not parse "${endpoint}" as a URL.`,
|
|
3631
|
+
"Pass a full HTTPS URL like `https://scrape.dvmkit.ai`, or a favorite alias like `@scrape`."
|
|
3632
|
+
);
|
|
3633
|
+
}
|
|
3634
|
+
return url.hostname.toLowerCase();
|
|
3715
3635
|
}
|
|
3716
|
-
function
|
|
3717
|
-
return {
|
|
3718
|
-
error: {
|
|
3719
|
-
code: "strict_per_call_unsafe",
|
|
3720
|
-
message,
|
|
3721
|
-
hint: "Resolve the existing wallet operation, then rebuild and re-approve the strict request."
|
|
3722
|
-
}
|
|
3723
|
-
};
|
|
3636
|
+
function reservedForMarker(builderHandle) {
|
|
3637
|
+
return `${BUILDER_RESERVE_PREFIX}${builderHandle}`;
|
|
3724
3638
|
}
|
|
3725
|
-
|
|
3726
|
-
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
recent_spends: [...wallet.recent_spends, args.recentSpend].slice(-RECENT_SPENDS_CAP)
|
|
3738
|
-
};
|
|
3739
|
-
saveAgentWallet(next);
|
|
3740
|
-
});
|
|
3639
|
+
|
|
3640
|
+
// src/lib/wallet-agent/inflight.ts
|
|
3641
|
+
var DEFAULT_INFLIGHT_PROOF_TIMEOUT_SEC = 60;
|
|
3642
|
+
var INFLIGHT_TIMEOUT_ENV = "DVM_INFLIGHT_PROOF_TIMEOUT_SEC";
|
|
3643
|
+
function inFlightTimeoutSeconds() {
|
|
3644
|
+
const raw = process.env[INFLIGHT_TIMEOUT_ENV];
|
|
3645
|
+
if (!raw) return DEFAULT_INFLIGHT_PROOF_TIMEOUT_SEC;
|
|
3646
|
+
const parsed = Number(raw);
|
|
3647
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
3648
|
+
return DEFAULT_INFLIGHT_PROOF_TIMEOUT_SEC;
|
|
3649
|
+
}
|
|
3650
|
+
return parsed;
|
|
3741
3651
|
}
|
|
3742
|
-
|
|
3743
|
-
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
3749
|
-
|
|
3750
|
-
|
|
3751
|
-
|
|
3752
|
-
recent_spends: [...wallet.recent_spends, {
|
|
3753
|
-
request_id: requestId,
|
|
3754
|
-
dvm_endpoint: submission.endpoint,
|
|
3755
|
-
mint: submission.mint,
|
|
3756
|
-
amount_sats: submission.amount_sats,
|
|
3757
|
-
signed_at_ms: now()
|
|
3758
|
-
}].slice(-RECENT_SPENDS_CAP)
|
|
3759
|
-
});
|
|
3760
|
-
});
|
|
3652
|
+
var DEFAULT_MELT_INFLIGHT_TIMEOUT_SEC = 900;
|
|
3653
|
+
var MELT_INFLIGHT_TIMEOUT_ENV = "DVM_MELT_INFLIGHT_TIMEOUT_SEC";
|
|
3654
|
+
function meltInFlightTimeoutSeconds() {
|
|
3655
|
+
const raw = process.env[MELT_INFLIGHT_TIMEOUT_ENV];
|
|
3656
|
+
if (!raw) return DEFAULT_MELT_INFLIGHT_TIMEOUT_SEC;
|
|
3657
|
+
const parsed = Number(raw);
|
|
3658
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
3659
|
+
return DEFAULT_MELT_INFLIGHT_TIMEOUT_SEC;
|
|
3660
|
+
}
|
|
3661
|
+
return parsed;
|
|
3761
3662
|
}
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
|
|
3772
|
-
|
|
3773
|
-
|
|
3774
|
-
|
|
3775
|
-
|
|
3776
|
-
|
|
3777
|
-
...s.context,
|
|
3778
|
-
submit_body: {
|
|
3779
|
-
...s.context.submit_body,
|
|
3780
|
-
data: { ...rest, fund: { ...fund, amount_micro: args.amountMicro } }
|
|
3781
|
-
}
|
|
3782
|
-
}
|
|
3783
|
-
};
|
|
3784
|
-
})
|
|
3785
|
-
};
|
|
3786
|
-
saveAgentWallet(next);
|
|
3663
|
+
function proofKey(p) {
|
|
3664
|
+
return `${p.mint}\0${p.secret}`;
|
|
3665
|
+
}
|
|
3666
|
+
function markProofsInFlight(wallet, proofKeys, untilMs) {
|
|
3667
|
+
const next = wallet.proofs.map(
|
|
3668
|
+
(p) => proofKeys.has(proofKey(p)) ? { ...p, status: "in_flight", in_flight_until_ms: untilMs } : p
|
|
3669
|
+
);
|
|
3670
|
+
return { ...wallet, proofs: next };
|
|
3671
|
+
}
|
|
3672
|
+
function revertInFlight(wallet, proofKeys) {
|
|
3673
|
+
const next = wallet.proofs.map((p) => {
|
|
3674
|
+
if (!proofKeys.has(proofKey(p))) return p;
|
|
3675
|
+
if (p.status !== "in_flight") return p;
|
|
3676
|
+
const { in_flight_until_ms: _drop, ...rest } = p;
|
|
3677
|
+
return { ...rest, status: "valid" };
|
|
3787
3678
|
});
|
|
3679
|
+
return { ...wallet, proofs: next };
|
|
3788
3680
|
}
|
|
3789
|
-
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3681
|
+
function sweepStaleInFlight(wallet, nowMs) {
|
|
3682
|
+
const mintCommitted = new Set(
|
|
3683
|
+
[
|
|
3684
|
+
...wallet.pending_melts.flatMap((m) => m.input_proofs),
|
|
3685
|
+
...wallet.pending_submissions.flatMap(
|
|
3686
|
+
(submission) => submission.swapping ? [...submission.swapping.input_proofs, ...submission.swapping.unselected_proofs] : []
|
|
3687
|
+
)
|
|
3688
|
+
].map((proof) => proofKey(proof))
|
|
3689
|
+
);
|
|
3690
|
+
let reverted = 0;
|
|
3691
|
+
const next = wallet.proofs.map((p) => {
|
|
3692
|
+
if (p.status !== "in_flight") return p;
|
|
3693
|
+
if (mintCommitted.has(proofKey(p))) return p;
|
|
3694
|
+
const stale = p.in_flight_until_ms === void 0 || p.in_flight_until_ms < nowMs;
|
|
3695
|
+
if (!stale) return p;
|
|
3696
|
+
reverted += 1;
|
|
3697
|
+
const { in_flight_until_ms: _drop, ...rest } = p;
|
|
3698
|
+
return { ...rest, status: "valid" };
|
|
3794
3699
|
});
|
|
3700
|
+
return { wallet: { ...wallet, proofs: next }, reverted };
|
|
3795
3701
|
}
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
|
|
3801
|
-
|
|
3802
|
-
|
|
3803
|
-
|
|
3804
|
-
|
|
3805
|
-
|
|
3806
|
-
|
|
3807
|
-
(s) => s.request_id === args.requestId ? { ...s, context: void 0 } : s
|
|
3808
|
-
) : wallet.pending_submissions.filter((s) => s.request_id !== args.requestId)
|
|
3809
|
-
};
|
|
3702
|
+
|
|
3703
|
+
// src/lib/wallet-agent/locktime.ts
|
|
3704
|
+
var DEFAULT_RESERVE_LOCKTIME_SECONDS = 30 * 24 * 60 * 60;
|
|
3705
|
+
var DEFAULT_PERCALL_LOCKTIME_SECONDS = 48 * 60 * 60;
|
|
3706
|
+
var PERCALL_LOCKTIME_ENV = "DVM_PERCALL_LOCKTIME_SEC";
|
|
3707
|
+
function perCallLocktimeSeconds(minLocktimeSeconds) {
|
|
3708
|
+
const raw = process.env[PERCALL_LOCKTIME_ENV];
|
|
3709
|
+
const parsed = raw ? Number(raw) : NaN;
|
|
3710
|
+
const base = Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : DEFAULT_PERCALL_LOCKTIME_SECONDS;
|
|
3711
|
+
const floor = typeof minLocktimeSeconds === "number" && Number.isFinite(minLocktimeSeconds) ? Math.max(0, Math.floor(minLocktimeSeconds)) : 0;
|
|
3712
|
+
return Math.max(base, floor);
|
|
3810
3713
|
}
|
|
3811
|
-
|
|
3812
|
-
|
|
3813
|
-
|
|
3814
|
-
|
|
3815
|
-
|
|
3816
|
-
|
|
3817
|
-
|
|
3714
|
+
var SUFFIXES = {
|
|
3715
|
+
s: 1,
|
|
3716
|
+
m: 60,
|
|
3717
|
+
h: 60 * 60,
|
|
3718
|
+
d: 24 * 60 * 60
|
|
3719
|
+
};
|
|
3720
|
+
function parseLocktime(raw) {
|
|
3721
|
+
const trimmed = raw.trim().toLowerCase();
|
|
3722
|
+
const match = /^(\d+)([smhd])$/.exec(trimmed);
|
|
3723
|
+
if (!match) {
|
|
3724
|
+
throw new DvmError(
|
|
3725
|
+
"invalid_locktime",
|
|
3726
|
+
`Could not parse "${raw}" as a locktime.`,
|
|
3727
|
+
"Pass a positive integer followed by `s`, `m`, `h`, or `d` \u2014 e.g. `30d`, `12h`, `90m`."
|
|
3728
|
+
);
|
|
3729
|
+
}
|
|
3730
|
+
const n = Number(match[1]);
|
|
3731
|
+
if (!Number.isFinite(n) || n <= 0) {
|
|
3732
|
+
throw new DvmError(
|
|
3733
|
+
"invalid_locktime",
|
|
3734
|
+
`Locktime must be a positive number; got "${raw}".`,
|
|
3735
|
+
"Pass a positive integer followed by `s`, `m`, `h`, or `d` \u2014 e.g. `30d`, `12h`, `90m`."
|
|
3736
|
+
);
|
|
3737
|
+
}
|
|
3738
|
+
const suffix = match[2];
|
|
3739
|
+
const seconds = n * SUFFIXES[suffix];
|
|
3740
|
+
return seconds;
|
|
3818
3741
|
}
|
|
3819
|
-
function
|
|
3820
|
-
|
|
3821
|
-
if (
|
|
3822
|
-
return {
|
|
3823
|
-
|
|
3824
|
-
|
|
3825
|
-
(s) => s.request_id === requestId ? { ...s, accepted_unresolved: marker } : s
|
|
3826
|
-
)
|
|
3827
|
-
};
|
|
3742
|
+
function formatLocktime(seconds) {
|
|
3743
|
+
if (seconds <= 0) return `${seconds}s`;
|
|
3744
|
+
if (seconds % SUFFIXES.d === 0) return `${seconds / SUFFIXES.d}d`;
|
|
3745
|
+
if (seconds % SUFFIXES.h === 0) return `${seconds / SUFFIXES.h}h`;
|
|
3746
|
+
if (seconds % SUFFIXES.m === 0) return `${seconds / SUFFIXES.m}m`;
|
|
3747
|
+
return `${seconds}s`;
|
|
3828
3748
|
}
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3833
|
-
if (!mnemonic) return null;
|
|
3834
|
-
const locktimeSeconds = Math.max(
|
|
3835
|
-
locktimeSecondsOverride ?? perCallLocktimeSeconds(offer.min_locktime),
|
|
3836
|
-
offer.min_locktime ?? 0
|
|
3837
|
-
);
|
|
3838
|
-
try {
|
|
3749
|
+
|
|
3750
|
+
// src/lib/wallet-agent/spend.ts
|
|
3751
|
+
async function prepareAgentSpend(args) {
|
|
3752
|
+
if (args.maxCashuPrincipalSats !== void 0 && (!Number.isSafeInteger(args.maxCashuPrincipalSats) || args.maxCashuPrincipalSats < 0)) {
|
|
3839
3753
|
return {
|
|
3840
|
-
|
|
3841
|
-
|
|
3842
|
-
|
|
3754
|
+
error: {
|
|
3755
|
+
code: "invalid_max_cashu_principal",
|
|
3756
|
+
message: "The Cashu principal limit must be an exact non-negative integer number of sats.",
|
|
3757
|
+
hint: "Pass --max-cashu-principal-sats with a value such as 20 or 100."
|
|
3758
|
+
}
|
|
3843
3759
|
};
|
|
3844
|
-
} catch {
|
|
3845
|
-
return null;
|
|
3846
3760
|
}
|
|
3847
|
-
|
|
3848
|
-
|
|
3849
|
-
|
|
3850
|
-
|
|
3851
|
-
|
|
3852
|
-
|
|
3853
|
-
|
|
3854
|
-
|
|
3855
|
-
|
|
3761
|
+
if (args.maxCashuPrincipalSats !== void 0 && args.amountSats > args.maxCashuPrincipalSats) {
|
|
3762
|
+
return principalCapFailure(args.amountSats, args.maxCashuPrincipalSats);
|
|
3763
|
+
}
|
|
3764
|
+
if (args.maxCashuFeeSats !== void 0 && (!Number.isSafeInteger(args.maxCashuFeeSats) || args.maxCashuFeeSats < 0)) {
|
|
3765
|
+
return {
|
|
3766
|
+
error: {
|
|
3767
|
+
code: "invalid_max_cashu_fee",
|
|
3768
|
+
message: "The Cashu fee limit must be an exact non-negative integer number of sats.",
|
|
3769
|
+
hint: "Pass --max-cashu-fee-sats with a value such as 1 or 2."
|
|
3770
|
+
}
|
|
3771
|
+
};
|
|
3772
|
+
}
|
|
3773
|
+
const strict = args.mode === "strict_per_call";
|
|
3774
|
+
let submitContext = args.submitContext;
|
|
3775
|
+
if (strict) {
|
|
3776
|
+
const strictError = strictSpendInputError(args);
|
|
3777
|
+
if (strictError) return strictError;
|
|
3778
|
+
if (!submitContext)
|
|
3779
|
+
return strictSpendFailure("The strict Cashu request has no recovery context.");
|
|
3780
|
+
const binding = cashuSubmissionBindingFromContext(submitContext);
|
|
3781
|
+
if (!binding)
|
|
3782
|
+
return strictSpendFailure("The strict Cashu request has no complete recovery binding.");
|
|
3783
|
+
const bindingFingerprint = cashuSubmissionBindingFingerprint(binding);
|
|
3784
|
+
if (submitContext.binding_fingerprint !== bindingFingerprint)
|
|
3785
|
+
return strictSpendFailure(
|
|
3786
|
+
"The strict Cashu request binding does not match its request body."
|
|
3787
|
+
);
|
|
3788
|
+
submitContext = { ...submitContext, binding_fingerprint: bindingFingerprint };
|
|
3789
|
+
}
|
|
3790
|
+
const now = args.now ?? (() => Date.now());
|
|
3791
|
+
const uuid = args.uuid ?? (() => randomUUID3());
|
|
3792
|
+
const timeoutSec = args.inFlightTimeoutSec ?? inFlightTimeoutSeconds();
|
|
3793
|
+
const getWalletForMint = args.getWalletForMint ?? getWallet;
|
|
3794
|
+
const refundClause = resolveRefundClause(args.cashuP2pk, args.locktimeSeconds, now(), {
|
|
3795
|
+
readMnemonic: args.readMnemonic
|
|
3796
|
+
});
|
|
3797
|
+
const lock1 = await withWalletLock(() => {
|
|
3798
|
+
const initial = loadAgentWallet();
|
|
3799
|
+
if (!initial) {
|
|
3800
|
+
return {
|
|
3801
|
+
error: {
|
|
3802
|
+
code: "no_agent_wallet",
|
|
3803
|
+
message: "No agent wallet found at ~/.dvm/wallet.json.",
|
|
3804
|
+
hint: "Run: dvm wallet init"
|
|
3805
|
+
}
|
|
3806
|
+
};
|
|
3807
|
+
}
|
|
3808
|
+
if (!args.cashuP2pk.lock_pubkey) {
|
|
3809
|
+
return {
|
|
3810
|
+
error: {
|
|
3811
|
+
code: "missing_lock_pubkey",
|
|
3812
|
+
message: "DVM did not advertise a lock pubkey.",
|
|
3813
|
+
hint: "Ask the DVM operator to set DVMKIT_CASHU_LOCK_PUBKEY."
|
|
3814
|
+
}
|
|
3815
|
+
};
|
|
3816
|
+
}
|
|
3817
|
+
if (strict) {
|
|
3818
|
+
const pending = strictWalletStateReason(initial);
|
|
3819
|
+
if (pending) return strictSpendFailure(pending);
|
|
3820
|
+
}
|
|
3821
|
+
const swept = strict ? { wallet: initial, reverted: 0 } : sweepStaleInFlight(initial, now());
|
|
3822
|
+
if (!strict && args.builderHandle) {
|
|
3823
|
+
const reserveSelection = selectReserveProofs({
|
|
3824
|
+
proofs: swept.wallet.proofs,
|
|
3825
|
+
builderHandle: args.builderHandle,
|
|
3826
|
+
lockPubkey: args.cashuP2pk.lock_pubkey,
|
|
3827
|
+
mintAllowlist: args.cashuP2pk.mints,
|
|
3828
|
+
nowMs: now(),
|
|
3829
|
+
amountSats: args.amountSats
|
|
3830
|
+
});
|
|
3831
|
+
if (reserveSelection) {
|
|
3832
|
+
if (args.maxCashuPrincipalSats !== void 0 && reserveSelection.totalSats > args.maxCashuPrincipalSats) {
|
|
3833
|
+
return principalCapFailure(reserveSelection.totalSats, args.maxCashuPrincipalSats);
|
|
3834
|
+
}
|
|
3835
|
+
const proofKeys = new Set(reserveSelection.selected.map((p) => proofKey(p)));
|
|
3836
|
+
const untilMs = now() + timeoutSec * 1e3;
|
|
3837
|
+
const requestId2 = uuid();
|
|
3838
|
+
const reserveToken = ki({
|
|
3839
|
+
mint: reserveSelection.mint,
|
|
3840
|
+
proofs: toCashuProofs(reserveSelection.selected)
|
|
3841
|
+
});
|
|
3842
|
+
const reserveContext = bindCashuTokenToSubmissionContext(
|
|
3843
|
+
contextWithInitialCashuFee(submitContext, args.maxCashuFeeSats, 0),
|
|
3844
|
+
reserveToken
|
|
3845
|
+
);
|
|
3846
|
+
const submission = {
|
|
3847
|
+
endpoint: args.endpoint,
|
|
3848
|
+
request_id: requestId2,
|
|
3849
|
+
intended_lock_pubkey: args.cashuP2pk.lock_pubkey,
|
|
3850
|
+
mint: reserveSelection.mint,
|
|
3851
|
+
amount_sats: reserveSelection.totalSats,
|
|
3852
|
+
...args.maxCashuFeeSats !== void 0 ? { max_cashu_fee_sats: args.maxCashuFeeSats } : {},
|
|
3853
|
+
initial_cashu_fee_sats: 0,
|
|
3854
|
+
output_proofs: reserveSelection.selected,
|
|
3855
|
+
created_at: new Date(now()).toISOString(),
|
|
3856
|
+
cashu_token: reserveToken,
|
|
3857
|
+
...reserveContext ? { context: reserveContext } : {}
|
|
3858
|
+
};
|
|
3859
|
+
const marked = markProofsInFlight(swept.wallet, proofKeys, untilMs);
|
|
3860
|
+
saveAgentWallet({
|
|
3861
|
+
...marked,
|
|
3862
|
+
pending_submissions: [...marked.pending_submissions, submission]
|
|
3863
|
+
});
|
|
3864
|
+
return {
|
|
3865
|
+
kind: "reserve",
|
|
3866
|
+
inner: {
|
|
3867
|
+
lockPrivkey: initial.lock_privkey,
|
|
3868
|
+
lockPubkey: initial.lock_pubkey,
|
|
3869
|
+
selectedProofs: reserveSelection.selected,
|
|
3870
|
+
selectedKeys: proofKeys,
|
|
3871
|
+
mint: reserveSelection.mint,
|
|
3872
|
+
requestId: requestId2,
|
|
3873
|
+
submission,
|
|
3874
|
+
fromReserve: true
|
|
3875
|
+
}
|
|
3876
|
+
};
|
|
3877
|
+
}
|
|
3878
|
+
}
|
|
3879
|
+
const covering = coveringMintsForSpend({
|
|
3880
|
+
proofs: swept.wallet.proofs,
|
|
3881
|
+
mintAllowlist: args.cashuP2pk.mints,
|
|
3882
|
+
amountSats: args.amountSats
|
|
3856
3883
|
});
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
3860
|
-
|
|
3861
|
-
return {
|
|
3862
|
-
code: "no_eligible_mint",
|
|
3863
|
-
message: "No mint the DVM accepts could be attempted for this payment.",
|
|
3864
|
-
hint: "Fund the wallet at one of the DVM's accepted mints with: dvm wallet fund <amount>",
|
|
3865
|
-
attempts
|
|
3866
|
-
};
|
|
3867
|
-
}
|
|
3868
|
-
if (lastSelectError && attempts.every((a) => isSelectionReason(a.reason))) {
|
|
3869
|
-
if (attempts.length === 1) return { ...lastSelectError, attempts };
|
|
3884
|
+
if ("error" in covering) {
|
|
3885
|
+
if (swept.reverted > 0) saveAgentWallet(swept.wallet);
|
|
3886
|
+
return { error: covering.error };
|
|
3887
|
+
}
|
|
3870
3888
|
return {
|
|
3871
|
-
|
|
3872
|
-
|
|
3873
|
-
|
|
3874
|
-
|
|
3889
|
+
kind: "swap-candidates",
|
|
3890
|
+
candidateMints: covering.mints,
|
|
3891
|
+
lockPrivkey: initial.lock_privkey,
|
|
3892
|
+
lockPubkey: initial.lock_pubkey
|
|
3875
3893
|
};
|
|
3876
|
-
}
|
|
3877
|
-
if (
|
|
3878
|
-
|
|
3879
|
-
|
|
3880
|
-
|
|
3894
|
+
});
|
|
3895
|
+
if ("error" in lock1) return lock1;
|
|
3896
|
+
if (lock1.kind === "reserve") {
|
|
3897
|
+
const inner2 = lock1.inner;
|
|
3898
|
+
const cashuToken2 = inner2.submission.cashu_token ?? ki({
|
|
3899
|
+
mint: inner2.mint,
|
|
3900
|
+
proofs: toCashuProofs(inner2.selectedProofs)
|
|
3901
|
+
});
|
|
3881
3902
|
return {
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3903
|
+
cashuToken: cashuToken2,
|
|
3904
|
+
requestId: inner2.requestId,
|
|
3905
|
+
mint: inner2.mint,
|
|
3906
|
+
totalSats: inner2.submission.amount_sats,
|
|
3907
|
+
endpoint: args.endpoint,
|
|
3908
|
+
intendedLockPubkey: args.cashuP2pk.lock_pubkey,
|
|
3909
|
+
fromReserve: true,
|
|
3910
|
+
...inner2.submission.context?.binding_fingerprint ? { submissionBindingFingerprint: inner2.submission.context.binding_fingerprint } : {}
|
|
3885
3911
|
};
|
|
3886
3912
|
}
|
|
3887
|
-
const
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
|
|
3896
|
-
|
|
3897
|
-
|
|
3898
|
-
|
|
3899
|
-
|
|
3900
|
-
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
|
|
3904
|
-
try {
|
|
3905
|
-
if (typeof loose.getMintInfo !== "function") return true;
|
|
3906
|
-
nuts = loose.getMintInfo().cache?.nuts;
|
|
3907
|
-
} catch {
|
|
3908
|
-
return true;
|
|
3909
|
-
}
|
|
3910
|
-
if (typeof nuts !== "object" || nuts === null) return true;
|
|
3911
|
-
return canSwap(nuts);
|
|
3912
|
-
}
|
|
3913
|
-
function errorText(err) {
|
|
3914
|
-
return err instanceof Error ? err.message : String(err);
|
|
3915
|
-
}
|
|
3916
|
-
function selectReserveProofs(args) {
|
|
3917
|
-
const marker = reservedForMarker(args.builderHandle);
|
|
3918
|
-
const candidates = args.proofs.filter(
|
|
3919
|
-
(p) => p.reserved_for === marker && args.mintAllowlist.includes(p.mint) && p.locked_to_pubkey === args.lockPubkey && p.status === "valid" && typeof p.t_expire === "number" && p.t_expire > args.nowMs
|
|
3920
|
-
);
|
|
3921
|
-
const byMint = /* @__PURE__ */ new Map();
|
|
3922
|
-
for (const p of candidates) {
|
|
3923
|
-
const bucket = byMint.get(p.mint) ?? [];
|
|
3924
|
-
bucket.push(p);
|
|
3925
|
-
byMint.set(p.mint, bucket);
|
|
3926
|
-
}
|
|
3927
|
-
for (const [mint, mintProofs] of byMint) {
|
|
3928
|
-
const sorted = mintProofs.slice().sort((a, b) => a.amount - b.amount || (a.t_expire ?? 0) - (b.t_expire ?? 0));
|
|
3929
|
-
const subset = minOvershootSubset(sorted, args.amountSats);
|
|
3930
|
-
if (subset) {
|
|
3931
|
-
return { selected: subset.selected, mint, totalSats: subset.totalSats };
|
|
3932
|
-
}
|
|
3933
|
-
}
|
|
3934
|
-
return null;
|
|
3935
|
-
}
|
|
3936
|
-
function minOvershootSubset(proofs, amountSats) {
|
|
3937
|
-
if (proofs.length === 0) return null;
|
|
3938
|
-
const maxProof = proofs.reduce((m, p) => Math.max(m, p.amount), 0);
|
|
3939
|
-
const ceiling = amountSats + maxProof;
|
|
3940
|
-
const reachable = /* @__PURE__ */ new Map();
|
|
3941
|
-
reachable.set(0, []);
|
|
3942
|
-
for (let i = 0; i < proofs.length; i++) {
|
|
3943
|
-
const v = proofs[i].amount;
|
|
3944
|
-
const snapshot = Array.from(reachable.entries());
|
|
3945
|
-
for (const [target, indices2] of snapshot) {
|
|
3946
|
-
const next = target + v;
|
|
3947
|
-
if (next > ceiling) continue;
|
|
3948
|
-
if (reachable.has(next)) continue;
|
|
3949
|
-
reachable.set(next, [...indices2, i]);
|
|
3913
|
+
const requestId = uuid();
|
|
3914
|
+
const attempts = [];
|
|
3915
|
+
let lastSelectError;
|
|
3916
|
+
let lastFeeCapError;
|
|
3917
|
+
let inputsLeftInFlight = false;
|
|
3918
|
+
let inner;
|
|
3919
|
+
let sendProofs = [];
|
|
3920
|
+
let keepProofs = [];
|
|
3921
|
+
for (const [index, mint] of lock1.candidateMints.entries()) {
|
|
3922
|
+
const hasNextCandidate = index < lock1.candidateMints.length - 1;
|
|
3923
|
+
let candidateWallet;
|
|
3924
|
+
try {
|
|
3925
|
+
candidateWallet = await getWalletForMint(mint);
|
|
3926
|
+
rememberKeysetFees(mint, candidateWallet);
|
|
3927
|
+
} catch (err) {
|
|
3928
|
+
attempts.push({ mint, reason: "unreachable", message: errorText(err) });
|
|
3929
|
+
continue;
|
|
3950
3930
|
}
|
|
3951
|
-
|
|
3952
|
-
let bestTarget = -1;
|
|
3953
|
-
for (const t of reachable.keys()) {
|
|
3954
|
-
if (t >= amountSats && (bestTarget === -1 || t < bestTarget)) bestTarget = t;
|
|
3955
|
-
}
|
|
3956
|
-
if (bestTarget === -1) return null;
|
|
3957
|
-
const indices = reachable.get(bestTarget) ?? [];
|
|
3958
|
-
return { selected: indices.map((i) => proofs[i]), totalSats: bestTarget };
|
|
3959
|
-
}
|
|
3960
|
-
|
|
3961
|
-
// src/lib/taken-payment.ts
|
|
3962
|
-
function midJobSpendLabel(reason) {
|
|
3963
|
-
const text = reason?.trim();
|
|
3964
|
-
return text ? { label: text, labelSource: "provider" } : {};
|
|
3965
|
-
}
|
|
3966
|
-
async function finishBookedSubmission(jobId, booked2, endpoint) {
|
|
3967
|
-
recordSpend({
|
|
3968
|
-
msats: booked2.amountMsats,
|
|
3969
|
-
btcRate: booked2.btcRate,
|
|
3970
|
-
jobId,
|
|
3971
|
-
providerEndpoint: endpoint ?? loadJob(jobId)?.endpoint ?? "",
|
|
3972
|
-
...midJobSpendLabel(booked2.reason)
|
|
3973
|
-
});
|
|
3974
|
-
if (booked2.rail === "cashu_p2pk") await commitHeldSubmission(booked2.cashuRequestId);
|
|
3975
|
-
}
|
|
3976
|
-
async function settleTakenPayment(jobId, requestSeq) {
|
|
3977
|
-
const booked2 = markPaymentRequestPaid(jobId, requestSeq);
|
|
3978
|
-
if (booked2) await finishBookedSubmission(jobId, booked2);
|
|
3979
|
-
return booked2;
|
|
3980
|
-
}
|
|
3981
|
-
|
|
3982
|
-
// src/lib/wallet-agent/journal-file.ts
|
|
3983
|
-
var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
|
|
3984
|
-
import { closeSync as closeSync5, existsSync as existsSync5, fsyncSync as fsyncSync4, openSync as openSync5, readFileSync as readFileSync5, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
3985
|
-
import { dirname as dirname2, join as join4 } from "path";
|
|
3986
|
-
function journalFile(name) {
|
|
3987
|
-
const file = () => join4(dirname2(JOBS_FILE), name);
|
|
3988
|
-
function read() {
|
|
3989
|
-
if (!existsSync5(file())) return [];
|
|
3931
|
+
let reserveSats;
|
|
3990
3932
|
try {
|
|
3991
|
-
|
|
3992
|
-
|
|
3993
|
-
|
|
3994
|
-
|
|
3933
|
+
reserveSats = swapSendReserve(candidateWallet, args.amountSats);
|
|
3934
|
+
} catch (err) {
|
|
3935
|
+
attempts.push({ mint, reason: "keys_unavailable", message: errorText(err) });
|
|
3936
|
+
continue;
|
|
3995
3937
|
}
|
|
3996
|
-
|
|
3997
|
-
|
|
3998
|
-
|
|
3999
|
-
|
|
4000
|
-
|
|
4001
|
-
|
|
4002
|
-
|
|
4003
|
-
release = import_proper_lockfile2.default.lockSync(file(), { realpath: false });
|
|
4004
|
-
} catch (error) {
|
|
4005
|
-
if (attempt >= 40) throw error;
|
|
4006
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
|
|
4007
|
-
}
|
|
3938
|
+
if (!swapEnabled(candidateWallet)) {
|
|
3939
|
+
attempts.push({
|
|
3940
|
+
mint,
|
|
3941
|
+
reason: "swap_disabled",
|
|
3942
|
+
message: "Mint advertises swaps switched off (NUT-3 disabled)."
|
|
3943
|
+
});
|
|
3944
|
+
continue;
|
|
4008
3945
|
}
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
|
|
4012
|
-
|
|
3946
|
+
const lock2 = await withWalletLock(() => {
|
|
3947
|
+
const fresh = loadAgentWallet();
|
|
3948
|
+
if (!fresh) {
|
|
3949
|
+
return {
|
|
3950
|
+
error: {
|
|
3951
|
+
code: "no_agent_wallet",
|
|
3952
|
+
message: "Agent wallet vanished between locks.",
|
|
3953
|
+
hint: "Run: dvm wallet init"
|
|
3954
|
+
}
|
|
3955
|
+
};
|
|
3956
|
+
}
|
|
3957
|
+
if (strict) {
|
|
3958
|
+
const pending = strictWalletStateReason(fresh);
|
|
3959
|
+
if (pending) return strictSpendFailure(pending);
|
|
3960
|
+
}
|
|
3961
|
+
const swept = strict ? { wallet: fresh, reverted: 0 } : sweepStaleInFlight(fresh, now());
|
|
3962
|
+
const selection = selectProofsForSpend({
|
|
3963
|
+
proofs: swept.wallet.proofs,
|
|
3964
|
+
mintAllowlist: [mint],
|
|
3965
|
+
amountSats: args.amountSats,
|
|
3966
|
+
swapReserveSats: reserveSats
|
|
3967
|
+
});
|
|
3968
|
+
if ("error" in selection) {
|
|
3969
|
+
if (swept.reverted > 0) saveAgentWallet(swept.wallet);
|
|
3970
|
+
return { error: selection.error };
|
|
3971
|
+
}
|
|
3972
|
+
const selectedFeeSats = reserveSats(selection.selected);
|
|
3973
|
+
if (args.maxCashuFeeSats !== void 0 && selectedFeeSats > args.maxCashuFeeSats) {
|
|
3974
|
+
return {
|
|
3975
|
+
error: {
|
|
3976
|
+
code: "cashu_fee_cap_exceeded",
|
|
3977
|
+
message: `Cashu fees at ${mint} would be ${selectedFeeSats} sats, over the ${args.maxCashuFeeSats}-sat --max-cashu-fee-sats limit.`,
|
|
3978
|
+
hint: "Raise --max-cashu-fee-sats only after approval, or fund an accepted mint with a lower swap fee."
|
|
3979
|
+
}
|
|
3980
|
+
};
|
|
3981
|
+
}
|
|
3982
|
+
const proofKeys = new Set(selection.selected.map((p) => proofKey(p)));
|
|
3983
|
+
const untilMs = now() + timeoutSec * 1e3;
|
|
3984
|
+
const feeContext = contextWithInitialCashuFee(
|
|
3985
|
+
submitContext,
|
|
3986
|
+
args.maxCashuFeeSats,
|
|
3987
|
+
selectedFeeSats
|
|
3988
|
+
);
|
|
3989
|
+
const submission = {
|
|
3990
|
+
endpoint: args.endpoint,
|
|
3991
|
+
request_id: requestId,
|
|
3992
|
+
intended_lock_pubkey: args.cashuP2pk.lock_pubkey,
|
|
3993
|
+
mint: selection.mint,
|
|
3994
|
+
amount_sats: args.amountSats,
|
|
3995
|
+
...args.maxCashuFeeSats !== void 0 ? { max_cashu_fee_sats: args.maxCashuFeeSats } : {},
|
|
3996
|
+
initial_cashu_fee_sats: selectedFeeSats,
|
|
3997
|
+
output_proofs: [],
|
|
3998
|
+
created_at: new Date(now()).toISOString(),
|
|
3999
|
+
...feeContext ? { context: feeContext } : {},
|
|
4000
|
+
...refundClause ? {
|
|
4001
|
+
canonical_id: refundClause.canonicalId,
|
|
4002
|
+
refund_pubkey: refundClause.refundPubkey,
|
|
4003
|
+
t_expire: refundClause.tExpireSec * 1e3
|
|
4004
|
+
} : {}
|
|
4005
|
+
};
|
|
4006
|
+
const marked = markProofsInFlight(swept.wallet, proofKeys, untilMs);
|
|
4007
|
+
saveAgentWallet({
|
|
4008
|
+
...marked,
|
|
4009
|
+
pending_submissions: [...marked.pending_submissions, submission]
|
|
4010
|
+
});
|
|
4011
|
+
return {
|
|
4012
|
+
lockPrivkey: fresh.lock_privkey,
|
|
4013
|
+
lockPubkey: fresh.lock_pubkey,
|
|
4014
|
+
selectedProofs: selection.selected,
|
|
4015
|
+
selectedKeys: proofKeys,
|
|
4016
|
+
mint: selection.mint,
|
|
4017
|
+
requestId,
|
|
4018
|
+
submission,
|
|
4019
|
+
fromReserve: false
|
|
4020
|
+
};
|
|
4021
|
+
});
|
|
4022
|
+
if ("error" in lock2) {
|
|
4023
|
+
if (lock2.error.code === "no_agent_wallet") return lock2;
|
|
4024
|
+
if (lock2.error.code === "cashu_fee_cap_exceeded") {
|
|
4025
|
+
lastFeeCapError = lock2.error;
|
|
4026
|
+
attempts.push({ mint, reason: "fee_cap_exceeded", message: lock2.error.message });
|
|
4027
|
+
continue;
|
|
4028
|
+
}
|
|
4029
|
+
const selectError = lock2.error;
|
|
4030
|
+
lastSelectError = selectError;
|
|
4031
|
+
attempts.push({ mint, reason: selectError.code, message: selectError.message });
|
|
4032
|
+
continue;
|
|
4013
4033
|
}
|
|
4014
|
-
|
|
4015
|
-
|
|
4016
|
-
|
|
4017
|
-
|
|
4034
|
+
const swapBuilder = candidateWallet.ops.send(lock2.submission.amount_sats, toCashuProofs(lock2.selectedProofs)).asP2PK({
|
|
4035
|
+
pubkey: args.cashuP2pk.lock_pubkey,
|
|
4036
|
+
...refundClause ? { locktime: refundClause.tExpireSec, refundKeys: [refundClause.refundPubkey] } : {}
|
|
4037
|
+
}).keepAsP2PK({ pubkey: lock2.lockPubkey }).privkey(lock2.lockPrivkey).includeFees(true);
|
|
4038
|
+
let preview;
|
|
4018
4039
|
try {
|
|
4019
|
-
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4040
|
+
preview = await swapBuilder.prepare();
|
|
4041
|
+
} catch (err) {
|
|
4042
|
+
attempts.push({ mint, reason: "swap_rejected", message: errorText(err) });
|
|
4043
|
+
await rollbackAttempt(requestId, lock2.selectedKeys);
|
|
4044
|
+
if (hasNextCandidate) continue;
|
|
4045
|
+
break;
|
|
4023
4046
|
}
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
|
|
4035
|
-
|
|
4036
|
-
|
|
4037
|
-
|
|
4038
|
-
|
|
4039
|
-
|
|
4040
|
-
|
|
4041
|
-
|
|
4042
|
-
|
|
4043
|
-
|
|
4044
|
-
|
|
4045
|
-
|
|
4046
|
-
|
|
4047
|
-
|
|
4048
|
-
|
|
4049
|
-
|
|
4050
|
-
|
|
4051
|
-
|
|
4052
|
-
|
|
4053
|
-
|
|
4054
|
-
|
|
4055
|
-
|
|
4056
|
-
function recordSubmissionVerdicts(verdicts) {
|
|
4057
|
-
if (verdicts.length === 0) return;
|
|
4058
|
-
withVerdictsLock(() => {
|
|
4059
|
-
const journalled = readVerdicts();
|
|
4060
|
-
const reclaimed = new Set(journalled.filter((verdict) => verdict.verdict === "reclaimed").map((verdict) => verdict.requestId));
|
|
4061
|
-
const incoming = verdicts.filter((verdict) => !reclaimed.has(verdict.requestId));
|
|
4062
|
-
const ids = new Set(incoming.map((verdict) => verdict.requestId));
|
|
4063
|
-
writeVerdicts([...journalled.filter((verdict) => !ids.has(verdict.requestId)), ...incoming]);
|
|
4064
|
-
});
|
|
4065
|
-
}
|
|
4066
|
-
async function applySubmissionVerdicts() {
|
|
4067
|
-
let failure;
|
|
4068
|
-
try {
|
|
4069
|
-
finalizeLandedReclaims();
|
|
4070
|
-
} catch (error) {
|
|
4071
|
-
failure = { error };
|
|
4072
|
-
}
|
|
4073
|
-
try {
|
|
4074
|
-
await applyJournalledVerdicts();
|
|
4075
|
-
} catch (error) {
|
|
4076
|
-
failure ??= { error };
|
|
4077
|
-
}
|
|
4078
|
-
if (failure) throw failure.error;
|
|
4079
|
-
}
|
|
4080
|
-
async function applyJournalledVerdicts() {
|
|
4081
|
-
const journalled = readVerdicts();
|
|
4082
|
-
if (journalled.length === 0) return;
|
|
4083
|
-
const held = new Set(loadAgentWallet()?.pending_submissions.map((entry) => entry.request_id) ?? []);
|
|
4084
|
-
const landed = journalled.filter((verdict) => !held.has(verdict.requestId));
|
|
4085
|
-
if (landed.length === 0) return;
|
|
4086
|
-
releaseReclaimedSubmissions(new Set(landed.filter((verdict) => verdict.verdict === "reclaimed").map((verdict) => verdict.requestId)));
|
|
4087
|
-
for (const verdict of landed) {
|
|
4088
|
-
if (verdict.verdict === "reclaimed") continue;
|
|
4089
|
-
for (const ask of heldCashuSubmissionAsks(/* @__PURE__ */ new Set([verdict.requestId]))) {
|
|
4090
|
-
if (ask.blocked?.reason === "credit_held") continue;
|
|
4091
|
-
if (verdict.verdict === "spent" && !verdict.reserve) await settleTakenPayment(ask.jobId, ask.requestSeq);
|
|
4092
|
-
else blockHeldPayment(ask.jobId, ask.requestSeq, {
|
|
4093
|
-
reason: "proofs_spent",
|
|
4094
|
-
detail: verdict.verdict === "partly_spent" ? `The provider redeemed ${verdict.spentSats ?? "part"} of the ${verdict.amountSats ?? "?"} sats in the earlier token, and the wallet took back the rest; that is not a payment of this charge.` : "The reserve proofs the earlier token used are spent at the mint and the provider recorded no payment for this charge, but it may already have redeemed this token for this charge, so paying again may pay twice."
|
|
4047
|
+
const initialCashuFeeSats = reserveSats(preview.inputs);
|
|
4048
|
+
const preparedContext = contextWithInitialCashuFee(
|
|
4049
|
+
lock2.submission.context,
|
|
4050
|
+
args.maxCashuFeeSats,
|
|
4051
|
+
initialCashuFeeSats
|
|
4052
|
+
);
|
|
4053
|
+
const preparedSubmission = {
|
|
4054
|
+
...lock2.submission,
|
|
4055
|
+
initial_cashu_fee_sats: initialCashuFeeSats,
|
|
4056
|
+
...preparedContext ? { context: preparedContext } : {}
|
|
4057
|
+
};
|
|
4058
|
+
const inputSecrets = new Set(preview.inputs.map((proof) => proof.secret));
|
|
4059
|
+
const swapping = {
|
|
4060
|
+
keyset_id: preview.keysetId,
|
|
4061
|
+
input_proofs: lock2.selectedProofs.filter((proof) => inputSecrets.has(proof.secret)),
|
|
4062
|
+
unselected_proofs: lock2.selectedProofs.filter((proof) => !inputSecrets.has(proof.secret)),
|
|
4063
|
+
send_outputs: serializeOutputData(preview.sendOutputs ?? []),
|
|
4064
|
+
keep_outputs: serializeOutputData(preview.keepOutputs ?? [])
|
|
4065
|
+
};
|
|
4066
|
+
await withWalletLock(() => {
|
|
4067
|
+
const fresh = loadAgentWallet();
|
|
4068
|
+
if (!fresh) return;
|
|
4069
|
+
saveAgentWallet({
|
|
4070
|
+
...fresh,
|
|
4071
|
+
pending_submissions: fresh.pending_submissions.map(
|
|
4072
|
+
(submission) => submission.request_id === requestId ? {
|
|
4073
|
+
...submission,
|
|
4074
|
+
initial_cashu_fee_sats: initialCashuFeeSats,
|
|
4075
|
+
...preparedContext ? { context: preparedContext } : {},
|
|
4076
|
+
swapping
|
|
4077
|
+
} : submission
|
|
4078
|
+
)
|
|
4095
4079
|
});
|
|
4080
|
+
});
|
|
4081
|
+
try {
|
|
4082
|
+
const result = await candidateWallet.completeSwap(preview, lock2.lockPrivkey);
|
|
4083
|
+
inner = { ...lock2, submission: preparedSubmission };
|
|
4084
|
+
sendProofs = result.send;
|
|
4085
|
+
keepProofs = result.keep;
|
|
4086
|
+
break;
|
|
4087
|
+
} catch (err) {
|
|
4088
|
+
attempts.push({ mint, reason: "swap_rejected", message: errorText(err) });
|
|
4089
|
+
if (err instanceof te) {
|
|
4090
|
+
await rollbackAttempt(requestId, lock2.selectedKeys);
|
|
4091
|
+
if (hasNextCandidate) continue;
|
|
4092
|
+
break;
|
|
4093
|
+
}
|
|
4094
|
+
inputsLeftInFlight = true;
|
|
4095
|
+
break;
|
|
4096
4096
|
}
|
|
4097
4097
|
}
|
|
4098
|
-
if (
|
|
4099
|
-
|
|
4100
|
-
|
|
4101
|
-
}
|
|
4102
|
-
|
|
4103
|
-
const
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
|
|
4107
|
-
const
|
|
4108
|
-
|
|
4109
|
-
|
|
4110
|
-
|
|
4111
|
-
|
|
4112
|
-
|
|
4098
|
+
if (!inner)
|
|
4099
|
+
return {
|
|
4100
|
+
error: exhaustedError(attempts, lastSelectError, lastFeeCapError, inputsLeftInFlight)
|
|
4101
|
+
};
|
|
4102
|
+
const cashuToken = ki({ mint: inner.mint, proofs: sendProofs });
|
|
4103
|
+
const boundContext = bindCashuTokenToSubmissionContext(inner.submission.context, cashuToken);
|
|
4104
|
+
const agentOutputs = sendProofs.map(
|
|
4105
|
+
(p) => toAgentProof(p, inner.mint, args.cashuP2pk.lock_pubkey)
|
|
4106
|
+
);
|
|
4107
|
+
const agentKeep = keepProofs.map((p) => toAgentProof(p, inner.mint, inner.lockPubkey));
|
|
4108
|
+
await withWalletLock(() => {
|
|
4109
|
+
const fresh = loadAgentWallet();
|
|
4110
|
+
if (!fresh) return;
|
|
4111
|
+
const next = {
|
|
4112
|
+
...fresh,
|
|
4113
|
+
proofs: [...fresh.proofs.filter((p) => !inner.selectedKeys.has(proofKey(p))), ...agentKeep],
|
|
4114
|
+
pending_submissions: fresh.pending_submissions.map(
|
|
4115
|
+
(s) => s.request_id === inner.requestId ? {
|
|
4116
|
+
...s,
|
|
4117
|
+
output_proofs: agentOutputs,
|
|
4118
|
+
swapping: void 0,
|
|
4119
|
+
cashu_token: cashuToken,
|
|
4120
|
+
...boundContext ? { context: boundContext } : {},
|
|
4121
|
+
// What a later reclaim needs. Only the swap path
|
|
4122
|
+
// writes these: reserve-direct entries ship proofs that still
|
|
4123
|
+
// live in `wallet.proofs[]`, and `release` / the in-flight
|
|
4124
|
+
// revert already own their recovery.
|
|
4125
|
+
...refundClause ? {
|
|
4126
|
+
canonical_id: refundClause.canonicalId,
|
|
4127
|
+
refund_pubkey: refundClause.refundPubkey,
|
|
4128
|
+
t_expire: refundClause.tExpireSec * 1e3
|
|
4129
|
+
} : {}
|
|
4130
|
+
} : s
|
|
4131
|
+
)
|
|
4132
|
+
};
|
|
4133
|
+
saveAgentWallet(next);
|
|
4134
|
+
});
|
|
4135
|
+
return {
|
|
4136
|
+
cashuToken,
|
|
4137
|
+
requestId: inner.requestId,
|
|
4138
|
+
mint: inner.mint,
|
|
4139
|
+
totalSats: inner.submission.amount_sats,
|
|
4140
|
+
endpoint: args.endpoint,
|
|
4141
|
+
intendedLockPubkey: args.cashuP2pk.lock_pubkey,
|
|
4142
|
+
...attempts.length > 0 ? { attempts: successfulSpendAttempts(attempts) } : {},
|
|
4143
|
+
...boundContext?.binding_fingerprint ? { submissionBindingFingerprint: boundContext.binding_fingerprint } : {}
|
|
4144
|
+
};
|
|
4113
4145
|
}
|
|
4114
|
-
|
|
4115
|
-
|
|
4116
|
-
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
|
|
4122
|
-
|
|
4123
|
-
|
|
4124
|
-
|
|
4125
|
-
|
|
4126
|
-
|
|
4146
|
+
function successfulSpendAttempts(attempts) {
|
|
4147
|
+
const messages = {
|
|
4148
|
+
unreachable: "Mint could not be loaded.",
|
|
4149
|
+
keys_unavailable: "Mint did not provide an active keyset.",
|
|
4150
|
+
swap_disabled: "Mint advertises swaps switched off (NUT-3 disabled).",
|
|
4151
|
+
fee_cap_exceeded: "Mint swap fee exceeds the approved limit.",
|
|
4152
|
+
insufficient_balance: "Mint balance cannot cover the price and swap fee.",
|
|
4153
|
+
no_eligible_mint: "Mint no longer has eligible proofs for this payment.",
|
|
4154
|
+
swap_rejected: "Mint swap could not be prepared or was definitely refused."
|
|
4155
|
+
};
|
|
4156
|
+
return attempts.map(({ mint, reason }) => {
|
|
4157
|
+
let safeMint;
|
|
4158
|
+
try {
|
|
4159
|
+
new URL(mint);
|
|
4160
|
+
safeMint = redactUrl(mint).replace(/\/$/u, "").slice(0, 2048);
|
|
4161
|
+
} catch {
|
|
4162
|
+
safeMint = "[invalid mint URL]";
|
|
4127
4163
|
}
|
|
4128
|
-
|
|
4129
|
-
|
|
4130
|
-
return answered;
|
|
4164
|
+
return { mint: safeMint, reason, message: messages[reason] };
|
|
4165
|
+
});
|
|
4131
4166
|
}
|
|
4132
|
-
function
|
|
4133
|
-
|
|
4134
|
-
|
|
4135
|
-
|
|
4136
|
-
|
|
4137
|
-
|
|
4138
|
-
const seq = message.content.credit?.request_seq ?? paymentRequest;
|
|
4139
|
-
if (seq !== void 0) answers.set(seq, [...answers.get(seq) ?? [], message]);
|
|
4167
|
+
function principalCapFailure(principalSats, maxCashuPrincipalSats) {
|
|
4168
|
+
return {
|
|
4169
|
+
error: {
|
|
4170
|
+
code: "cashu_principal_cap_exceeded",
|
|
4171
|
+
message: `Cashu principal of ${principalSats} sats is over the ${maxCashuPrincipalSats}-sat --max-cashu-principal-sats limit.`,
|
|
4172
|
+
hint: "Raise --max-cashu-principal-sats only after approval, or retry when the approved dollar amount needs fewer sats."
|
|
4140
4173
|
}
|
|
4141
|
-
}
|
|
4142
|
-
return answers;
|
|
4143
|
-
}
|
|
4144
|
-
function carriesSubmission(content, submission) {
|
|
4145
|
-
if (submission.rail === "cashu_p2pk") return content.cashu_request_id === submission.cashuRequestId;
|
|
4146
|
-
const key = submission.rail === "x402" ? "x402_payment" : "tempo_credential";
|
|
4147
|
-
return content[key] !== void 0 && canonicalJson(content[key]) === canonicalJson(submission.content[key]);
|
|
4174
|
+
};
|
|
4148
4175
|
}
|
|
4149
|
-
function
|
|
4150
|
-
if (
|
|
4151
|
-
|
|
4152
|
-
|
|
4153
|
-
|
|
4176
|
+
function contextWithInitialCashuFee(context, maxCashuFeeSats, initialCashuFeeSats) {
|
|
4177
|
+
if (!context) return void 0;
|
|
4178
|
+
return {
|
|
4179
|
+
...context,
|
|
4180
|
+
...maxCashuFeeSats !== void 0 ? { max_cashu_fee_sats: maxCashuFeeSats } : {},
|
|
4181
|
+
initial_cashu_fee_sats: initialCashuFeeSats
|
|
4182
|
+
};
|
|
4154
4183
|
}
|
|
4155
|
-
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
if (
|
|
4159
|
-
|
|
4160
|
-
|
|
4184
|
+
function strictSpendInputError(args) {
|
|
4185
|
+
if (args.maxCashuFeeSats === void 0)
|
|
4186
|
+
return strictSpendFailure("Strict Cashu per-call mode requires an explicit fee ceiling.");
|
|
4187
|
+
if (args.builderHandle)
|
|
4188
|
+
return strictSpendFailure("Strict Cashu per-call mode cannot use builder reserve proofs.");
|
|
4189
|
+
if (args.cashuP2pk.mints.length !== 1)
|
|
4190
|
+
return strictSpendFailure("Strict Cashu per-call mode requires exactly one pinned mint.");
|
|
4191
|
+
const context = args.submitContext;
|
|
4192
|
+
if (context?.strict_per_call !== true || context.route === "credit" || context.max_cashu_fee_sats !== args.maxCashuFeeSats || context.pinned_mint !== args.cashuP2pk.mints[0])
|
|
4193
|
+
return strictSpendFailure("Strict Cashu per-call mode requires one matching job context.");
|
|
4194
|
+
return null;
|
|
4161
4195
|
}
|
|
4162
|
-
function
|
|
4163
|
-
|
|
4196
|
+
function strictWalletStateReason(wallet) {
|
|
4197
|
+
if (wallet.pending_mints.length > 0) return "The Cashu wallet has a pending mint.";
|
|
4198
|
+
if (wallet.pending_melts.length > 0) return "The Cashu wallet has a pending melt.";
|
|
4199
|
+
if (wallet.pending_submissions.length > 0)
|
|
4200
|
+
return "The Cashu wallet has another pending submission.";
|
|
4201
|
+
if (wallet.proofs.some((proof) => proof.status === "in_flight"))
|
|
4202
|
+
return "The Cashu wallet has in-flight proofs.";
|
|
4203
|
+
return null;
|
|
4164
4204
|
}
|
|
4165
|
-
function
|
|
4166
|
-
|
|
4167
|
-
|
|
4168
|
-
|
|
4169
|
-
|
|
4205
|
+
function strictSpendFailure(message) {
|
|
4206
|
+
return {
|
|
4207
|
+
error: {
|
|
4208
|
+
code: "strict_per_call_unsafe",
|
|
4209
|
+
message,
|
|
4210
|
+
hint: "Resolve the existing wallet operation, then rebuild and re-approve the strict request."
|
|
4211
|
+
}
|
|
4212
|
+
};
|
|
4170
4213
|
}
|
|
4171
|
-
function
|
|
4172
|
-
|
|
4173
|
-
|
|
4174
|
-
|
|
4175
|
-
|
|
4176
|
-
|
|
4177
|
-
|
|
4214
|
+
async function commitAgentSpend(args) {
|
|
4215
|
+
await withWalletLock(() => {
|
|
4216
|
+
const wallet = loadAgentWallet();
|
|
4217
|
+
if (!wallet) return;
|
|
4218
|
+
const submission = wallet.pending_submissions.find((s) => s.request_id === args.requestId);
|
|
4219
|
+
const shippedKeys = new Set(submission?.output_proofs.map((p) => `${p.secret}:${p.C}`) ?? []);
|
|
4220
|
+
const next = {
|
|
4221
|
+
...wallet,
|
|
4222
|
+
proofs: wallet.proofs.filter((p) => !shippedKeys.has(`${p.secret}:${p.C}`)),
|
|
4223
|
+
pending_submissions: wallet.pending_submissions.filter(
|
|
4224
|
+
(s) => s.request_id !== args.requestId
|
|
4225
|
+
),
|
|
4226
|
+
recent_spends: [...wallet.recent_spends, args.recentSpend].slice(-RECENT_SPENDS_CAP)
|
|
4227
|
+
};
|
|
4228
|
+
saveAgentWallet(next);
|
|
4229
|
+
});
|
|
4178
4230
|
}
|
|
4179
|
-
function
|
|
4180
|
-
|
|
4231
|
+
async function commitHeldSubmission(requestId, now = Date.now) {
|
|
4232
|
+
await withWalletLock(() => {
|
|
4233
|
+
const wallet = loadAgentWallet();
|
|
4234
|
+
const submission = wallet?.pending_submissions.find((s) => s.request_id === requestId);
|
|
4235
|
+
if (!wallet || !submission) return;
|
|
4236
|
+
const shippedKeys = new Set(submission.output_proofs.map((p) => `${p.secret}:${p.C}`));
|
|
4237
|
+
saveAgentWallet({
|
|
4238
|
+
...wallet,
|
|
4239
|
+
proofs: wallet.proofs.filter((p) => !shippedKeys.has(`${p.secret}:${p.C}`)),
|
|
4240
|
+
pending_submissions: wallet.pending_submissions.filter((s) => s.request_id !== requestId),
|
|
4241
|
+
recent_spends: [...wallet.recent_spends, {
|
|
4242
|
+
request_id: requestId,
|
|
4243
|
+
dvm_endpoint: submission.endpoint,
|
|
4244
|
+
mint: submission.mint,
|
|
4245
|
+
amount_sats: submission.amount_sats,
|
|
4246
|
+
signed_at_ms: now()
|
|
4247
|
+
}].slice(-RECENT_SPENDS_CAP)
|
|
4248
|
+
});
|
|
4249
|
+
});
|
|
4181
4250
|
}
|
|
4182
|
-
function
|
|
4183
|
-
|
|
4184
|
-
|
|
4185
|
-
|
|
4186
|
-
|
|
4187
|
-
|
|
4188
|
-
|
|
4251
|
+
async function correctPendingFundAmount(args) {
|
|
4252
|
+
await withWalletLock(() => {
|
|
4253
|
+
const wallet = loadAgentWallet();
|
|
4254
|
+
if (!wallet) return;
|
|
4255
|
+
const next = {
|
|
4256
|
+
...wallet,
|
|
4257
|
+
pending_submissions: wallet.pending_submissions.map((s) => {
|
|
4258
|
+
if (s.request_id !== args.requestId || !s.context) return s;
|
|
4259
|
+
const data = s.context.submit_body.data;
|
|
4260
|
+
const fund = data?.fund;
|
|
4261
|
+
if (!fund) return s;
|
|
4262
|
+
const { request_id: _requestId, ...rest } = data ?? {};
|
|
4263
|
+
return {
|
|
4264
|
+
...s,
|
|
4265
|
+
context: {
|
|
4266
|
+
...s.context,
|
|
4267
|
+
submit_body: {
|
|
4268
|
+
...s.context.submit_body,
|
|
4269
|
+
data: { ...rest, fund: { ...fund, amount_micro: args.amountMicro } }
|
|
4270
|
+
}
|
|
4271
|
+
}
|
|
4272
|
+
};
|
|
4273
|
+
})
|
|
4274
|
+
};
|
|
4275
|
+
saveAgentWallet(next);
|
|
4276
|
+
});
|
|
4189
4277
|
}
|
|
4190
|
-
async function
|
|
4191
|
-
|
|
4192
|
-
|
|
4193
|
-
|
|
4194
|
-
|
|
4195
|
-
|
|
4196
|
-
return reconcilePaymentRequestHistory(jobId, requestSeq, history, status, () => decisionTime);
|
|
4278
|
+
async function abandonPendingSubmission(args) {
|
|
4279
|
+
await withWalletLock(() => {
|
|
4280
|
+
const wallet = loadAgentWallet();
|
|
4281
|
+
if (!wallet) return;
|
|
4282
|
+
saveAgentWallet(abandonSubmissionInWallet(wallet, args));
|
|
4283
|
+
});
|
|
4197
4284
|
}
|
|
4198
|
-
|
|
4199
|
-
|
|
4200
|
-
|
|
4201
|
-
|
|
4202
|
-
|
|
4203
|
-
|
|
4204
|
-
|
|
4205
|
-
|
|
4206
|
-
|
|
4207
|
-
|
|
4208
|
-
|
|
4209
|
-
|
|
4210
|
-
|
|
4211
|
-
|
|
4212
|
-
`Retry with \`dvm pay ${shellQuoteArg(jobId)}\` in about ${seconds} ${seconds === 1 ? "second" : "seconds"}, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`,
|
|
4213
|
-
{ retry_at_ms: retryAt }
|
|
4214
|
-
);
|
|
4215
|
-
if (status !== "awaiting-input" || pendingPaymentRequest(history)?.seq !== requestSeq)
|
|
4216
|
-
throw new DvmError(
|
|
4217
|
-
"payment_request_not_pending",
|
|
4218
|
-
"The provider is no longer waiting on this payment request.",
|
|
4219
|
-
`Check the job with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
|
|
4220
|
-
);
|
|
4221
|
-
return false;
|
|
4285
|
+
function abandonSubmissionInWallet(wallet, args) {
|
|
4286
|
+
const submission = wallet.pending_submissions.find((s) => s.request_id === args.requestId);
|
|
4287
|
+
const shippedKeys = new Set(submission?.output_proofs.map((p) => `${p.secret}:${p.C}`) ?? []);
|
|
4288
|
+
const walletKeys = new Set(wallet.proofs.map((p) => `${p.secret}:${p.C}`));
|
|
4289
|
+
const retain = args.preserveRecovery && [...shippedKeys].some((key) => !walletKeys.has(key));
|
|
4290
|
+
return {
|
|
4291
|
+
...wallet,
|
|
4292
|
+
proofs: wallet.proofs.map(
|
|
4293
|
+
(p) => shippedKeys.has(`${p.secret}:${p.C}`) && p.status === "in_flight" ? { ...p, status: "valid", in_flight_until_ms: void 0 } : p
|
|
4294
|
+
),
|
|
4295
|
+
pending_submissions: retain ? wallet.pending_submissions.map(
|
|
4296
|
+
(s) => s.request_id === args.requestId ? { ...s, context: void 0 } : s
|
|
4297
|
+
) : wallet.pending_submissions.filter((s) => s.request_id !== args.requestId)
|
|
4298
|
+
};
|
|
4222
4299
|
}
|
|
4223
|
-
async function
|
|
4224
|
-
await
|
|
4225
|
-
|
|
4226
|
-
|
|
4227
|
-
|
|
4228
|
-
|
|
4229
|
-
|
|
4230
|
-
for (const seq of job?.paidPaymentRequestSeqs ?? []) held.delete(seq);
|
|
4231
|
-
if (held.size === 0) return;
|
|
4232
|
-
const history = loadMessages(jobId);
|
|
4233
|
-
const answers = paymentAnswers(history);
|
|
4234
|
-
for (const seq of held) if (answers.has(seq)) await settleAnsweredAsk(jobId, seq, history);
|
|
4300
|
+
async function markPendingSubmissionUnresolved(args) {
|
|
4301
|
+
await withWalletLock(() => {
|
|
4302
|
+
const wallet = loadAgentWallet();
|
|
4303
|
+
if (!wallet) return;
|
|
4304
|
+
const next = withAcceptedUnresolved(wallet, args.requestId, args.marker);
|
|
4305
|
+
if (next !== wallet) saveAgentWallet(next);
|
|
4306
|
+
});
|
|
4235
4307
|
}
|
|
4236
|
-
function
|
|
4237
|
-
const
|
|
4238
|
-
|
|
4308
|
+
function withAcceptedUnresolved(wallet, requestId, marker) {
|
|
4309
|
+
const target = wallet.pending_submissions.find((s) => s.request_id === requestId);
|
|
4310
|
+
if (!target || target.accepted_unresolved) return wallet;
|
|
4311
|
+
return {
|
|
4312
|
+
...wallet,
|
|
4313
|
+
pending_submissions: wallet.pending_submissions.map(
|
|
4314
|
+
(s) => s.request_id === requestId ? { ...s, accepted_unresolved: marker } : s
|
|
4315
|
+
)
|
|
4316
|
+
};
|
|
4239
4317
|
}
|
|
4240
|
-
|
|
4241
|
-
|
|
4318
|
+
function resolveRefundClause(offer, locktimeSecondsOverride, nowMs, opts) {
|
|
4319
|
+
const canonicalId = offer.canonical_id;
|
|
4320
|
+
if (!canonicalId) return null;
|
|
4321
|
+
const mnemonic = (opts.readMnemonic ?? readAgentMnemonic)();
|
|
4322
|
+
if (!mnemonic) return null;
|
|
4323
|
+
const locktimeSeconds = Math.max(
|
|
4324
|
+
locktimeSecondsOverride ?? perCallLocktimeSeconds(offer.min_locktime),
|
|
4325
|
+
offer.min_locktime ?? 0
|
|
4326
|
+
);
|
|
4242
4327
|
try {
|
|
4243
|
-
return
|
|
4244
|
-
|
|
4245
|
-
|
|
4246
|
-
|
|
4247
|
-
|
|
4248
|
-
|
|
4249
|
-
|
|
4250
|
-
"Payment recovery read timed out. No new payment was sent.",
|
|
4251
|
-
`Retry with \`dvm pay ${shellQuoteArg(jobId)}\` or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`
|
|
4252
|
-
);
|
|
4253
|
-
throw error;
|
|
4254
|
-
} finally {
|
|
4255
|
-
if (timer) clearTimeout(timer);
|
|
4328
|
+
return {
|
|
4329
|
+
tExpireSec: Math.floor(nowMs / 1e3) + locktimeSeconds,
|
|
4330
|
+
refundPubkey: deriveAgentRefundSubkeyPubkey(mnemonic, canonicalId),
|
|
4331
|
+
canonicalId
|
|
4332
|
+
};
|
|
4333
|
+
} catch {
|
|
4334
|
+
return null;
|
|
4256
4335
|
}
|
|
4257
4336
|
}
|
|
4258
|
-
|
|
4259
|
-
|
|
4260
|
-
|
|
4261
|
-
|
|
4337
|
+
async function rollbackAttempt(requestId, proofKeys) {
|
|
4338
|
+
await withWalletLock(() => {
|
|
4339
|
+
const wallet = loadAgentWallet();
|
|
4340
|
+
if (!wallet) return;
|
|
4341
|
+
const reverted = revertInFlight(wallet, proofKeys);
|
|
4342
|
+
saveAgentWallet({
|
|
4343
|
+
...reverted,
|
|
4344
|
+
pending_submissions: reverted.pending_submissions.filter((s) => s.request_id !== requestId)
|
|
4345
|
+
});
|
|
4346
|
+
});
|
|
4262
4347
|
}
|
|
4263
|
-
function
|
|
4348
|
+
function exhaustedError(attempts, lastSelectError, lastFeeCapError, inputsLeftInFlight) {
|
|
4349
|
+
if (attempts.length === 0) {
|
|
4350
|
+
return {
|
|
4351
|
+
code: "no_eligible_mint",
|
|
4352
|
+
message: "No mint the DVM accepts could be attempted for this payment.",
|
|
4353
|
+
hint: "Fund the wallet at one of the DVM's accepted mints with: dvm wallet fund <amount>",
|
|
4354
|
+
attempts
|
|
4355
|
+
};
|
|
4356
|
+
}
|
|
4357
|
+
if (lastSelectError && attempts.every((a) => isSelectionReason(a.reason))) {
|
|
4358
|
+
if (attempts.length === 1) return { ...lastSelectError, attempts };
|
|
4359
|
+
return {
|
|
4360
|
+
code: lastSelectError.code,
|
|
4361
|
+
message: `Agent wallet can't cover the price plus the per-call swap fee at any of the DVM's mints: ${describeAttempts(attempts)}.`,
|
|
4362
|
+
hint: lastSelectError.hint,
|
|
4363
|
+
attempts
|
|
4364
|
+
};
|
|
4365
|
+
}
|
|
4366
|
+
if (lastFeeCapError && attempts.every(
|
|
4367
|
+
(attempt) => ["fee_cap_exceeded", "insufficient_balance", "no_eligible_mint"].includes(attempt.reason)
|
|
4368
|
+
)) {
|
|
4369
|
+
if (attempts.length === 1) return { ...lastFeeCapError, attempts };
|
|
4370
|
+
return {
|
|
4371
|
+
...lastFeeCapError,
|
|
4372
|
+
message: `Every accepted mint that can cover this payment exceeds --max-cashu-fee-sats: ${describeAttempts(attempts)}.`,
|
|
4373
|
+
attempts
|
|
4374
|
+
};
|
|
4375
|
+
}
|
|
4376
|
+
const message = attempts.length === 1 ? `Mint swap failed at ${attempts[0].mint}: ${attempts[0].message}` : `Every mint the DVM accepts failed for this payment: ${describeAttempts(attempts)}.`;
|
|
4264
4377
|
return {
|
|
4265
|
-
|
|
4266
|
-
|
|
4267
|
-
hint:
|
|
4378
|
+
code: "swap_failed",
|
|
4379
|
+
message,
|
|
4380
|
+
hint: inputsLeftInFlight ? "The swap outcome is being recovered from the mint. Run `dvm wallet show` to restore signed outputs or return inputs once the mint confirms they stayed unspent." : "Nothing was spent and the balance is untouched. Retry now \u2014 a mint that's down now is tried again on the next call.",
|
|
4381
|
+
attempts
|
|
4268
4382
|
};
|
|
4269
4383
|
}
|
|
4270
|
-
function
|
|
4271
|
-
return
|
|
4384
|
+
function isSelectionReason(reason) {
|
|
4385
|
+
return reason === "insufficient_balance" || reason === "no_eligible_mint";
|
|
4272
4386
|
}
|
|
4273
|
-
function
|
|
4274
|
-
|
|
4275
|
-
|
|
4276
|
-
|
|
4387
|
+
function describeAttempts(attempts) {
|
|
4388
|
+
return attempts.map((a) => `${a.mint} \u2014 ${a.reason} (${a.message})`).join("; ");
|
|
4389
|
+
}
|
|
4390
|
+
function swapEnabled(cashuWallet) {
|
|
4391
|
+
const loose = cashuWallet;
|
|
4392
|
+
let nuts;
|
|
4277
4393
|
try {
|
|
4278
|
-
|
|
4394
|
+
if (typeof loose.getMintInfo !== "function") return true;
|
|
4395
|
+
nuts = loose.getMintInfo().cache?.nuts;
|
|
4279
4396
|
} catch {
|
|
4280
|
-
return
|
|
4281
|
-
}
|
|
4282
|
-
}
|
|
4283
|
-
function paymentInFlightHint(jobId, job, requestSeq) {
|
|
4284
|
-
const arg = guidanceJobArg(jobId);
|
|
4285
|
-
const resend = `A payment may already have been sent for this request. Resolve it with \`dvm pay ${arg}\`; it checks provider history and re-sends that same payment rather than signing a new one.`;
|
|
4286
|
-
if (!job || requestSeq === void 0) return resend;
|
|
4287
|
-
const submission = job.unconfirmedPaymentSubmissions?.[requestSeq];
|
|
4288
|
-
const stop = `To stop instead, \`dvm decline ${arg}\` ends the job and keeps the finished work, or \`dvm cancel ${arg}\` halts the work now and charges the work in progress.`;
|
|
4289
|
-
if (submission && !submission.blocked) {
|
|
4290
|
-
const resendability = heldPaymentResendability(job, requestSeq);
|
|
4291
|
-
if (resendability === "unreadable")
|
|
4292
|
-
return "The wallet is unreadable, so the earlier Cashu payment cannot be checked or re-sent. Preserve the wallet file; consult `dvm wallet recover --help` for recovery from your backed-up secret. " + unresendablePaymentHint(jobId);
|
|
4293
|
-
return resendability === "resendable" ? resend : `The wallet no longer holds the earlier Cashu payment for this request, so it cannot be re-sent. ${unresendablePaymentHint(jobId)}`;
|
|
4294
|
-
}
|
|
4295
|
-
if (submission?.blocked?.reason === "not_resendable")
|
|
4296
|
-
return `${submission.blocked.detail} ${unresendablePaymentHint(jobId)}`;
|
|
4297
|
-
const askBlock = job.askPaymentBlocks?.[requestSeq];
|
|
4298
|
-
if (askBlock?.reason === "credit_held") {
|
|
4299
|
-
const credit = askBlock.creditId;
|
|
4300
|
-
const drain = `dvm credit drain ${shellQuoteArg(job.dvmId ?? job.endpoint)}${credit ? ` --credit-id ${shellQuoteArg(credit)}` : ""}`;
|
|
4301
|
-
const kept = submission?.rail === "cashu_p2pk" ? `The provider kept the earlier Cashu payment for this charge${credit ? ` as credit ${credit}` : ""} because it fell short` : submission ? `The provider answered that the earlier payment fell short of this charge and may have kept it${credit ? ` as credit ${credit}` : ""}` : `The provider answered that an earlier payment for this charge fell short and may hold it${credit ? ` as credit ${credit}` : ""}`;
|
|
4302
|
-
return `${kept}, so that payment does not pay the charge and is not sent again. Reclaim any balance it holds with \`${drain}\`. Paying the charge takes a new payment that only an explicit \`dvm pay ${arg}\` signs. ${stop}`;
|
|
4397
|
+
return true;
|
|
4303
4398
|
}
|
|
4304
|
-
if (
|
|
4305
|
-
|
|
4306
|
-
return `A payment was already sent for this request and is unconfirmed, and this CLI holds no copy to re-send. ${unresendablePaymentHint(jobId)}`;
|
|
4399
|
+
if (typeof nuts !== "object" || nuts === null) return true;
|
|
4400
|
+
return canSwap(nuts);
|
|
4307
4401
|
}
|
|
4308
|
-
function
|
|
4309
|
-
|
|
4310
|
-
return `No new payment will be signed for this charge while the earlier one is unconfirmed. If the provider records it, \`dvm messages ${job} --wait\` shows the job continue. To stop instead, \`dvm decline ${job}\` ends the job and keeps the finished work, or \`dvm cancel ${job}\` halts the work now and charges the work in progress.`;
|
|
4402
|
+
function errorText(err) {
|
|
4403
|
+
return err instanceof Error ? err.message : String(err);
|
|
4311
4404
|
}
|
|
4312
|
-
|
|
4313
|
-
|
|
4314
|
-
|
|
4315
|
-
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
|
|
4325
|
-
|
|
4326
|
-
|
|
4327
|
-
|
|
4328
|
-
case "prompt": {
|
|
4329
|
-
const c = msg.content;
|
|
4330
|
-
const answer = c.schema ? "--json '<object matching schema>'" : '"<answer>"';
|
|
4331
|
-
const choices = c.options?.length ? ` Choices: ${c.options.map((option) => JSON.stringify(option)).join(", ")}.` : "";
|
|
4332
|
-
const choiceHint = !c.schema && c.options?.length ? " Answer with exactly one of options unless the human chose otherwise." : "";
|
|
4333
|
-
const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Answer" : "Reply", expiresAtMs, nowMs, jobId);
|
|
4334
|
-
const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
|
|
4335
|
-
const action = {
|
|
4336
|
-
type: "respond",
|
|
4337
|
-
job_id: jobId,
|
|
4338
|
-
prompt_id: c.id,
|
|
4339
|
-
prompt: asProviderText(c.text),
|
|
4340
|
-
_provider_fields: [
|
|
4341
|
-
"prompt_id",
|
|
4342
|
-
...c.schema ? ["schema"] : [],
|
|
4343
|
-
...c.options?.length ? ["options"] : []
|
|
4344
|
-
],
|
|
4345
|
-
display: withDeadline(`The provider asks: ${c.text}${choices}`, deadline),
|
|
4346
|
-
hint: expired ? deadline : withDeadline(`Provider is waiting for your input. Verify the question makes sense for your task before responding.${choiceHint} Run \`dvm message ${guidanceJobArg(jobId)} ${answer} --type response --prompt-id '<prompt_id>'\`.`, deadline)
|
|
4347
|
-
};
|
|
4348
|
-
if (c.schema) action.schema = c.schema;
|
|
4349
|
-
if (c.options?.length) action.options = c.options;
|
|
4350
|
-
if (expiresAtMs !== void 0) action.expires_at_ms = expiresAtMs;
|
|
4351
|
-
return action;
|
|
4352
|
-
}
|
|
4353
|
-
case "payment-request": {
|
|
4354
|
-
const c = msg.content;
|
|
4355
|
-
const display = formatPaymentAmount(c.amount_msats, c.fiat_amount);
|
|
4356
|
-
const safeCurrency = !c.fiat_amount || c.fiat_amount.amount <= 0 || c.fiat_amount.currency.length === 3 && /^[A-Z]{3}$/i.test(c.fiat_amount.currency);
|
|
4357
|
-
const priceGuidance = safeCurrency ? display : "see the provider price in next_action.fiat_amount";
|
|
4358
|
-
const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Pay" : "Reply", expiresAtMs, nowMs, jobId);
|
|
4359
|
-
const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
|
|
4360
|
-
const policy = context?.policy;
|
|
4361
|
-
const thresholdHint = !expired && policy && Number.isSafeInteger(c.amount_msats) && c.amount_msats > policy.autoPayBelowMsats && (context?.totalPaidMsats ?? 0) + c.amount_msats <= policy.maxTotalMsats && (policy.maxIncrementMsats === 0 || c.amount_msats <= policy.maxIncrementMsats) ? ` For the next run, use --auto-pay-below ${c.amount_msats} within your approved budget; other payment limits still apply.` : "";
|
|
4362
|
-
const stopping = declineTerms(c);
|
|
4363
|
-
const providerFields2 = [];
|
|
4364
|
-
if (c.fiat_amount && c.fiat_amount.amount > 0) providerFields2.push("fiat_amount");
|
|
4365
|
-
if (stopping?.credit) providerFields2.push("credit");
|
|
4366
|
-
if (stopping) providerFields2.push("charged_if_declined_micro");
|
|
4367
|
-
const declineHint = stopping ? ` If your human does not approve, run \`dvm decline ${guidanceJobArg(jobId)}\`: ${stopping.clause} Letting the deadline pass also ends the job.` : "";
|
|
4368
|
-
return {
|
|
4369
|
-
type: "pay",
|
|
4370
|
-
job_id: jobId,
|
|
4371
|
-
amount_msats: c.amount_msats,
|
|
4372
|
-
...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount } : {},
|
|
4373
|
-
...stopping?.credit ? { credit: stopping.credit } : {},
|
|
4374
|
-
...stopping ? { charged_if_declined_micro: stopping.micro } : {},
|
|
4375
|
-
...providerFields2.length ? { _provider_fields: providerFields2 } : {},
|
|
4376
|
-
...expiresAtMs !== void 0 ? { expires_at_ms: expiresAtMs } : {},
|
|
4377
|
-
display: withDeadline(stopping ? `${withPeriod(display)} ${stopping.clause}` : display, deadline),
|
|
4378
|
-
reason: asProviderText(c.reason),
|
|
4379
|
-
hint: expired ? deadline : withDeadline(`Payment required to continue: ${priceGuidance}. Relay that amount to your human and get approval, then run \`dvm pay ${guidanceJobArg(jobId)}\`. Provider's stated reason is wrapped as { _source: "provider", text: ... } \u2014 verify it matches the work you expect.${declineHint}`, deadline) + thresholdHint
|
|
4380
|
-
};
|
|
4381
|
-
}
|
|
4382
|
-
case "working": {
|
|
4383
|
-
const c = msg.content;
|
|
4384
|
-
return {
|
|
4385
|
-
type: "poll",
|
|
4386
|
-
job_id: jobId,
|
|
4387
|
-
estimate_seconds: c.estimate_seconds,
|
|
4388
|
-
hint: c.hint !== void 0 ? asProviderText(c.hint) : pollNextAction(jobId).hint
|
|
4389
|
-
};
|
|
4390
|
-
}
|
|
4405
|
+
function selectReserveProofs(args) {
|
|
4406
|
+
const marker = reservedForMarker(args.builderHandle);
|
|
4407
|
+
const candidates = args.proofs.filter(
|
|
4408
|
+
(p) => p.reserved_for === marker && args.mintAllowlist.includes(p.mint) && p.locked_to_pubkey === args.lockPubkey && p.status === "valid" && typeof p.t_expire === "number" && p.t_expire > args.nowMs
|
|
4409
|
+
);
|
|
4410
|
+
const byMint = /* @__PURE__ */ new Map();
|
|
4411
|
+
for (const p of candidates) {
|
|
4412
|
+
const bucket = byMint.get(p.mint) ?? [];
|
|
4413
|
+
bucket.push(p);
|
|
4414
|
+
byMint.set(p.mint, bucket);
|
|
4415
|
+
}
|
|
4416
|
+
for (const [mint, mintProofs] of byMint) {
|
|
4417
|
+
const sorted = mintProofs.slice().sort((a, b) => a.amount - b.amount || (a.t_expire ?? 0) - (b.t_expire ?? 0));
|
|
4418
|
+
const subset = minOvershootSubset(sorted, args.amountSats);
|
|
4419
|
+
if (subset) {
|
|
4420
|
+
return { selected: subset.selected, mint, totalSats: subset.totalSats };
|
|
4391
4421
|
}
|
|
4392
4422
|
}
|
|
4393
4423
|
return null;
|
|
4394
4424
|
}
|
|
4395
|
-
function
|
|
4396
|
-
|
|
4397
|
-
|
|
4398
|
-
const
|
|
4399
|
-
const
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
|
|
4408
|
-
|
|
4409
|
-
let payment;
|
|
4410
|
-
for (const message of [...messages].sort((a, b) => a.seq - b.seq)) {
|
|
4411
|
-
if (message.from === "provider" && message.type === "prompt") {
|
|
4412
|
-
prompts.set(message.content.id, validDeadline(message.content.expires_at_ms));
|
|
4413
|
-
} else if (message.from === "requester" && message.type === "response") {
|
|
4414
|
-
prompts.delete(message.content.prompt_id);
|
|
4415
|
-
} else if (message.from === "provider" && message.type === "payment-request") {
|
|
4416
|
-
payment = !answered.has(message.seq) && message.content.amount_msats > 0 ? validDeadline(message.content.expires_at_ms) : void 0;
|
|
4425
|
+
function minOvershootSubset(proofs, amountSats) {
|
|
4426
|
+
if (proofs.length === 0) return null;
|
|
4427
|
+
const maxProof = proofs.reduce((m, p) => Math.max(m, p.amount), 0);
|
|
4428
|
+
const ceiling = amountSats + maxProof;
|
|
4429
|
+
const reachable = /* @__PURE__ */ new Map();
|
|
4430
|
+
reachable.set(0, []);
|
|
4431
|
+
for (let i = 0; i < proofs.length; i++) {
|
|
4432
|
+
const v = proofs[i].amount;
|
|
4433
|
+
const snapshot = Array.from(reachable.entries());
|
|
4434
|
+
for (const [target, indices2] of snapshot) {
|
|
4435
|
+
const next = target + v;
|
|
4436
|
+
if (next > ceiling) continue;
|
|
4437
|
+
if (reachable.has(next)) continue;
|
|
4438
|
+
reachable.set(next, [...indices2, i]);
|
|
4417
4439
|
}
|
|
4418
4440
|
}
|
|
4419
|
-
let
|
|
4420
|
-
for (const
|
|
4421
|
-
if (
|
|
4441
|
+
let bestTarget = -1;
|
|
4442
|
+
for (const t of reachable.keys()) {
|
|
4443
|
+
if (t >= amountSats && (bestTarget === -1 || t < bestTarget)) bestTarget = t;
|
|
4422
4444
|
}
|
|
4423
|
-
return
|
|
4445
|
+
if (bestTarget === -1) return null;
|
|
4446
|
+
const indices = reachable.get(bestTarget) ?? [];
|
|
4447
|
+
return { selected: indices.map((i) => proofs[i]), totalSats: bestTarget };
|
|
4424
4448
|
}
|
|
4425
|
-
|
|
4426
|
-
|
|
4449
|
+
|
|
4450
|
+
// src/lib/taken-payment.ts
|
|
4451
|
+
function midJobSpendLabel(reason) {
|
|
4452
|
+
const text = reason?.trim();
|
|
4453
|
+
return text ? { label: text, labelSource: "provider" } : {};
|
|
4427
4454
|
}
|
|
4428
|
-
function
|
|
4429
|
-
|
|
4430
|
-
|
|
4455
|
+
async function finishBookedSubmission(jobId, booked2, endpoint) {
|
|
4456
|
+
recordSpend({
|
|
4457
|
+
msats: booked2.amountMsats,
|
|
4458
|
+
btcRate: booked2.btcRate,
|
|
4459
|
+
jobId,
|
|
4460
|
+
providerEndpoint: endpoint ?? loadJob(jobId)?.endpoint ?? "",
|
|
4461
|
+
...midJobSpendLabel(booked2.reason)
|
|
4462
|
+
});
|
|
4463
|
+
if (booked2.rail === "cashu_p2pk") await commitHeldSubmission(booked2.cashuRequestId);
|
|
4431
4464
|
}
|
|
4432
|
-
function
|
|
4433
|
-
|
|
4434
|
-
|
|
4435
|
-
|
|
4436
|
-
return `The deadline to ${action.toLowerCase()} (${deadline}) has passed. The provider will probably cancel the job. Check its status with \`dvm status ${guidanceJobArg(jobId)}\`.`;
|
|
4437
|
-
}
|
|
4438
|
-
const minutes = Math.floor((expiresAtMs - nowMs) / 6e4);
|
|
4439
|
-
const hours = Math.floor(minutes / 60);
|
|
4440
|
-
const remaining = expiresAtMs - nowMs > 48 * 36e5 ? `${Math.floor(hours / 24)} days${hours % 24 ? ` ${hours % 24} h` : ""}` : [hours ? `${hours} h` : "", minutes % 60 ? `${minutes % 60} min` : ""].filter(Boolean).join(" ") || "less than 1 min";
|
|
4441
|
-
return `${action} by ${deadline} (in ${remaining}), or the provider cancels the job.`;
|
|
4465
|
+
async function settleTakenPayment(jobId, requestSeq) {
|
|
4466
|
+
const booked2 = markPaymentRequestPaid(jobId, requestSeq);
|
|
4467
|
+
if (booked2) await finishBookedSubmission(jobId, booked2);
|
|
4468
|
+
return booked2;
|
|
4442
4469
|
}
|
|
4443
4470
|
|
|
4444
|
-
// src/lib/
|
|
4445
|
-
|
|
4446
|
-
|
|
4447
|
-
|
|
4448
|
-
|
|
4449
|
-
|
|
4450
|
-
const currency = settlementCurrency(receipt, job, messages, context.currency);
|
|
4451
|
-
const stopped = settlement.pieces.filter((piece) => piece.state === "stopped").reduce((sum, piece) => sum + piece.charged, 0);
|
|
4452
|
-
const callerStop = receipt.outcome === "cancelled" && !job?.callerDeclined && (job?.callerCancelled === true || receipt.ended_by === "caller");
|
|
4453
|
-
const ending = receipt.outcome === "completed" ? "finish" : callerStop ? "stop" : "release";
|
|
4454
|
-
const paid = currency && job && context.messages !== void 0 && settlement.pieces.length > 0 ? paidCeiling(job, messages, settlement, currency, ending) : void 0;
|
|
4455
|
-
const listed = settlement.pieces.length > 0 ? settlement.pieces.filter((piece) => piece.state === "finished" || piece.state === "stopped").reduce((sum, piece) => sum + Math.min(piece.charged, piece.amount), 0) : void 0;
|
|
4456
|
-
const declined = ending === "release" && job ? declineCap(job, messages) : void 0;
|
|
4457
|
-
const bounds = [["payments", paid], ["declined_ask", declined], ["receipt_pieces", listed]].filter((entry) => entry[1] !== void 0);
|
|
4458
|
-
const lowest = bounds.reduce(
|
|
4459
|
-
(best, entry) => best === void 0 || entry[1] < best[1] ? entry : best,
|
|
4460
|
-
void 0
|
|
4461
|
-
);
|
|
4462
|
-
const basis = lowest?.[0];
|
|
4463
|
-
const ceiling = lowest?.[1];
|
|
4464
|
-
const overcharged = ceiling !== void 0 && settlement.charged > ceiling;
|
|
4465
|
-
const money = (micro) => formatMicro(micro, currency);
|
|
4466
|
-
let display = `Charged ${money(settlement.charged)} of ${money(settlement.held)} held, ${money(settlement.released)} released.`;
|
|
4467
|
-
if (overcharged) display += ` ${overchargeClause(basis, money(ceiling))}`;
|
|
4468
|
-
return {
|
|
4469
|
-
held_micro: settlement.held,
|
|
4470
|
-
charged_micro: settlement.charged,
|
|
4471
|
-
released_micro: settlement.released,
|
|
4472
|
-
stopped_micro: stopped,
|
|
4473
|
-
currency,
|
|
4474
|
-
...ceiling !== void 0 ? { ceiling_micro: ceiling, ceiling_basis: basis } : {},
|
|
4475
|
-
overcharged,
|
|
4476
|
-
display
|
|
4477
|
-
};
|
|
4471
|
+
// src/lib/wallet-agent/reclaim-intents.ts
|
|
4472
|
+
var intents = journalFile("reclaim-intents.json");
|
|
4473
|
+
function recordReclaimIntent(intent) {
|
|
4474
|
+
intents.withLock(() => {
|
|
4475
|
+
intents.write([...intents.read().filter((held) => held.requestId !== intent.requestId), intent]);
|
|
4476
|
+
});
|
|
4478
4477
|
}
|
|
4479
|
-
function
|
|
4480
|
-
return
|
|
4478
|
+
function loadReclaimIntent(requestId) {
|
|
4479
|
+
return intents.read().find((intent) => intent.requestId === requestId);
|
|
4481
4480
|
}
|
|
4482
|
-
function
|
|
4483
|
-
|
|
4484
|
-
const units = (micro / 1e6).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 6 });
|
|
4485
|
-
return `${units} ${UNKNOWN_CURRENCY_LABEL}`;
|
|
4481
|
+
function allReclaimIntents() {
|
|
4482
|
+
return intents.read();
|
|
4486
4483
|
}
|
|
4487
|
-
|
|
4488
|
-
|
|
4489
|
-
|
|
4484
|
+
function clearReclaimIntent(requestId, createdAt) {
|
|
4485
|
+
const matches = (held) => held.requestId === requestId && (createdAt === void 0 || held.createdAt === createdAt);
|
|
4486
|
+
if (!intents.read().some(matches)) return;
|
|
4487
|
+
intents.withLock(() => intents.write(intents.read().filter((held) => !matches(held))));
|
|
4490
4488
|
}
|
|
4491
|
-
function
|
|
4492
|
-
|
|
4493
|
-
return `This receipt does not name the currency it was charged in, and no local record of the job's prices or of its credit names one this CLI can show. The amounts are in the provider's credit currency: for a US-dollar credit, 2.06 means $2.06. Run ${describe} to see which currency this DVM's credits use.`;
|
|
4489
|
+
function reclaimIntentIds() {
|
|
4490
|
+
return new Set(intents.read().map((intent) => intent.requestId));
|
|
4494
4491
|
}
|
|
4495
|
-
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4500
|
-
|
|
4501
|
-
|
|
4492
|
+
|
|
4493
|
+
// src/lib/wallet-agent/submission-verdicts.ts
|
|
4494
|
+
var verdictJournal = journalFile("submission-verdicts.json");
|
|
4495
|
+
var readVerdicts = verdictJournal.read;
|
|
4496
|
+
var withVerdictsLock = verdictJournal.withLock;
|
|
4497
|
+
var writeVerdicts = verdictJournal.write;
|
|
4498
|
+
function recordSubmissionVerdicts(verdicts) {
|
|
4499
|
+
if (verdicts.length === 0) return;
|
|
4500
|
+
withVerdictsLock(() => {
|
|
4501
|
+
const journalled = readVerdicts();
|
|
4502
|
+
const reclaimed = new Set(journalled.filter((verdict) => verdict.verdict === "reclaimed").map((verdict) => verdict.requestId));
|
|
4503
|
+
const incoming = verdicts.filter((verdict) => !reclaimed.has(verdict.requestId));
|
|
4504
|
+
const ids = new Set(incoming.map((verdict) => verdict.requestId));
|
|
4505
|
+
writeVerdicts([...journalled.filter((verdict) => !ids.has(verdict.requestId)), ...incoming]);
|
|
4506
|
+
});
|
|
4507
|
+
}
|
|
4508
|
+
async function applySubmissionVerdicts() {
|
|
4509
|
+
let failure;
|
|
4510
|
+
try {
|
|
4511
|
+
finalizeLandedReclaims();
|
|
4512
|
+
} catch (error) {
|
|
4513
|
+
failure = { error };
|
|
4502
4514
|
}
|
|
4503
|
-
|
|
4504
|
-
|
|
4505
|
-
|
|
4506
|
-
|
|
4507
|
-
|
|
4508
|
-
|
|
4509
|
-
|
|
4510
|
-
|
|
4511
|
-
|
|
4512
|
-
|
|
4513
|
-
|
|
4514
|
-
|
|
4515
|
-
|
|
4516
|
-
|
|
4517
|
-
|
|
4518
|
-
|
|
4519
|
-
|
|
4520
|
-
|
|
4521
|
-
|
|
4522
|
-
|
|
4523
|
-
|
|
4524
|
-
|
|
4525
|
-
|
|
4515
|
+
try {
|
|
4516
|
+
await applyJournalledVerdicts();
|
|
4517
|
+
} catch (error) {
|
|
4518
|
+
failure ??= { error };
|
|
4519
|
+
}
|
|
4520
|
+
if (failure) throw failure.error;
|
|
4521
|
+
}
|
|
4522
|
+
async function applyJournalledVerdicts() {
|
|
4523
|
+
const journalled = readVerdicts();
|
|
4524
|
+
if (journalled.length === 0) return;
|
|
4525
|
+
const held = new Set(loadAgentWallet()?.pending_submissions.map((entry) => entry.request_id) ?? []);
|
|
4526
|
+
const landed = journalled.filter((verdict) => !held.has(verdict.requestId));
|
|
4527
|
+
if (landed.length === 0) return;
|
|
4528
|
+
releaseReclaimedSubmissions(new Set(landed.filter((verdict) => verdict.verdict === "reclaimed").map((verdict) => verdict.requestId)));
|
|
4529
|
+
for (const verdict of landed) {
|
|
4530
|
+
if (verdict.verdict === "reclaimed") continue;
|
|
4531
|
+
for (const ask of heldCashuSubmissionAsks(/* @__PURE__ */ new Set([verdict.requestId]))) {
|
|
4532
|
+
if (ask.blocked?.reason === "credit_held") continue;
|
|
4533
|
+
if (verdict.verdict === "spent" && !verdict.reserve) await settleTakenPayment(ask.jobId, ask.requestSeq);
|
|
4534
|
+
else blockHeldPayment(ask.jobId, ask.requestSeq, {
|
|
4535
|
+
reason: "proofs_spent",
|
|
4536
|
+
detail: verdict.verdict === "partly_spent" ? `The provider redeemed ${verdict.spentSats ?? "part"} of the ${verdict.amountSats ?? "?"} sats in the earlier token, and the wallet took back the rest; that is not a payment of this charge.` : "The reserve proofs the earlier token used are spent at the mint and the provider recorded no payment for this charge, but it may already have redeemed this token for this charge, so paying again may pay twice."
|
|
4537
|
+
});
|
|
4538
|
+
}
|
|
4539
|
+
}
|
|
4540
|
+
if (hasUnsavedJobState()) return;
|
|
4541
|
+
const applied = new Set(landed.map((verdict) => verdict.requestId));
|
|
4542
|
+
withVerdictsLock(() => writeVerdicts(readVerdicts().filter((verdict) => !applied.has(verdict.requestId))));
|
|
4543
|
+
}
|
|
4544
|
+
function finalizeLandedReclaims() {
|
|
4545
|
+
const intents2 = allReclaimIntents();
|
|
4546
|
+
if (intents2.length === 0) return;
|
|
4547
|
+
const wallet = loadAgentWallet();
|
|
4548
|
+
if (!wallet) return;
|
|
4549
|
+
const held = new Set(wallet.pending_submissions.map((entry) => entry.request_id));
|
|
4550
|
+
for (const intent of intents2) {
|
|
4551
|
+
if (held.has(intent.requestId)) continue;
|
|
4552
|
+
recordSubmissionVerdicts([intent.verdict]);
|
|
4553
|
+
clearReclaimIntent(intent.requestId, intent.createdAt);
|
|
4554
|
+
}
|
|
4555
|
+
}
|
|
4556
|
+
|
|
4557
|
+
// src/lib/yield-state.ts
|
|
4558
|
+
var JOB_READ_TIMEOUT_MS = 6e4;
|
|
4559
|
+
var PAYMENT_SETTLE_WINDOW_MS = 45e3;
|
|
4560
|
+
function answeredYieldSeqs(messages) {
|
|
4561
|
+
const answered = /* @__PURE__ */ new Set();
|
|
4562
|
+
const prompts = /* @__PURE__ */ new Map();
|
|
4563
|
+
for (const message of [...messages].sort((a, b) => a.seq - b.seq)) {
|
|
4564
|
+
if (message.from === "provider") {
|
|
4565
|
+
if (message.type === "prompt") prompts.set(message.content.id, message.seq);
|
|
4566
|
+
} else if (message.type === "response") {
|
|
4567
|
+
const seq = prompts.get(message.content.prompt_id);
|
|
4568
|
+
if (seq !== void 0) answered.add(seq);
|
|
4526
4569
|
}
|
|
4527
4570
|
}
|
|
4528
|
-
|
|
4529
|
-
return
|
|
4530
|
-
}
|
|
4531
|
-
function declineCap(job, messages) {
|
|
4532
|
-
const ask = messages.findLast((message) => message.from === "provider" && message.type === "payment-request");
|
|
4533
|
-
if (!ask || !validMicro(ask.content.charged_if_declined_micro)) return void 0;
|
|
4534
|
-
const recorded = [
|
|
4535
|
-
...job.paidPaymentRequestSeqs ?? [],
|
|
4536
|
-
...job.inFlightPaymentRequestSeqs ?? [],
|
|
4537
|
-
...(job.bookedCreditPayments ?? []).map((payment) => payment.authorization.request_seq)
|
|
4538
|
-
];
|
|
4539
|
-
if (recorded.some((seq) => seq > ask.seq)) return void 0;
|
|
4540
|
-
const paidAsk = answeredYieldSeqs(messages).has(ask.seq) || recorded.includes(ask.seq);
|
|
4541
|
-
if (!paidAsk) return ask.content.charged_if_declined_micro;
|
|
4542
|
-
const price = ask.content.credit?.amount_micro;
|
|
4543
|
-
return validMicro(price) ? ask.content.charged_if_declined_micro + price : void 0;
|
|
4544
|
-
}
|
|
4545
|
-
function wholeThroughEnd(messages) {
|
|
4546
|
-
if (messages.length === 0 || messages[0].seq > 1) return false;
|
|
4547
|
-
if (!messages.every((message, index) => index === 0 || message.seq === messages[index - 1].seq + 1)) return false;
|
|
4548
|
-
return messages.some((message) => message.type === "complete" || message.type === "cancel" || message.type === "decline");
|
|
4571
|
+
for (const seq of paymentAnswers(messages).keys()) answered.add(seq);
|
|
4572
|
+
return answered;
|
|
4549
4573
|
}
|
|
4550
|
-
function
|
|
4551
|
-
const
|
|
4552
|
-
|
|
4553
|
-
|
|
4554
|
-
if (message.
|
|
4574
|
+
function paymentAnswers(messages) {
|
|
4575
|
+
const answers = /* @__PURE__ */ new Map();
|
|
4576
|
+
let paymentRequest;
|
|
4577
|
+
for (const message of [...messages].sort((a, b) => a.seq - b.seq)) {
|
|
4578
|
+
if (message.from === "provider" && message.type === "payment-request") paymentRequest = message.seq;
|
|
4579
|
+
else if (message.from !== "provider" && message.type === "payment") {
|
|
4580
|
+
const seq = message.content.credit?.request_seq ?? paymentRequest;
|
|
4581
|
+
if (seq !== void 0) answers.set(seq, [...answers.get(seq) ?? [], message]);
|
|
4582
|
+
}
|
|
4555
4583
|
}
|
|
4556
|
-
|
|
4557
|
-
const creditId = receipt.credit?.credit_id;
|
|
4558
|
-
if (creditId) candidates.push(safeCredits().find((credit) => credit.creditId === creditId)?.currency);
|
|
4559
|
-
const found = candidates.find((currency) => typeof currency === "string" && /^[a-z]{3}$/i.test(currency));
|
|
4560
|
-
return found ? found.toLowerCase() : null;
|
|
4584
|
+
return answers;
|
|
4561
4585
|
}
|
|
4562
|
-
function
|
|
4563
|
-
|
|
4564
|
-
|
|
4565
|
-
|
|
4566
|
-
return [];
|
|
4567
|
-
}
|
|
4586
|
+
function carriesSubmission(content, submission) {
|
|
4587
|
+
if (submission.rail === "cashu_p2pk") return content.cashu_request_id === submission.cashuRequestId;
|
|
4588
|
+
const key = submission.rail === "x402" ? "x402_payment" : "tempo_credential";
|
|
4589
|
+
return content[key] !== void 0 && canonicalJson(content[key]) === canonicalJson(submission.content[key]);
|
|
4568
4590
|
}
|
|
4569
|
-
function
|
|
4570
|
-
|
|
4591
|
+
function canonicalJson(value) {
|
|
4592
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
4593
|
+
if (value && typeof value === "object")
|
|
4594
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
|
|
4595
|
+
return JSON.stringify(value);
|
|
4571
4596
|
}
|
|
4572
|
-
function
|
|
4573
|
-
|
|
4597
|
+
async function settleAnsweredAsk(jobId, requestSeq, history) {
|
|
4598
|
+
const submission = loadJob(jobId)?.unconfirmedPaymentSubmissions?.[requestSeq];
|
|
4599
|
+
const payments = paymentAnswers(history).get(requestSeq) ?? [];
|
|
4600
|
+
if (submission && payments.some((payment) => carriesSubmission(payment.content, submission)))
|
|
4601
|
+
await settleTakenPayment(jobId, requestSeq);
|
|
4602
|
+
else markPaymentRequestAnswered(jobId, requestSeq);
|
|
4574
4603
|
}
|
|
4575
|
-
function
|
|
4576
|
-
|
|
4577
|
-
const s = value;
|
|
4578
|
-
return validMicro(s.held) && validMicro(s.charged) && validMicro(s.released) && Array.isArray(s.pieces) && s.pieces.every((piece) => piece && typeof piece === "object" && validMicro(piece.amount) && validMicro(piece.charged) && typeof piece.state === "string");
|
|
4604
|
+
function latestProviderPaymentRequest(messages) {
|
|
4605
|
+
return [...messages].sort((a, b) => a.seq - b.seq).findLast((message) => message.from === "provider" && message.type === "payment-request");
|
|
4579
4606
|
}
|
|
4580
|
-
|
|
4581
|
-
|
|
4582
|
-
|
|
4583
|
-
|
|
4584
|
-
return
|
|
4607
|
+
function pendingPaymentRequest(messages, answered = answeredYieldSeqs(messages)) {
|
|
4608
|
+
const latest = latestProviderPaymentRequest(messages);
|
|
4609
|
+
if (!latest || answered.has(latest.seq)) return void 0;
|
|
4610
|
+
if (messages.some((message) => message.from === "provider" && message.seq > latest.seq && (message.type === "complete" || message.type === "cancel" || message.type === "working"))) return void 0;
|
|
4611
|
+
return latest;
|
|
4585
4612
|
}
|
|
4586
|
-
function
|
|
4587
|
-
|
|
4588
|
-
|
|
4589
|
-
|
|
4590
|
-
|
|
4591
|
-
|
|
4592
|
-
|
|
4593
|
-
display: "Settlement unknown; recorded payments do not prove a final charge or return."
|
|
4594
|
-
};
|
|
4613
|
+
function loadAnsweredYieldSeqs(jobId) {
|
|
4614
|
+
const answered = answeredYieldSeqs(loadMessages(jobId));
|
|
4615
|
+
const job = loadJob(jobId);
|
|
4616
|
+
for (const seq of job?.paidPaymentRequestSeqs ?? []) answered.add(seq);
|
|
4617
|
+
for (const payment of job?.bookedCreditPayments ?? []) answered.add(payment.authorization.request_seq);
|
|
4618
|
+
for (const seq of declinedAskSeqs(jobId)) answered.add(seq);
|
|
4619
|
+
return answered;
|
|
4595
4620
|
}
|
|
4596
|
-
function
|
|
4597
|
-
|
|
4598
|
-
if (verification !== "verified" && verification !== "verified_unattested") return unknownSettlement(rail);
|
|
4599
|
-
const pieces = pieceSettlement(receipt, context);
|
|
4600
|
-
if (pieces && !(receipt.outcome === "completed" && receipt.paid.msats === 0 && pieces.held_micro === 0)) {
|
|
4601
|
-
const whole = receipt.outcome === "completed" && pieces.released_micro === 0;
|
|
4602
|
-
return {
|
|
4603
|
-
status: pieces.charged_micro === 0 ? "released" : "settled",
|
|
4604
|
-
settled_msats: whole ? receipt.paid.msats : pieces.charged_micro === 0 ? 0 : null,
|
|
4605
|
-
...pieces.charged_micro === 0 ? { released_msats: receipt.paid.msats } : {},
|
|
4606
|
-
refunded_msats: 0,
|
|
4607
|
-
rail,
|
|
4608
|
-
evidence: "receipt",
|
|
4609
|
-
held_micro: pieces.held_micro,
|
|
4610
|
-
charged_micro: pieces.charged_micro,
|
|
4611
|
-
released_micro: pieces.released_micro,
|
|
4612
|
-
stopped_micro: pieces.stopped_micro,
|
|
4613
|
-
currency: pieces.currency,
|
|
4614
|
-
...pieces.ceiling_micro !== void 0 ? { ceiling_micro: pieces.ceiling_micro, ceiling_basis: pieces.ceiling_basis } : {},
|
|
4615
|
-
overcharged: pieces.overcharged,
|
|
4616
|
-
display: pieces.display
|
|
4617
|
-
};
|
|
4618
|
-
}
|
|
4619
|
-
const amount = amountDisplay(receipt.paid.msats, rail, rate);
|
|
4620
|
-
if (receipt.outcome === "completed") {
|
|
4621
|
-
return {
|
|
4622
|
-
status: receipt.paid.msats === 0 ? "free" : "settled",
|
|
4623
|
-
settled_msats: receipt.paid.msats,
|
|
4624
|
-
refunded_msats: 0,
|
|
4625
|
-
rail,
|
|
4626
|
-
evidence: "receipt",
|
|
4627
|
-
display: receipt.paid.msats === 0 ? "This was a free job." : `Settled ${amount}${rail ? ` via ${rail}` : ""}.`
|
|
4628
|
-
};
|
|
4629
|
-
}
|
|
4630
|
-
if (receipt.credit) {
|
|
4631
|
-
return {
|
|
4632
|
-
status: "released",
|
|
4633
|
-
settled_msats: 0,
|
|
4634
|
-
released_msats: receipt.paid.msats,
|
|
4635
|
-
refunded_msats: 0,
|
|
4636
|
-
rail,
|
|
4637
|
-
evidence: "receipt",
|
|
4638
|
-
display: `Released ${amount} to the provider credit balance${rail ? ` (funding rail: ${rail})` : ""}; no job charge.`
|
|
4639
|
-
};
|
|
4640
|
-
}
|
|
4641
|
-
return unknownSettlement(rail);
|
|
4621
|
+
function declinedAskSeqs(jobId) {
|
|
4622
|
+
return new Set(loadJob(jobId)?.callerDeclined ? declinedYieldSeqs(loadMessages(jobId)) : []);
|
|
4642
4623
|
}
|
|
4643
|
-
function
|
|
4644
|
-
const
|
|
4645
|
-
const
|
|
4646
|
-
|
|
4647
|
-
const
|
|
4648
|
-
const
|
|
4649
|
-
|
|
4650
|
-
let pending = false;
|
|
4651
|
-
for (const message of inbound) {
|
|
4652
|
-
const amount = job.claimedPaymentAmountsMsats?.[message.seq];
|
|
4653
|
-
if (job.claimedPaymentSeqs?.includes(message.seq) && amount !== void 0 && Number.isSafeInteger(amount) && amount > 0)
|
|
4654
|
-
refunded += amount;
|
|
4655
|
-
else pending = true;
|
|
4656
|
-
}
|
|
4657
|
-
const verified = receipt ? verifyJobReceipt({ receipt, expectedJobId: job.id, builder: job.builderAnchor }) : void 0;
|
|
4658
|
-
const summary = receipt && verified ? receiptSettlement(receipt, verified.status, void 0, { job, messages: log }) : void 0;
|
|
4659
|
-
const matching = receipt?.outcome === job.status;
|
|
4660
|
-
if (!isTerminalJobStatus(job.status)) {
|
|
4661
|
-
return {
|
|
4662
|
-
status: "pending",
|
|
4663
|
-
settled_msats: null,
|
|
4664
|
-
refunded_msats: refunded,
|
|
4665
|
-
rail,
|
|
4666
|
-
evidence: "local",
|
|
4667
|
-
display: "Settlement pending; payments sent or held are not the final job charge."
|
|
4668
|
-
};
|
|
4669
|
-
}
|
|
4670
|
-
if (refunded > 0 || pending) {
|
|
4671
|
-
const soundReceipt = matching && (verified?.status === "verified" || verified?.status === "verified_unattested");
|
|
4672
|
-
const expectedTotal = soundReceipt ? receipt.paid.msats : total;
|
|
4673
|
-
const converted = [
|
|
4674
|
-
rail,
|
|
4675
|
-
job.paymentMethod,
|
|
4676
|
-
job.upfrontPayment?.rail,
|
|
4677
|
-
typeof job.upfrontRailPayment === "object" ? job.upfrontRailPayment.method : void 0
|
|
4678
|
-
].some((method) => method === "tempo" || method === "x402") || log.some((message) => message.from === "requester" && message.type === "payment" && (message.content.tempo_credential || message.content.x402_payment));
|
|
4679
|
-
const full = expectedTotal !== void 0 && expectedTotal > 0 && refunded >= expectedTotal && !converted && (soundReceipt || !hasUnknownUpfrontCredit(job) && !hasUnknownUpfrontRail(job));
|
|
4680
|
-
return {
|
|
4681
|
-
status: full ? "refunded" : pending ? "pending" : "unknown",
|
|
4682
|
-
settled_msats: full ? 0 : null,
|
|
4683
|
-
refunded_msats: refunded,
|
|
4684
|
-
rail: "cashu",
|
|
4685
|
-
evidence: refunded > 0 ? "wallet" : "unknown",
|
|
4686
|
-
display: `${refunded > 0 ? `Refunded ${amountDisplay(refunded, "cashu")} via cashu into your wallet.` : "Refund pending via cashu; no wallet-confirmed amount is recorded."}` + (full ? " No net job charge." : refunded > 0 ? " Final net charge is unknown." : "")
|
|
4687
|
-
};
|
|
4688
|
-
}
|
|
4689
|
-
if (matching && summary && summary.status !== "unknown") return summary;
|
|
4690
|
-
if (summary) return unknownSettlement(rail);
|
|
4691
|
-
if (job.status === "completed" && !hasUnknownUpfrontCredit(job) && !hasUnknownUpfrontRail(job)) {
|
|
4692
|
-
const amount = total ?? 0;
|
|
4693
|
-
return {
|
|
4694
|
-
status: amount === 0 ? "free" : "settled",
|
|
4695
|
-
settled_msats: amount,
|
|
4696
|
-
refunded_msats: 0,
|
|
4697
|
-
rail,
|
|
4698
|
-
evidence: "local",
|
|
4699
|
-
display: amount === 0 ? "This job was free." : `Settled ${amountDisplay(amount, rail)}${rail ? ` via ${rail}` : ""}.`
|
|
4700
|
-
};
|
|
4701
|
-
}
|
|
4702
|
-
return unknownSettlement(rail);
|
|
4624
|
+
function declinedYieldSeqs(messages) {
|
|
4625
|
+
const sorted = [...messages].sort((a, b) => a.seq - b.seq);
|
|
4626
|
+
const decline = sorted.findLast((message) => message.from === "requester" && message.type === "decline");
|
|
4627
|
+
if (!decline) return [];
|
|
4628
|
+
const before = sorted.filter((message) => message.from === "provider" && message.seq < decline.seq);
|
|
4629
|
+
const ask = before.findLast((message) => message.type === "payment-request");
|
|
4630
|
+
return [...ask ? [ask.seq] : [], ...before.filter((message) => message.type === "prompt").map((message) => message.seq)];
|
|
4703
4631
|
}
|
|
4704
|
-
function
|
|
4705
|
-
const
|
|
4706
|
-
const
|
|
4707
|
-
|
|
4708
|
-
const
|
|
4709
|
-
const
|
|
4710
|
-
|
|
4711
|
-
verifyJobReceipt({ receipt: options.receipt, expectedJobId: jobId }).status,
|
|
4712
|
-
void 0,
|
|
4713
|
-
{ currency: options.currency }
|
|
4714
|
-
) : unknownSettlement(null) : jobSettlement(job, options.receipt);
|
|
4715
|
-
const hint = settlementCurrencyHint(settlement, stored?.endpoint || void 0);
|
|
4716
|
-
return { settlement, ...hint ? { settlement_hint: hint } : {} };
|
|
4632
|
+
async function reconcileInFlightPaymentRequest(jobId, requestSeq, transport, provider, options) {
|
|
4633
|
+
const boundedOptions = { ...options, timeoutMs: options.timeoutMs ?? JOB_READ_TIMEOUT_MS };
|
|
4634
|
+
const history = await boundedPaymentRead(jobId, () => transport.getMessages(jobId, 0, provider, boundedOptions), boundedOptions.timeoutMs);
|
|
4635
|
+
const decisionTime = Date.now();
|
|
4636
|
+
const needsStatus = !answeredYieldSeqs(history).has(requestSeq) && decisionTime >= settleUntilMs(jobId, requestSeq, decisionTime);
|
|
4637
|
+
const status = needsStatus ? (await boundedPaymentRead(jobId, () => transport.status(jobId, provider, boundedOptions), boundedOptions.timeoutMs)).status : void 0;
|
|
4638
|
+
return reconcilePaymentRequestHistory(jobId, requestSeq, history, status, () => decisionTime);
|
|
4717
4639
|
}
|
|
4718
|
-
|
|
4719
|
-
|
|
4720
|
-
|
|
4721
|
-
|
|
4722
|
-
switch (status) {
|
|
4723
|
-
case "verified":
|
|
4724
|
-
return `Verified reclaim receipts (${tally}): signed by the key this DVM's builder identity attests.`;
|
|
4725
|
-
case "verified_unattested":
|
|
4726
|
-
return `Reclaim receipts, signed but unattested (${tally}): the signature holds, but this DVM publishes no builder identity to vouch for the signing key.`;
|
|
4727
|
-
case "invalid":
|
|
4728
|
-
return `UNVERIFIED reclaim receipts: only ${tally} hold up \u2014 the refund is still owed, but this evidence is not sound.`;
|
|
4729
|
-
case "absent":
|
|
4730
|
-
return "No reclaim receipts: this DVM returned no signed evidence of the drain.";
|
|
4640
|
+
async function reconcilePaymentRequestHistory(jobId, requestSeq, history, status, now = Date.now) {
|
|
4641
|
+
if (paymentAnswers(history).has(requestSeq)) {
|
|
4642
|
+
await settleAnsweredAsk(jobId, requestSeq, history);
|
|
4643
|
+
return true;
|
|
4731
4644
|
}
|
|
4645
|
+
const superseded = (latestProviderPaymentRequest(history)?.seq ?? -1) > requestSeq;
|
|
4646
|
+
if (superseded) clearPaymentRequestInFlight(jobId, requestSeq);
|
|
4647
|
+
const decisionTime = now();
|
|
4648
|
+
const retryAt = settleUntilMs(jobId, requestSeq, decisionTime);
|
|
4649
|
+
const seconds = Math.ceil((retryAt - decisionTime) / 1e3);
|
|
4650
|
+
if (!superseded && decisionTime < retryAt)
|
|
4651
|
+
throw new DvmError(
|
|
4652
|
+
"payment_settling",
|
|
4653
|
+
"The previous payment may still be processing.",
|
|
4654
|
+
`Retry with \`dvm pay ${shellQuoteArg(jobId)}\` in about ${seconds} ${seconds === 1 ? "second" : "seconds"}, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`,
|
|
4655
|
+
{ retry_at_ms: retryAt }
|
|
4656
|
+
);
|
|
4657
|
+
if (status !== "awaiting-input" || pendingPaymentRequest(history)?.seq !== requestSeq)
|
|
4658
|
+
throw new DvmError(
|
|
4659
|
+
"payment_request_not_pending",
|
|
4660
|
+
"The provider is no longer waiting on this payment request.",
|
|
4661
|
+
`Check the job with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
|
|
4662
|
+
);
|
|
4663
|
+
return false;
|
|
4732
4664
|
}
|
|
4733
|
-
function
|
|
4734
|
-
|
|
4735
|
-
|
|
4736
|
-
|
|
4737
|
-
|
|
4738
|
-
|
|
4739
|
-
|
|
4740
|
-
|
|
4741
|
-
|
|
4742
|
-
|
|
4743
|
-
|
|
4665
|
+
async function settleRecordedPayments(jobId) {
|
|
4666
|
+
await applySubmissionVerdicts().catch(() => void 0);
|
|
4667
|
+
const job = loadJob(jobId);
|
|
4668
|
+
const held = /* @__PURE__ */ new Set([
|
|
4669
|
+
...job?.inFlightPaymentRequestSeqs ?? [],
|
|
4670
|
+
...Object.keys(job?.unconfirmedPaymentSubmissions ?? {}).map(Number)
|
|
4671
|
+
]);
|
|
4672
|
+
for (const seq of job?.paidPaymentRequestSeqs ?? []) held.delete(seq);
|
|
4673
|
+
if (held.size === 0) return;
|
|
4674
|
+
const history = loadMessages(jobId);
|
|
4675
|
+
const answers = paymentAnswers(history);
|
|
4676
|
+
for (const seq of held) if (answers.has(seq)) await settleAnsweredAsk(jobId, seq, history);
|
|
4744
4677
|
}
|
|
4745
|
-
function
|
|
4746
|
-
const
|
|
4747
|
-
|
|
4748
|
-
const settlement = receiptSettlement(receipt, status, rate, context);
|
|
4749
|
-
const payment = settlement.charged_micro !== void 0 ? `Charged ${formatMicro(settlement.charged_micro, settlement.currency ?? null)}` : settlement.status === "settled" ? `Settled ${formatPaid(receipt.paid.msats, rate)}` : settlement.status === "free" ? "free job" : settlement.display.replace(/\.$/, "");
|
|
4750
|
-
return `${VERDICT_PREFIX[status]}: ${payment} for ${what}, ${receipt.outcome}${when ? ` ${when}` : ""}.`;
|
|
4678
|
+
function settleUntilMs(jobId, requestSeq, now) {
|
|
4679
|
+
const startedAt = loadJob(jobId)?.inFlightPaymentRequestStartedAtMs?.[requestSeq];
|
|
4680
|
+
return startedAt === void 0 ? 0 : Math.min(startedAt + PAYMENT_SETTLE_WINDOW_MS, now + PAYMENT_SETTLE_WINDOW_MS);
|
|
4751
4681
|
}
|
|
4752
|
-
function
|
|
4753
|
-
|
|
4754
|
-
|
|
4682
|
+
async function boundedPaymentRead(jobId, read, timeoutMs) {
|
|
4683
|
+
let timer;
|
|
4684
|
+
try {
|
|
4685
|
+
return await Promise.race([read(), new Promise((_, reject) => {
|
|
4686
|
+
timer = setTimeout(() => reject(new DvmError("timeout", "Payment recovery read timed out. No new payment was sent.")), timeoutMs);
|
|
4687
|
+
})]);
|
|
4688
|
+
} catch (error) {
|
|
4689
|
+
if (isAbortError(error) || error instanceof DvmError && error.code === "timeout")
|
|
4690
|
+
throw new DvmError(
|
|
4691
|
+
"timeout",
|
|
4692
|
+
"Payment recovery read timed out. No new payment was sent.",
|
|
4693
|
+
`Retry with \`dvm pay ${shellQuoteArg(jobId)}\` or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`
|
|
4694
|
+
);
|
|
4695
|
+
throw error;
|
|
4696
|
+
} finally {
|
|
4697
|
+
if (timer) clearTimeout(timer);
|
|
4698
|
+
}
|
|
4755
4699
|
}
|
|
4756
|
-
|
|
4757
|
-
|
|
4758
|
-
|
|
4700
|
+
|
|
4701
|
+
// src/lib/next-action.ts
|
|
4702
|
+
function isTerminalJobStatus(status) {
|
|
4703
|
+
return TERMINAL_STATUSES.has(status);
|
|
4759
4704
|
}
|
|
4760
|
-
function
|
|
4761
|
-
|
|
4762
|
-
|
|
4705
|
+
function pollNextAction(jobId, hint) {
|
|
4706
|
+
return {
|
|
4707
|
+
type: "poll",
|
|
4708
|
+
job_id: jobId,
|
|
4709
|
+
hint: hint ?? `Provider is still working. Keep the job moving unattended with \`dvm messages ${guidanceJobArg(jobId)} --wait\`.`
|
|
4710
|
+
};
|
|
4763
4711
|
}
|
|
4764
|
-
function
|
|
4765
|
-
|
|
4766
|
-
|
|
4712
|
+
function heldPaymentResendable(job, requestSeq) {
|
|
4713
|
+
return heldPaymentResendability(job, requestSeq) === "resendable";
|
|
4714
|
+
}
|
|
4715
|
+
function heldPaymentResendability(job, requestSeq) {
|
|
4716
|
+
const submission = job?.unconfirmedPaymentSubmissions?.[requestSeq];
|
|
4717
|
+
if (!submission || submission.blocked) return "unavailable";
|
|
4718
|
+
if (submission.rail !== "cashu_p2pk") return "resendable";
|
|
4719
|
+
try {
|
|
4720
|
+
return loadAgentWallet()?.pending_submissions.some((entry) => entry.request_id === submission.cashuRequestId) ? "resendable" : "unavailable";
|
|
4721
|
+
} catch {
|
|
4722
|
+
return "unreadable";
|
|
4767
4723
|
}
|
|
4768
|
-
return new Date(ms).toISOString();
|
|
4769
4724
|
}
|
|
4770
|
-
function
|
|
4771
|
-
const
|
|
4772
|
-
|
|
4773
|
-
|
|
4774
|
-
|
|
4775
|
-
|
|
4776
|
-
|
|
4777
|
-
|
|
4778
|
-
|
|
4779
|
-
|
|
4780
|
-
|
|
4725
|
+
function paymentInFlightHint(jobId, job, requestSeq) {
|
|
4726
|
+
const arg = guidanceJobArg(jobId);
|
|
4727
|
+
const resend = `A payment may already have been sent for this request. Resolve it with \`dvm pay ${arg}\`; it checks provider history and re-sends that same payment rather than signing a new one.`;
|
|
4728
|
+
if (!job || requestSeq === void 0) return resend;
|
|
4729
|
+
const submission = job.unconfirmedPaymentSubmissions?.[requestSeq];
|
|
4730
|
+
const stop = `To stop instead, \`dvm decline ${arg}\` ends the job and keeps the finished work, or \`dvm cancel ${arg}\` halts the work now and charges the work in progress.`;
|
|
4731
|
+
if (submission && !submission.blocked) {
|
|
4732
|
+
const resendability = heldPaymentResendability(job, requestSeq);
|
|
4733
|
+
if (resendability === "unreadable")
|
|
4734
|
+
return "The wallet is unreadable, so the earlier Cashu payment cannot be checked or re-sent. Preserve the wallet file; consult `dvm wallet recover --help` for recovery from your backed-up secret. " + unresendablePaymentHint(jobId);
|
|
4735
|
+
return resendability === "resendable" ? resend : `The wallet no longer holds the earlier Cashu payment for this request, so it cannot be re-sent. ${unresendablePaymentHint(jobId)}`;
|
|
4736
|
+
}
|
|
4737
|
+
if (submission?.blocked?.reason === "not_resendable")
|
|
4738
|
+
return `${submission.blocked.detail} ${unresendablePaymentHint(jobId)}`;
|
|
4739
|
+
const askBlock = job.askPaymentBlocks?.[requestSeq];
|
|
4740
|
+
if (askBlock?.reason === "credit_held") {
|
|
4741
|
+
const credit = askBlock.creditId;
|
|
4742
|
+
const drain = `dvm credit drain ${shellQuoteArg(job.dvmId ?? job.endpoint)}${credit ? ` --credit-id ${shellQuoteArg(credit)}` : ""}`;
|
|
4743
|
+
const kept = submission?.rail === "cashu_p2pk" ? `The provider kept the earlier Cashu payment for this charge${credit ? ` as credit ${credit}` : ""} because it fell short` : submission ? `The provider answered that the earlier payment fell short of this charge and may have kept it${credit ? ` as credit ${credit}` : ""}` : `The provider answered that an earlier payment for this charge fell short and may hold it${credit ? ` as credit ${credit}` : ""}`;
|
|
4744
|
+
return `${kept}, so that payment does not pay the charge and is not sent again. Reclaim any balance it holds with \`${drain}\`. Paying the charge takes a new payment that only an explicit \`dvm pay ${arg}\` signs. ${stop}`;
|
|
4781
4745
|
}
|
|
4746
|
+
if (askBlock?.reason === "proofs_spent")
|
|
4747
|
+
return `${askBlock.detail ?? "The proofs the earlier Cashu payment used are already spent at the mint; the provider may already have redeemed them for this charge, so paying again may pay twice."} Nothing is sent again or signed automatically. Paying the charge takes a new payment that only an explicit \`dvm pay ${arg}\` signs. ${stop}`;
|
|
4748
|
+
return `A payment was already sent for this request and is unconfirmed, and this CLI holds no copy to re-send. ${unresendablePaymentHint(jobId)}`;
|
|
4782
4749
|
}
|
|
4783
|
-
function
|
|
4784
|
-
|
|
4785
|
-
|
|
4786
|
-
|
|
4787
|
-
|
|
4788
|
-
|
|
4789
|
-
|
|
4790
|
-
|
|
4791
|
-
|
|
4792
|
-
|
|
4793
|
-
|
|
4794
|
-
|
|
4795
|
-
|
|
4796
|
-
|
|
4797
|
-
|
|
4798
|
-
|
|
4799
|
-
|
|
4800
|
-
|
|
4801
|
-
|
|
4802
|
-
|
|
4803
|
-
|
|
4804
|
-
|
|
4805
|
-
|
|
4806
|
-
|
|
4807
|
-
|
|
4808
|
-
|
|
4809
|
-
|
|
4810
|
-
|
|
4811
|
-
|
|
4812
|
-
|
|
4813
|
-
|
|
4814
|
-
|
|
4750
|
+
function unresendablePaymentHint(jobId) {
|
|
4751
|
+
const job = guidanceJobArg(jobId);
|
|
4752
|
+
return `No new payment will be signed for this charge while the earlier one is unconfirmed. If the provider records it, \`dvm messages ${job} --wait\` shows the job continue. To stop instead, \`dvm decline ${job}\` ends the job and keeps the finished work, or \`dvm cancel ${job}\` halts the work now and charges the work in progress.`;
|
|
4753
|
+
}
|
|
4754
|
+
var YIELD_TYPES = /* @__PURE__ */ new Set(["prompt", "payment-request", "working", "complete", "cancel"]);
|
|
4755
|
+
var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
4756
|
+
"completed",
|
|
4757
|
+
"failed",
|
|
4758
|
+
"cancelled"
|
|
4759
|
+
]);
|
|
4760
|
+
function computeNextAction(jobId, messages, nowMs = Date.now(), context) {
|
|
4761
|
+
const answered = answeredYieldSeqs(messages);
|
|
4762
|
+
const expiresAtMs = pendingDeadline(messages, answered);
|
|
4763
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
4764
|
+
const msg = messages[i];
|
|
4765
|
+
if (!YIELD_TYPES.has(msg.type) || answered.has(msg.seq)) continue;
|
|
4766
|
+
switch (msg.type) {
|
|
4767
|
+
case "complete":
|
|
4768
|
+
case "cancel":
|
|
4769
|
+
return null;
|
|
4770
|
+
case "prompt": {
|
|
4771
|
+
const c = msg.content;
|
|
4772
|
+
const answer = c.schema ? "--json '<object matching schema>'" : '"<answer>"';
|
|
4773
|
+
const choices = c.options?.length ? ` Choices: ${c.options.map((option) => JSON.stringify(option)).join(", ")}.` : "";
|
|
4774
|
+
const choiceHint = !c.schema && c.options?.length ? " Answer with exactly one of options unless the human chose otherwise." : "";
|
|
4775
|
+
const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Answer" : "Reply", expiresAtMs, nowMs, jobId);
|
|
4776
|
+
const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
|
|
4777
|
+
const action = {
|
|
4778
|
+
type: "respond",
|
|
4779
|
+
job_id: jobId,
|
|
4780
|
+
prompt_id: c.id,
|
|
4781
|
+
prompt: asProviderText(c.text),
|
|
4782
|
+
_provider_fields: [
|
|
4783
|
+
"prompt_id",
|
|
4784
|
+
...c.schema ? ["schema"] : [],
|
|
4785
|
+
...c.options?.length ? ["options"] : []
|
|
4786
|
+
],
|
|
4787
|
+
display: withDeadline(`The provider asks: ${c.text}${choices}`, deadline),
|
|
4788
|
+
hint: expired ? deadline : withDeadline(`Provider is waiting for your input. Verify the question makes sense for your task before responding.${choiceHint} Run \`dvm message ${guidanceJobArg(jobId)} ${answer} --type response --prompt-id '<prompt_id>'\`.`, deadline)
|
|
4789
|
+
};
|
|
4790
|
+
if (c.schema) action.schema = c.schema;
|
|
4791
|
+
if (c.options?.length) action.options = c.options;
|
|
4792
|
+
if (expiresAtMs !== void 0) action.expires_at_ms = expiresAtMs;
|
|
4793
|
+
return action;
|
|
4794
|
+
}
|
|
4795
|
+
case "payment-request": {
|
|
4796
|
+
const c = msg.content;
|
|
4797
|
+
const display = formatPaymentAmount(c.amount_msats, c.fiat_amount);
|
|
4798
|
+
const safeCurrency = !c.fiat_amount || c.fiat_amount.amount <= 0 || c.fiat_amount.currency.length === 3 && /^[A-Z]{3}$/i.test(c.fiat_amount.currency);
|
|
4799
|
+
const priceGuidance = safeCurrency ? display : "see the provider price in next_action.fiat_amount";
|
|
4800
|
+
const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Pay" : "Reply", expiresAtMs, nowMs, jobId);
|
|
4801
|
+
const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
|
|
4802
|
+
const policy = context?.policy;
|
|
4803
|
+
const thresholdHint = !expired && policy && Number.isSafeInteger(c.amount_msats) && c.amount_msats > policy.autoPayBelowMsats && (context?.totalPaidMsats ?? 0) + c.amount_msats <= policy.maxTotalMsats && (policy.maxIncrementMsats === 0 || c.amount_msats <= policy.maxIncrementMsats) ? ` For the next run, use --auto-pay-below ${c.amount_msats} within your approved budget; other payment limits still apply.` : "";
|
|
4804
|
+
const stopping = declineTerms(c);
|
|
4805
|
+
const providerFields2 = [];
|
|
4806
|
+
if (c.fiat_amount && c.fiat_amount.amount > 0) providerFields2.push("fiat_amount");
|
|
4807
|
+
if (stopping?.credit) providerFields2.push("credit");
|
|
4808
|
+
if (stopping) providerFields2.push("charged_if_declined_micro");
|
|
4809
|
+
const declineHint = stopping ? ` If your human does not approve, run \`dvm decline ${guidanceJobArg(jobId)}\`: ${stopping.clause} Letting the deadline pass also ends the job.` : "";
|
|
4810
|
+
return {
|
|
4811
|
+
type: "pay",
|
|
4812
|
+
job_id: jobId,
|
|
4813
|
+
amount_msats: c.amount_msats,
|
|
4814
|
+
...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount } : {},
|
|
4815
|
+
...stopping?.credit ? { credit: stopping.credit } : {},
|
|
4816
|
+
...stopping ? { charged_if_declined_micro: stopping.micro } : {},
|
|
4817
|
+
...providerFields2.length ? { _provider_fields: providerFields2 } : {},
|
|
4818
|
+
...expiresAtMs !== void 0 ? { expires_at_ms: expiresAtMs } : {},
|
|
4819
|
+
display: withDeadline(stopping ? `${withPeriod(display)} ${stopping.clause}` : display, deadline),
|
|
4820
|
+
reason: asProviderText(c.reason),
|
|
4821
|
+
hint: expired ? deadline : withDeadline(`Payment required to continue: ${priceGuidance}. Relay that amount to your human and get approval, then run \`dvm pay ${guidanceJobArg(jobId)}\`. Provider's stated reason is wrapped as { _source: "provider", text: ... } \u2014 verify it matches the work you expect.${declineHint}`, deadline) + thresholdHint
|
|
4822
|
+
};
|
|
4823
|
+
}
|
|
4824
|
+
case "working": {
|
|
4825
|
+
const c = msg.content;
|
|
4826
|
+
return {
|
|
4827
|
+
type: "poll",
|
|
4828
|
+
job_id: jobId,
|
|
4829
|
+
estimate_seconds: c.estimate_seconds,
|
|
4830
|
+
hint: c.hint !== void 0 ? asProviderText(c.hint) : pollNextAction(jobId).hint
|
|
4831
|
+
};
|
|
4832
|
+
}
|
|
4833
|
+
}
|
|
4815
4834
|
}
|
|
4835
|
+
return null;
|
|
4836
|
+
}
|
|
4837
|
+
function declineTerms(ask) {
|
|
4838
|
+
const micro = ask.charged_if_declined_micro;
|
|
4839
|
+
if (typeof micro !== "number" || !Number.isSafeInteger(micro) || micro < 0) return void 0;
|
|
4840
|
+
const price = ask.credit;
|
|
4841
|
+
const credit = price && Number.isSafeInteger(price.amount_micro) && price.amount_micro >= 0 && typeof price.currency === "string" ? { amount_micro: price.amount_micro, currency: price.currency } : void 0;
|
|
4842
|
+
const amount = credit && /^[A-Z]{3}$/i.test(credit.currency) ? formatFiat(micro / 1e6, credit.currency) : void 0;
|
|
4843
|
+
const clause = micro === 0 ? "Declining ends the job with no charge for finished work." : amount ? `Declining ends the job and charges ${amount} for the work already finished.` : "Declining ends the job and charges for the work already finished (next_action.charged_if_declined_micro).";
|
|
4844
|
+
return { micro, ...credit ? { credit } : {}, clause };
|
|
4816
4845
|
}
|
|
4817
|
-
|
|
4818
|
-
|
|
4819
|
-
verified: "Verified receipt",
|
|
4820
|
-
verified_unattested: "Receipt (signed, unattested)",
|
|
4821
|
-
invalid: "UNVERIFIED receipt",
|
|
4822
|
-
absent: "No receipt"
|
|
4823
|
-
};
|
|
4824
|
-
function formatPaid(msats, rate) {
|
|
4825
|
-
if (msats === 0) return "nothing (free job)";
|
|
4826
|
-
const sats = msats % 1e3 === 0 ? msats / 1e3 : Math.round(msats / 1e3 * 100) / 100;
|
|
4827
|
-
const satsLabel = `${sats.toLocaleString("en-US")} sats`;
|
|
4828
|
-
if (rate <= 0) return satsLabel;
|
|
4829
|
-
const usd2 = msatsToUsd(msats, rate);
|
|
4830
|
-
return `~$${formatUsd(usd2)} (${satsLabel}, ${costAnchor(usd2)})`;
|
|
4846
|
+
function withPeriod(text) {
|
|
4847
|
+
return /[.!?]$/.test(text) ? text : `${text}.`;
|
|
4831
4848
|
}
|
|
4832
|
-
|
|
4833
|
-
|
|
4834
|
-
|
|
4835
|
-
|
|
4836
|
-
|
|
4837
|
-
|
|
4838
|
-
|
|
4839
|
-
|
|
4840
|
-
|
|
4841
|
-
|
|
4842
|
-
|
|
4843
|
-
unlinkSync as unlinkSync2,
|
|
4844
|
-
writeFileSync as writeFileSync5
|
|
4845
|
-
} from "fs";
|
|
4846
|
-
import { dirname as dirname3 } from "path";
|
|
4847
|
-
var DEFAULT_FILE_MODE = 384;
|
|
4848
|
-
function loadFavorites() {
|
|
4849
|
-
let raw;
|
|
4850
|
-
try {
|
|
4851
|
-
raw = readFileSync6(FAVORITES_FILE, "utf8");
|
|
4852
|
-
} catch (error) {
|
|
4853
|
-
if (nodeErrorCode(error) === "ENOENT") return {};
|
|
4854
|
-
throw unreadableFavorites(error);
|
|
4849
|
+
function pendingDeadline(messages, answered) {
|
|
4850
|
+
const prompts = /* @__PURE__ */ new Map();
|
|
4851
|
+
let payment;
|
|
4852
|
+
for (const message of [...messages].sort((a, b) => a.seq - b.seq)) {
|
|
4853
|
+
if (message.from === "provider" && message.type === "prompt") {
|
|
4854
|
+
prompts.set(message.content.id, validDeadline(message.content.expires_at_ms));
|
|
4855
|
+
} else if (message.from === "requester" && message.type === "response") {
|
|
4856
|
+
prompts.delete(message.content.prompt_id);
|
|
4857
|
+
} else if (message.from === "provider" && message.type === "payment-request") {
|
|
4858
|
+
payment = !answered.has(message.seq) && message.content.amount_msats > 0 ? validDeadline(message.content.expires_at_ms) : void 0;
|
|
4859
|
+
}
|
|
4855
4860
|
}
|
|
4856
|
-
|
|
4857
|
-
|
|
4858
|
-
if (
|
|
4859
|
-
return parsed;
|
|
4860
|
-
} catch (error) {
|
|
4861
|
-
throw unreadableFavorites(error);
|
|
4861
|
+
let earliest = payment;
|
|
4862
|
+
for (const deadline of prompts.values()) {
|
|
4863
|
+
if (deadline !== void 0 && (earliest === void 0 || deadline < earliest)) earliest = deadline;
|
|
4862
4864
|
}
|
|
4865
|
+
return earliest;
|
|
4863
4866
|
}
|
|
4864
|
-
|
|
4865
|
-
return
|
|
4866
|
-
const favs = loadFavorites();
|
|
4867
|
-
const existed = Object.hasOwn(favs, alias);
|
|
4868
|
-
favs[alias] = fav;
|
|
4869
|
-
writeFavorites(favs);
|
|
4870
|
-
return existed;
|
|
4871
|
-
});
|
|
4867
|
+
function validDeadline(value) {
|
|
4868
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 864e13 ? value : void 0;
|
|
4872
4869
|
}
|
|
4873
|
-
|
|
4874
|
-
|
|
4875
|
-
|
|
4876
|
-
if (!Object.hasOwn(favs, alias)) return false;
|
|
4877
|
-
const { [alias]: _, ...rest } = favs;
|
|
4878
|
-
writeFavorites(rest);
|
|
4879
|
-
return true;
|
|
4880
|
-
});
|
|
4870
|
+
function withDeadline(display, deadline) {
|
|
4871
|
+
if (!deadline) return display;
|
|
4872
|
+
return `${display}${/[.!?]$/.test(display) ? "" : "."} ${deadline}`;
|
|
4881
4873
|
}
|
|
4882
|
-
function
|
|
4883
|
-
if (
|
|
4884
|
-
const
|
|
4885
|
-
|
|
4886
|
-
|
|
4887
|
-
if (!fav) {
|
|
4888
|
-
throw new DvmError(
|
|
4889
|
-
"unknown_favorite",
|
|
4890
|
-
`No favorite named "${alias}".`,
|
|
4891
|
-
"Run 'dvm fav list' to see saved favorites, or 'dvm fav add <endpoint>' to save one."
|
|
4892
|
-
);
|
|
4874
|
+
function deadlineClause(action, expiresAtMs, nowMs, jobId) {
|
|
4875
|
+
if (expiresAtMs === void 0) return "";
|
|
4876
|
+
const deadline = new Date(expiresAtMs).toISOString().slice(0, 16).replace("T", " ") + " UTC";
|
|
4877
|
+
if (expiresAtMs <= nowMs) {
|
|
4878
|
+
return `The deadline to ${action.toLowerCase()} (${deadline}) has passed. The provider will probably cancel the job. Check its status with \`dvm status ${guidanceJobArg(jobId)}\`.`;
|
|
4893
4879
|
}
|
|
4894
|
-
|
|
4880
|
+
const minutes = Math.floor((expiresAtMs - nowMs) / 6e4);
|
|
4881
|
+
const hours = Math.floor(minutes / 60);
|
|
4882
|
+
const remaining = expiresAtMs - nowMs > 48 * 36e5 ? `${Math.floor(hours / 24)} days${hours % 24 ? ` ${hours % 24} h` : ""}` : [hours ? `${hours} h` : "", minutes % 60 ? `${minutes % 60} min` : ""].filter(Boolean).join(" ") || "less than 1 min";
|
|
4883
|
+
return `${action} by ${deadline} (in ${remaining}), or the provider cancels the job.`;
|
|
4895
4884
|
}
|
|
4896
|
-
|
|
4885
|
+
|
|
4886
|
+
// src/lib/wallet-leftover.ts
|
|
4887
|
+
async function walletRemaining(job) {
|
|
4897
4888
|
try {
|
|
4898
|
-
|
|
4899
|
-
|
|
4900
|
-
|
|
4901
|
-
|
|
4902
|
-
|
|
4903
|
-
|
|
4889
|
+
if (!isTerminalJobStatus(job.status)) return;
|
|
4890
|
+
const payments = loadMessages(job.id).filter((message) => message.type === "payment").filter((message) => message.from === "requester").map((message) => message.content);
|
|
4891
|
+
const suppliedToken = payments.some((payment) => payment.cashu_token && !payment.cashu_request_id);
|
|
4892
|
+
const localRail = payments.map((payment) => payment.credit && !isImplicitCreditId(payment.credit.credit_id) ? "credit" : payment.tempo_credential ? "tempo" : payment.x402_payment ? "x402" : payment.cashu_token && payment.cashu_request_id ? "cashu" : void 0).filter(Boolean).at(-1) ?? job.paymentMethod ?? (typeof job.upfrontRailPayment === "object" ? job.upfrontRailPayment.method : void 0);
|
|
4893
|
+
const creditIds = [job.upfrontPayment?.credit_id, job.receipt?.credit?.credit_id];
|
|
4894
|
+
const callerCredit = job.creditBinding && (!("creditId" in job.creditBinding) || !isImplicitCreditId(job.creditBinding.creditId)) || creditIds.some((id) => id && !isImplicitCreditId(id));
|
|
4895
|
+
const rail = localRail ?? (callerCredit ? "credit" : suppliedToken ? void 0 : job.upfrontPayment?.rail ?? (job.receipt && job.receipt.paid.msats > 0 ? job.receipt.paid.rail : void 0));
|
|
4896
|
+
if (rail === "cashu") {
|
|
4897
|
+
try {
|
|
4898
|
+
if (loadFloat() !== null) return;
|
|
4899
|
+
} catch {
|
|
4900
|
+
}
|
|
4901
|
+
return cashuRemaining();
|
|
4904
4902
|
}
|
|
4905
|
-
|
|
4903
|
+
if (rail !== "x402" && rail !== "tempo") return;
|
|
4904
|
+
return await stablecoinRemaining(rail);
|
|
4906
4905
|
} catch {
|
|
4907
|
-
return
|
|
4906
|
+
return;
|
|
4908
4907
|
}
|
|
4909
4908
|
}
|
|
4910
|
-
|
|
4911
|
-
|
|
4912
|
-
|
|
4913
|
-
|
|
4914
|
-
|
|
4915
|
-
|
|
4916
|
-
|
|
4917
|
-
|
|
4918
|
-
|
|
4919
|
-
|
|
4920
|
-
|
|
4921
|
-
|
|
4922
|
-
|
|
4923
|
-
|
|
4924
|
-
|
|
4925
|
-
);
|
|
4926
|
-
}
|
|
4909
|
+
function cashuRemaining() {
|
|
4910
|
+
const wallet = loadAgentWallet();
|
|
4911
|
+
if (!wallet) return;
|
|
4912
|
+
const proofs = wallet.proofs.filter((proof) => proof.status === "valid" && !proof.reserved_for && (proof.locked_to_pubkey === null || proof.locked_to_pubkey === wallet.lock_pubkey));
|
|
4913
|
+
const sats = proofs.reduce((sum, proof) => sum + proof.amount, 0);
|
|
4914
|
+
if (sats <= 0) return;
|
|
4915
|
+
const cached = getLastKnownBtcRate();
|
|
4916
|
+
const rate = cached && Date.now() - cached.cachedAt <= 24 * 60 * 60 * 1e3 ? cached.rate : void 0;
|
|
4917
|
+
const amount = (value) => rate ? `$${formatUsd(msatsToUsd(value * 1e3, rate))}` : formatSats(value * 1e3);
|
|
4918
|
+
let invoiceSats = 0;
|
|
4919
|
+
for (const mint of new Set(proofs.map((proof) => proof.mint))) {
|
|
4920
|
+
const inputs = proofs.filter((proof) => proof.mint === mint);
|
|
4921
|
+
const fee = localInputFee(mint, inputs.map((proof) => proof.id));
|
|
4922
|
+
if (fee === void 0) continue;
|
|
4923
|
+
const balance = inputs.reduce((sum, proof) => sum + proof.amount, 0);
|
|
4924
|
+
invoiceSats = Math.max(invoiceSats, Math.floor(balance - fee - Math.max(2, balance * 0.01)));
|
|
4925
|
+
}
|
|
4926
|
+
let invoiceUsd;
|
|
4927
|
+
if (rate && invoiceSats > 0) {
|
|
4928
|
+
const cents = Math.floor(msatsToUsd(invoiceSats * 1e3, rate) * 100);
|
|
4929
|
+
invoiceUsd = cents / 100;
|
|
4930
|
+
invoiceSats = Math.ceil(cents * 1e6 / rate);
|
|
4931
|
+
}
|
|
4932
|
+
const canSend = sats > 100;
|
|
4933
|
+
const invoiceDisplay = invoiceUsd === void 0 ? amount(invoiceSats) : `$${formatUsd(invoiceUsd)}`;
|
|
4934
|
+
const offer = invoiceSats > 0 ? ` or an invoice for ${invoiceDisplay}` : "";
|
|
4935
|
+
return {
|
|
4936
|
+
rail: "cashu",
|
|
4937
|
+
amount_sats: sats,
|
|
4938
|
+
...rate ? { usd: amount(sats) } : {},
|
|
4939
|
+
can_send_back: canSend,
|
|
4940
|
+
...canSend ? {
|
|
4941
|
+
...invoiceSats > 0 ? { invoice_amount_sats: invoiceSats } : {},
|
|
4942
|
+
hint: "Run dvm wallet cash-out <lightning-address> --all or dvm wallet cash-out <invoice>."
|
|
4943
|
+
} : {},
|
|
4944
|
+
display: `${amount(sats)} of what you paid is left over from this job. ` + (canSend ? `I can keep it for your next job, or send it back to you; for that I need your Lightning address${offer}.` : "I'll keep it for your next job.")
|
|
4945
|
+
};
|
|
4946
|
+
}
|
|
4947
|
+
async function stablecoinRemaining(rail) {
|
|
4948
|
+
const config = loadConfig();
|
|
4949
|
+
if (config?.[rail]?.generated !== true) return;
|
|
4950
|
+
let timer;
|
|
4927
4951
|
try {
|
|
4928
|
-
|
|
4952
|
+
const balance = await Promise.race([
|
|
4953
|
+
(async () => {
|
|
4954
|
+
if (rail === "x402") {
|
|
4955
|
+
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
|
|
4956
|
+
const wallet = loadX402Wallet2();
|
|
4957
|
+
if (!wallet) return;
|
|
4958
|
+
return (await getX402Balance(await ensureAddress(wallet))).usdc;
|
|
4959
|
+
}
|
|
4960
|
+
const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-OTB2YSWE.js");
|
|
4961
|
+
const account = await connectedTempoAccount2();
|
|
4962
|
+
if (account) return (await getTempoUsdcBalance(account)).usdc;
|
|
4963
|
+
})(),
|
|
4964
|
+
new Promise((resolve) => {
|
|
4965
|
+
timer = setTimeout(resolve, 3e3);
|
|
4966
|
+
})
|
|
4967
|
+
]);
|
|
4968
|
+
if (balance === void 0 || !Number.isFinite(balance) || balance <= 0) return;
|
|
4969
|
+
const usd2 = `$${formatUsd(balance)}`;
|
|
4970
|
+
return {
|
|
4971
|
+
rail,
|
|
4972
|
+
amount_usdc: balance,
|
|
4973
|
+
usd: usd2,
|
|
4974
|
+
can_send_back: false,
|
|
4975
|
+
display: `${usd2} of what you paid is left over from this job. I'll keep it for your next job.`
|
|
4976
|
+
};
|
|
4929
4977
|
} finally {
|
|
4930
|
-
|
|
4978
|
+
clearTimeout(timer);
|
|
4931
4979
|
}
|
|
4932
4980
|
}
|
|
4933
|
-
|
|
4934
|
-
|
|
4935
|
-
|
|
4936
|
-
const
|
|
4937
|
-
|
|
4938
|
-
|
|
4939
|
-
|
|
4940
|
-
|
|
4941
|
-
|
|
4942
|
-
|
|
4943
|
-
|
|
4944
|
-
|
|
4945
|
-
|
|
4946
|
-
|
|
4947
|
-
|
|
4948
|
-
|
|
4949
|
-
|
|
4950
|
-
|
|
4951
|
-
|
|
4981
|
+
|
|
4982
|
+
// src/lib/piece-settlement.ts
|
|
4983
|
+
function pieceSettlement(receipt, context = {}) {
|
|
4984
|
+
const settlement = receipt.settlement;
|
|
4985
|
+
if (!isSettlement(settlement)) return void 0;
|
|
4986
|
+
const job = context.job ?? void 0;
|
|
4987
|
+
const messages = [...context.messages ?? []].sort((a, b) => a.seq - b.seq);
|
|
4988
|
+
const currency = settlementCurrency(receipt, job, messages, context.currency);
|
|
4989
|
+
const stopped = settlement.pieces.filter((piece) => piece.state === "stopped").reduce((sum, piece) => sum + piece.charged, 0);
|
|
4990
|
+
const callerStop = receipt.outcome === "cancelled" && !job?.callerDeclined && (job?.callerCancelled === true || receipt.ended_by === "caller");
|
|
4991
|
+
const ending = receipt.outcome === "completed" ? "finish" : callerStop ? "stop" : "release";
|
|
4992
|
+
const paid = currency && job && context.messages !== void 0 && settlement.pieces.length > 0 ? paidCeiling(job, messages, settlement, currency, ending) : void 0;
|
|
4993
|
+
const listed = settlement.pieces.length > 0 ? settlement.pieces.filter((piece) => piece.state === "finished" || piece.state === "stopped").reduce((sum, piece) => sum + Math.min(piece.charged, piece.amount), 0) : void 0;
|
|
4994
|
+
const declined = ending === "release" && job ? declineCap(job, messages) : void 0;
|
|
4995
|
+
const bounds = [["payments", paid], ["declined_ask", declined], ["receipt_pieces", listed]].filter((entry) => entry[1] !== void 0);
|
|
4996
|
+
const lowest = bounds.reduce(
|
|
4997
|
+
(best, entry) => best === void 0 || entry[1] < best[1] ? entry : best,
|
|
4998
|
+
void 0
|
|
4999
|
+
);
|
|
5000
|
+
const basis = lowest?.[0];
|
|
5001
|
+
const ceiling = lowest?.[1];
|
|
5002
|
+
const overcharged = ceiling !== void 0 && settlement.charged > ceiling;
|
|
5003
|
+
const money = (micro) => formatMicro(micro, currency);
|
|
5004
|
+
let display = `Charged ${money(settlement.charged)} of ${money(settlement.held)} held, ${money(settlement.released)} released.`;
|
|
5005
|
+
if (overcharged) display += ` ${overchargeClause(basis, money(ceiling))}`;
|
|
5006
|
+
return {
|
|
5007
|
+
held_micro: settlement.held,
|
|
5008
|
+
charged_micro: settlement.charged,
|
|
5009
|
+
released_micro: settlement.released,
|
|
5010
|
+
stopped_micro: stopped,
|
|
5011
|
+
currency,
|
|
5012
|
+
...ceiling !== void 0 ? { ceiling_micro: ceiling, ceiling_basis: basis } : {},
|
|
5013
|
+
overcharged,
|
|
5014
|
+
display
|
|
5015
|
+
};
|
|
5016
|
+
}
|
|
5017
|
+
function overchargeClause(basis, ceiling) {
|
|
5018
|
+
return basis === "payments" ? `This charge exceeds the finished pieces this CLI paid for (at most ${ceiling}).` : basis === "declined_ask" ? `This charge exceeds what the job's last ask said stopping would cost (at most ${ceiling}).` : `This charge exceeds what the receipt's own pieces add up to (${ceiling}).`;
|
|
5019
|
+
}
|
|
5020
|
+
function formatMicro(micro, currency) {
|
|
5021
|
+
if (currency) return formatFiat(micro / 1e6, currency);
|
|
5022
|
+
const units = (micro / 1e6).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 6 });
|
|
5023
|
+
return `${units} ${UNKNOWN_CURRENCY_LABEL}`;
|
|
5024
|
+
}
|
|
5025
|
+
var UNKNOWN_CURRENCY_LABEL = "(currency not recorded)";
|
|
5026
|
+
function settlementCurrencyHint(settlement, endpoint) {
|
|
5027
|
+
return settlement?.charged_micro !== void 0 && !settlement.currency ? unknownCurrencyHint(endpoint) : void 0;
|
|
5028
|
+
}
|
|
5029
|
+
function unknownCurrencyHint(endpoint) {
|
|
5030
|
+
const describe = endpoint ? `'dvm describe ${endpoint}'` : "'dvm describe <endpoint>'";
|
|
5031
|
+
return `This receipt does not name the currency it was charged in, and no local record of the job's prices or of its credit names one this CLI can show. The amounts are in the provider's credit currency: for a US-dollar credit, 2.06 means $2.06. Run ${describe} to see which currency this DVM's credits use.`;
|
|
5032
|
+
}
|
|
5033
|
+
function paidCeiling(job, messages, settlement, currency, ending) {
|
|
5034
|
+
let upfront = 0;
|
|
5035
|
+
if (job.upfrontPayment?.amount_micro !== void 0) {
|
|
5036
|
+
if (!sameCurrency(job.upfrontPayment.currency, currency)) return void 0;
|
|
5037
|
+
upfront = job.upfrontPayment.amount_micro;
|
|
5038
|
+
} else if (job.upfrontPayment || settlement.pieces.some((piece) => piece.paid_seq === 0)) {
|
|
5039
|
+
return void 0;
|
|
5040
|
+
}
|
|
5041
|
+
const logged = new Set(messages.filter((message) => message.from === "requester" && message.type === "payment").map((message) => message.seq));
|
|
5042
|
+
if (!wholeThroughEnd(messages) && settlement.pieces.some((piece) => piece.paid_seq !== 0 && !logged.has(piece.paid_seq))) return void 0;
|
|
5043
|
+
let paid = upfront;
|
|
5044
|
+
let finished;
|
|
5045
|
+
let afterAsk = upfront;
|
|
5046
|
+
const asks = /* @__PURE__ */ new Map();
|
|
5047
|
+
let latestAsk;
|
|
5048
|
+
for (const message of messages) {
|
|
5049
|
+
if (message.from === "provider" && message.type === "payment-request") {
|
|
5050
|
+
asks.set(message.seq, message.content);
|
|
5051
|
+
latestAsk = message.seq;
|
|
5052
|
+
const declined = message.content.charged_if_declined_micro;
|
|
5053
|
+
if (validMicro(declined) && sameCurrency(message.content.credit?.currency, currency)) {
|
|
5054
|
+
finished = declined;
|
|
5055
|
+
afterAsk = 0;
|
|
4952
5056
|
}
|
|
5057
|
+
} else if (message.from === "requester" && message.type === "payment") {
|
|
5058
|
+
const credit = message.content.credit;
|
|
5059
|
+
const ask = asks.get(credit?.request_seq ?? latestAsk ?? -1)?.credit;
|
|
5060
|
+
const price = credit ? credit : ask;
|
|
5061
|
+
if (!price || !validMicro(price.amount_micro) || !sameCurrency(price.currency, currency)) return void 0;
|
|
5062
|
+
paid += price.amount_micro;
|
|
5063
|
+
afterAsk += price.amount_micro;
|
|
4953
5064
|
}
|
|
4954
|
-
try {
|
|
4955
|
-
unlinkSync2(temporary);
|
|
4956
|
-
} catch {
|
|
4957
|
-
}
|
|
4958
|
-
throw error;
|
|
4959
5065
|
}
|
|
5066
|
+
if (ending !== "release") return paid;
|
|
5067
|
+
return wholeThroughEnd(messages) ? finished ?? 0 : (finished ?? 0) + afterAsk;
|
|
5068
|
+
}
|
|
5069
|
+
function declineCap(job, messages) {
|
|
5070
|
+
const ask = messages.findLast((message) => message.from === "provider" && message.type === "payment-request");
|
|
5071
|
+
if (!ask || !validMicro(ask.content.charged_if_declined_micro)) return void 0;
|
|
5072
|
+
const recorded = [
|
|
5073
|
+
...job.paidPaymentRequestSeqs ?? [],
|
|
5074
|
+
...job.inFlightPaymentRequestSeqs ?? [],
|
|
5075
|
+
...(job.bookedCreditPayments ?? []).map((payment) => payment.authorization.request_seq)
|
|
5076
|
+
];
|
|
5077
|
+
if (recorded.some((seq) => seq > ask.seq)) return void 0;
|
|
5078
|
+
const paidAsk = answeredYieldSeqs(messages).has(ask.seq) || recorded.includes(ask.seq);
|
|
5079
|
+
if (!paidAsk) return ask.content.charged_if_declined_micro;
|
|
5080
|
+
const price = ask.content.credit?.amount_micro;
|
|
5081
|
+
return validMicro(price) ? ask.content.charged_if_declined_micro + price : void 0;
|
|
4960
5082
|
}
|
|
4961
|
-
function
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
|
|
4965
|
-
|
|
4966
|
-
|
|
5083
|
+
function wholeThroughEnd(messages) {
|
|
5084
|
+
if (messages.length === 0 || messages[0].seq > 1) return false;
|
|
5085
|
+
if (!messages.every((message, index) => index === 0 || message.seq === messages[index - 1].seq + 1)) return false;
|
|
5086
|
+
return messages.some((message) => message.type === "complete" || message.type === "cancel" || message.type === "decline");
|
|
5087
|
+
}
|
|
5088
|
+
function settlementCurrency(receipt, job, messages, hint) {
|
|
5089
|
+
const candidates = [job?.upfrontPayment?.currency];
|
|
5090
|
+
for (const message of [...messages].reverse()) {
|
|
5091
|
+
if (message.type === "payment-request" && message.from === "provider") candidates.push(message.content.credit?.currency);
|
|
5092
|
+
if (message.type === "payment" && message.from === "requester") candidates.push(message.content.credit?.currency);
|
|
4967
5093
|
}
|
|
5094
|
+
candidates.push(hint);
|
|
5095
|
+
const creditId = receipt.credit?.credit_id;
|
|
5096
|
+
if (creditId) candidates.push(safeCredits().find((credit) => credit.creditId === creditId)?.currency);
|
|
5097
|
+
const found = candidates.find((currency) => typeof currency === "string" && /^[a-z]{3}$/i.test(currency));
|
|
5098
|
+
return found ? found.toLowerCase() : null;
|
|
4968
5099
|
}
|
|
4969
|
-
function
|
|
4970
|
-
if (process.platform === "win32") return;
|
|
4971
|
-
const fd = openSync6(path, "r");
|
|
5100
|
+
function safeCredits() {
|
|
4972
5101
|
try {
|
|
4973
|
-
|
|
4974
|
-
}
|
|
4975
|
-
|
|
5102
|
+
return listCredits();
|
|
5103
|
+
} catch {
|
|
5104
|
+
return [];
|
|
4976
5105
|
}
|
|
4977
5106
|
}
|
|
4978
|
-
function
|
|
4979
|
-
return
|
|
4980
|
-
}
|
|
4981
|
-
function unreadableFavorites(error) {
|
|
4982
|
-
return new DvmError(
|
|
4983
|
-
"favorites_unreadable",
|
|
4984
|
-
"Saved favorites are corrupt or unreadable.",
|
|
4985
|
-
`The original file at ${FAVORITES_FILE} was left unchanged. Restore it from a backup, or move it aside before rebuilding favorites.`,
|
|
4986
|
-
{
|
|
4987
|
-
path: FAVORITES_FILE,
|
|
4988
|
-
...nodeErrorCode(error) ? { error_code: nodeErrorCode(error) } : {}
|
|
4989
|
-
}
|
|
4990
|
-
);
|
|
4991
|
-
}
|
|
4992
|
-
function nodeErrorCode(error) {
|
|
4993
|
-
if (!(error instanceof Error) || !("code" in error)) return void 0;
|
|
4994
|
-
const code = error.code;
|
|
4995
|
-
return typeof code === "string" && /^E[A-Z0-9_]{1,63}$/.test(code) ? code : void 0;
|
|
5107
|
+
function sameCurrency(a, b) {
|
|
5108
|
+
return typeof a === "string" && a.toLowerCase() === b;
|
|
4996
5109
|
}
|
|
4997
|
-
function
|
|
4998
|
-
|
|
4999
|
-
return Object.values(value).every(isFavorite);
|
|
5110
|
+
function validMicro(value) {
|
|
5111
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
5000
5112
|
}
|
|
5001
|
-
function
|
|
5002
|
-
if (!value || typeof value !== "object"
|
|
5003
|
-
const
|
|
5004
|
-
return
|
|
5113
|
+
function isSettlement(value) {
|
|
5114
|
+
if (!value || typeof value !== "object") return false;
|
|
5115
|
+
const s = value;
|
|
5116
|
+
return validMicro(s.held) && validMicro(s.charged) && validMicro(s.released) && Array.isArray(s.pieces) && s.pieces.every((piece) => piece && typeof piece === "object" && validMicro(piece.amount) && validMicro(piece.charged) && typeof piece.state === "string");
|
|
5005
5117
|
}
|
|
5006
5118
|
|
|
5007
|
-
// src/lib/job-
|
|
5008
|
-
function
|
|
5009
|
-
const
|
|
5010
|
-
|
|
5011
|
-
return resolveJobAccessWithRecord(jobId, opts, stored);
|
|
5119
|
+
// src/lib/job-settlement.ts
|
|
5120
|
+
function amountDisplay(msats, rail, rate) {
|
|
5121
|
+
const amount = rate === void 0 ? formatPaymentAmount(msats, void 0, { anchor: false }) : rate > 0 ? formatAmount(msats, rate, { anchor: false }) : formatSats(msats);
|
|
5122
|
+
return amount + (rail === "tempo" || rail === "x402" ? " (BTC valuation)" : "");
|
|
5012
5123
|
}
|
|
5013
|
-
function
|
|
5014
|
-
const endpointOverride = opts.endpoint ?? process.env.DVM_JOB_ENDPOINT;
|
|
5015
|
-
const tokenOverride = opts.jobToken ?? process.env.DVM_JOB_TOKEN;
|
|
5016
|
-
const endpointOverridden = endpointOverride !== void 0;
|
|
5017
|
-
const tokenOverridden = tokenOverride !== void 0;
|
|
5018
|
-
const foreign = record !== null && endpointOverride !== void 0 && !sameEndpoint(resolveEndpoint(endpointOverride), record.endpoint);
|
|
5019
|
-
const stored = foreign ? null : record;
|
|
5020
|
-
const rawEndpoint = endpointOverride ?? stored?.endpoint;
|
|
5021
|
-
const jobToken = tokenOverride ?? stored?.jobToken;
|
|
5022
|
-
if (!stored && rawEndpoint === void 0 && jobToken === void 0) {
|
|
5023
|
-
throw new DvmError(
|
|
5024
|
-
"job_access_required",
|
|
5025
|
-
`Job ${jobId} is not in the local store, and no portable job access was supplied.`,
|
|
5026
|
-
"Pass --endpoint <url> and --job-token <hex>, or set DVM_JOB_ENDPOINT and DVM_JOB_TOKEN."
|
|
5027
|
-
);
|
|
5028
|
-
}
|
|
5029
|
-
if (rawEndpoint === void 0) {
|
|
5030
|
-
throw new DvmError(
|
|
5031
|
-
"job_endpoint_required",
|
|
5032
|
-
`No provider endpoint is available for job ${jobId}.`,
|
|
5033
|
-
"Pass --endpoint <url> or set DVM_JOB_ENDPOINT."
|
|
5034
|
-
);
|
|
5035
|
-
}
|
|
5036
|
-
if (foreign && jobToken === void 0) {
|
|
5037
|
-
throw foreignJobTokenRequired(jobId, record.endpoint, resolveEndpoint(endpointOverride));
|
|
5038
|
-
}
|
|
5039
|
-
if (!stored && jobToken === void 0) {
|
|
5040
|
-
throw new DvmError(
|
|
5041
|
-
"job_token_required",
|
|
5042
|
-
`No job token is available for job ${jobId}.`,
|
|
5043
|
-
"Pass --job-token <hex> or set DVM_JOB_TOKEN."
|
|
5044
|
-
);
|
|
5045
|
-
}
|
|
5046
|
-
if (tokenOverridden && !isJobToken(jobToken)) {
|
|
5047
|
-
throw new DvmError(
|
|
5048
|
-
"invalid_job_token",
|
|
5049
|
-
"The supplied job token is not a 64-character hexadecimal value.",
|
|
5050
|
-
"Copy the job_token returned when the job was submitted; the value is never printed by this command."
|
|
5051
|
-
);
|
|
5052
|
-
}
|
|
5124
|
+
function unknownSettlement(rail) {
|
|
5053
5125
|
return {
|
|
5054
|
-
|
|
5055
|
-
|
|
5056
|
-
|
|
5057
|
-
|
|
5058
|
-
|
|
5126
|
+
status: "unknown",
|
|
5127
|
+
settled_msats: null,
|
|
5128
|
+
refunded_msats: 0,
|
|
5129
|
+
rail,
|
|
5130
|
+
evidence: "unknown",
|
|
5131
|
+
display: "Settlement unknown; recorded payments do not prove a final charge or return."
|
|
5059
5132
|
};
|
|
5060
5133
|
}
|
|
5061
|
-
function
|
|
5062
|
-
const
|
|
5063
|
-
if (
|
|
5064
|
-
|
|
5065
|
-
|
|
5066
|
-
|
|
5067
|
-
|
|
5068
|
-
|
|
5134
|
+
function receiptSettlement(receipt, verification, rate, context) {
|
|
5135
|
+
const rail = receipt.paid.rail;
|
|
5136
|
+
if (verification !== "verified" && verification !== "verified_unattested") return unknownSettlement(rail);
|
|
5137
|
+
const pieces = pieceSettlement(receipt, context);
|
|
5138
|
+
if (pieces && !(receipt.outcome === "completed" && receipt.paid.msats === 0 && pieces.held_micro === 0)) {
|
|
5139
|
+
const whole = receipt.outcome === "completed" && pieces.released_micro === 0;
|
|
5140
|
+
return {
|
|
5141
|
+
status: pieces.charged_micro === 0 ? "released" : "settled",
|
|
5142
|
+
settled_msats: whole ? receipt.paid.msats : pieces.charged_micro === 0 ? 0 : null,
|
|
5143
|
+
...pieces.charged_micro === 0 ? { released_msats: receipt.paid.msats } : {},
|
|
5144
|
+
refunded_msats: 0,
|
|
5145
|
+
rail,
|
|
5146
|
+
evidence: "receipt",
|
|
5147
|
+
held_micro: pieces.held_micro,
|
|
5148
|
+
charged_micro: pieces.charged_micro,
|
|
5149
|
+
released_micro: pieces.released_micro,
|
|
5150
|
+
stopped_micro: pieces.stopped_micro,
|
|
5151
|
+
currency: pieces.currency,
|
|
5152
|
+
...pieces.ceiling_micro !== void 0 ? { ceiling_micro: pieces.ceiling_micro, ceiling_basis: pieces.ceiling_basis } : {},
|
|
5153
|
+
overcharged: pieces.overcharged,
|
|
5154
|
+
display: pieces.display
|
|
5155
|
+
};
|
|
5069
5156
|
}
|
|
5070
|
-
|
|
5071
|
-
|
|
5072
|
-
|
|
5073
|
-
|
|
5074
|
-
|
|
5075
|
-
|
|
5076
|
-
|
|
5157
|
+
const amount = amountDisplay(receipt.paid.msats, rail, rate);
|
|
5158
|
+
if (receipt.outcome === "completed") {
|
|
5159
|
+
return {
|
|
5160
|
+
status: receipt.paid.msats === 0 ? "free" : "settled",
|
|
5161
|
+
settled_msats: receipt.paid.msats,
|
|
5162
|
+
refunded_msats: 0,
|
|
5163
|
+
rail,
|
|
5164
|
+
evidence: "receipt",
|
|
5165
|
+
display: receipt.paid.msats === 0 ? "This was a free job." : `Settled ${amount}${rail ? ` via ${rail}` : ""}.`
|
|
5166
|
+
};
|
|
5077
5167
|
}
|
|
5168
|
+
if (receipt.credit) {
|
|
5169
|
+
return {
|
|
5170
|
+
status: "released",
|
|
5171
|
+
settled_msats: 0,
|
|
5172
|
+
released_msats: receipt.paid.msats,
|
|
5173
|
+
refunded_msats: 0,
|
|
5174
|
+
rail,
|
|
5175
|
+
evidence: "receipt",
|
|
5176
|
+
display: `Released ${amount} to the provider credit balance${rail ? ` (funding rail: ${rail})` : ""}; no job charge.`
|
|
5177
|
+
};
|
|
5178
|
+
}
|
|
5179
|
+
return unknownSettlement(rail);
|
|
5078
5180
|
}
|
|
5079
|
-
function
|
|
5080
|
-
|
|
5081
|
-
const
|
|
5082
|
-
|
|
5083
|
-
|
|
5084
|
-
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
|
|
5088
|
-
|
|
5089
|
-
|
|
5090
|
-
|
|
5091
|
-
|
|
5092
|
-
|
|
5093
|
-
|
|
5094
|
-
|
|
5095
|
-
|
|
5096
|
-
|
|
5097
|
-
{
|
|
5098
|
-
|
|
5099
|
-
|
|
5100
|
-
|
|
5101
|
-
|
|
5102
|
-
|
|
5103
|
-
|
|
5104
|
-
}
|
|
5105
|
-
|
|
5106
|
-
|
|
5107
|
-
|
|
5108
|
-
|
|
5109
|
-
|
|
5110
|
-
|
|
5181
|
+
function jobSettlement(job, offeredReceipt) {
|
|
5182
|
+
const receipt = offeredReceipt ?? (isSignedJobReceipt(job.receipt) ? job.receipt : void 0);
|
|
5183
|
+
const rail = receipt?.paid.rail ?? job.upfrontPayment?.rail ?? job.paymentMethod ?? null;
|
|
5184
|
+
const total = job.totalPaidMsats ?? job.costMsats;
|
|
5185
|
+
const log = loadMessages(job.id);
|
|
5186
|
+
const inbound = log.filter((message) => message.from === "provider" && message.type === "payment" && message.content.cashu_token && (message.content.reason ?? "refund") === "refund");
|
|
5187
|
+
let refunded = 0;
|
|
5188
|
+
let pending = false;
|
|
5189
|
+
for (const message of inbound) {
|
|
5190
|
+
const amount = job.claimedPaymentAmountsMsats?.[message.seq];
|
|
5191
|
+
if (job.claimedPaymentSeqs?.includes(message.seq) && amount !== void 0 && Number.isSafeInteger(amount) && amount > 0)
|
|
5192
|
+
refunded += amount;
|
|
5193
|
+
else pending = true;
|
|
5194
|
+
}
|
|
5195
|
+
const verified = receipt ? verifyJobReceipt({ receipt, expectedJobId: job.id, builder: job.builderAnchor }) : void 0;
|
|
5196
|
+
const summary = receipt && verified ? receiptSettlement(receipt, verified.status, void 0, { job, messages: log }) : void 0;
|
|
5197
|
+
const matching = receipt?.outcome === job.status;
|
|
5198
|
+
if (!isTerminalJobStatus(job.status)) {
|
|
5199
|
+
return {
|
|
5200
|
+
status: "pending",
|
|
5201
|
+
settled_msats: null,
|
|
5202
|
+
refunded_msats: refunded,
|
|
5203
|
+
rail,
|
|
5204
|
+
evidence: "local",
|
|
5205
|
+
display: "Settlement pending; payments sent or held are not the final job charge."
|
|
5206
|
+
};
|
|
5207
|
+
}
|
|
5208
|
+
if (refunded > 0 || pending) {
|
|
5209
|
+
const soundReceipt = matching && (verified?.status === "verified" || verified?.status === "verified_unattested");
|
|
5210
|
+
const expectedTotal = soundReceipt ? receipt.paid.msats : total;
|
|
5211
|
+
const converted = [
|
|
5212
|
+
rail,
|
|
5213
|
+
job.paymentMethod,
|
|
5214
|
+
job.upfrontPayment?.rail,
|
|
5215
|
+
typeof job.upfrontRailPayment === "object" ? job.upfrontRailPayment.method : void 0
|
|
5216
|
+
].some((method) => method === "tempo" || method === "x402") || log.some((message) => message.from === "requester" && message.type === "payment" && (message.content.tempo_credential || message.content.x402_payment));
|
|
5217
|
+
const full = expectedTotal !== void 0 && expectedTotal > 0 && refunded >= expectedTotal && !converted && (soundReceipt || !hasUnknownUpfrontCredit(job) && !hasUnknownUpfrontRail(job));
|
|
5218
|
+
return {
|
|
5219
|
+
status: full ? "refunded" : pending ? "pending" : "unknown",
|
|
5220
|
+
settled_msats: full ? 0 : null,
|
|
5221
|
+
refunded_msats: refunded,
|
|
5222
|
+
rail: "cashu",
|
|
5223
|
+
evidence: refunded > 0 ? "wallet" : "unknown",
|
|
5224
|
+
display: `${refunded > 0 ? `Refunded ${amountDisplay(refunded, "cashu")} via cashu into your wallet.` : "Refund pending via cashu; no wallet-confirmed amount is recorded."}` + (full ? " No net job charge." : refunded > 0 ? " Final net charge is unknown." : "")
|
|
5225
|
+
};
|
|
5111
5226
|
}
|
|
5112
|
-
return
|
|
5113
|
-
|
|
5114
|
-
|
|
5227
|
+
if (matching && summary && summary.status !== "unknown") return summary;
|
|
5228
|
+
if (summary) return unknownSettlement(rail);
|
|
5229
|
+
if (job.status === "completed" && !hasUnknownUpfrontCredit(job) && !hasUnknownUpfrontRail(job)) {
|
|
5230
|
+
const amount = total ?? 0;
|
|
5231
|
+
return {
|
|
5232
|
+
status: amount === 0 ? "free" : "settled",
|
|
5233
|
+
settled_msats: amount,
|
|
5234
|
+
refunded_msats: 0,
|
|
5235
|
+
rail,
|
|
5236
|
+
evidence: "local",
|
|
5237
|
+
display: amount === 0 ? "This job was free." : `Settled ${amountDisplay(amount, rail)}${rail ? ` via ${rail}` : ""}.`
|
|
5238
|
+
};
|
|
5239
|
+
}
|
|
5240
|
+
return unknownSettlement(rail);
|
|
5115
5241
|
}
|
|
5116
|
-
function
|
|
5117
|
-
|
|
5242
|
+
function terminalSettlementFields(jobId, options = {}) {
|
|
5243
|
+
const stored = options.persistLocalState === false ? null : loadJob(jobId);
|
|
5244
|
+
const status = options.status ?? stored?.status ?? options.receipt?.outcome;
|
|
5245
|
+
if (!status || !isTerminalJobStatus(status)) return {};
|
|
5246
|
+
const job = stored ? { ...stored, status } : { id: jobId, endpoint: "", submittedAt: 0, status };
|
|
5247
|
+
const settlement = options.persistLocalState === false ? options.receipt && options.receipt.outcome === status ? receiptSettlement(
|
|
5248
|
+
options.receipt,
|
|
5249
|
+
verifyJobReceipt({ receipt: options.receipt, expectedJobId: jobId }).status,
|
|
5250
|
+
void 0,
|
|
5251
|
+
{ currency: options.currency }
|
|
5252
|
+
) : unknownSettlement(null) : jobSettlement(job, options.receipt);
|
|
5253
|
+
const hint = settlementCurrencyHint(settlement, stored?.endpoint || void 0);
|
|
5254
|
+
return { settlement, ...hint ? { settlement_hint: hint } : {} };
|
|
5118
5255
|
}
|
|
5119
|
-
function
|
|
5120
|
-
|
|
5121
|
-
|
|
5122
|
-
|
|
5123
|
-
}
|
|
5124
|
-
}
|
|
5125
|
-
throw new DvmError(
|
|
5126
|
-
"invalid_endpoint",
|
|
5127
|
-
"The supplied job endpoint is not a valid HTTP(S) provider URL.",
|
|
5128
|
-
"Pass a full URL such as https://provider.example, or a favorite alias such as @provider."
|
|
5129
|
-
);
|
|
5256
|
+
async function terminalSettlementReport(jobId, options = {}) {
|
|
5257
|
+
const fields = terminalSettlementFields(jobId, options);
|
|
5258
|
+
if (!fields.settlement || options.persistLocalState === false) return fields;
|
|
5259
|
+
const stored = loadJob(jobId);
|
|
5260
|
+
const remaining = stored ? await walletRemaining({ ...stored, ...options.receipt ? { receipt: options.receipt } : {}, status: options.status ?? stored.status }) : void 0;
|
|
5261
|
+
return { ...fields, ...remaining ? { wallet_remaining: remaining } : {} };
|
|
5130
5262
|
}
|
|
5131
|
-
|
|
5132
|
-
|
|
5133
|
-
|
|
5134
|
-
)
|
|
5263
|
+
|
|
5264
|
+
// src/lib/receipt-verify.ts
|
|
5265
|
+
function drainReceiptsDisplay(status, sound, total) {
|
|
5266
|
+
const tally = `${String(sound)} of ${String(total)}`;
|
|
5267
|
+
switch (status) {
|
|
5268
|
+
case "verified":
|
|
5269
|
+
return `Verified reclaim receipts (${tally}): signed by the key this DVM's builder identity attests.`;
|
|
5270
|
+
case "verified_unattested":
|
|
5271
|
+
return `Reclaim receipts, signed but unattested (${tally}): the signature holds, but this DVM publishes no builder identity to vouch for the signing key.`;
|
|
5272
|
+
case "invalid":
|
|
5273
|
+
return `UNVERIFIED reclaim receipts: only ${tally} hold up \u2014 the refund is still owed, but this evidence is not sound.`;
|
|
5274
|
+
case "absent":
|
|
5275
|
+
return "No reclaim receipts: this DVM returned no signed evidence of the drain.";
|
|
5276
|
+
}
|
|
5135
5277
|
}
|
|
5136
|
-
function
|
|
5137
|
-
|
|
5138
|
-
|
|
5139
|
-
|
|
5140
|
-
|
|
5278
|
+
function drainReceiptsHint(status) {
|
|
5279
|
+
switch (status) {
|
|
5280
|
+
case "verified":
|
|
5281
|
+
return "The refund evidence chains to this DVM's published builder identity, and is stored locally with that identity pinned beside it \u2014 so an unhonoured refund stays provable against the builder, not against an anonymous key.";
|
|
5282
|
+
case "verified_unattested":
|
|
5283
|
+
return "The receipts are signed, but nothing vouches for the signing key \u2014 expected for a locally-run or development DVM, not for a deployed one. Stored either way; the refund is owed regardless.";
|
|
5284
|
+
case "invalid":
|
|
5285
|
+
return "The refund is unaffected \u2014 this is a problem with the proof, not the money. Keep this output, and treat the reclaim as unattested when deciding how much to leave on deposit at this DVM.";
|
|
5286
|
+
case "absent":
|
|
5287
|
+
return "This DVM countersigned nothing, so the only artifact behind this reclaim is the drain request the caller signed. Weaker evidence than a countersigned drain, and worth weighing before funding here again.";
|
|
5141
5288
|
}
|
|
5142
|
-
return value;
|
|
5143
5289
|
}
|
|
5144
|
-
|
|
5145
|
-
|
|
5146
|
-
|
|
5147
|
-
|
|
5290
|
+
function receiptDisplay(receipt, status, rate = 0, context = receiptPieceContext(receipt)) {
|
|
5291
|
+
const what = `${receipt.dvm}/${receipt.capability} (DVM ID ${receipt.dvm_id})`;
|
|
5292
|
+
const when = receiptIssuedAtIso(receipt)?.slice(0, 10);
|
|
5293
|
+
const settlement = receiptSettlement(receipt, status, rate, context);
|
|
5294
|
+
const payment = settlement.charged_micro !== void 0 ? `Charged ${formatMicro(settlement.charged_micro, settlement.currency ?? null)}` : settlement.status === "settled" ? `Settled ${formatPaid(receipt.paid.msats, rate)}` : settlement.status === "free" ? "free job" : settlement.display.replace(/\.$/, "");
|
|
5295
|
+
return `${VERDICT_PREFIX[status]}: ${payment} for ${what}, ${receipt.outcome}${when ? ` ${when}` : ""}.`;
|
|
5148
5296
|
}
|
|
5149
|
-
|
|
5150
|
-
|
|
5151
|
-
|
|
5152
|
-
draw_id_mismatch: "draw_id",
|
|
5153
|
-
fund_id_mismatch: "fund_id",
|
|
5154
|
-
caller_pubkey_mismatch: "caller_pubkey"
|
|
5155
|
-
};
|
|
5156
|
-
function nextAction(job) {
|
|
5157
|
-
return `Nothing is owed or lost: the job's terminal receipt still decides the charge. Refresh your credit balances with \`dvm credit balance ${shellQuoteArg(job.endpoint)}\` once the job ends; if this repeats, report job ${JSON.stringify(job.id)} and the reason to the provider.`;
|
|
5297
|
+
function receiptPieceContext(receipt, currency) {
|
|
5298
|
+
const job = loadJob(receipt.job_id);
|
|
5299
|
+
return { job, messages: job ? loadMessages(receipt.job_id) : void 0, ...currency ? { currency } : {} };
|
|
5158
5300
|
}
|
|
5159
|
-
function
|
|
5160
|
-
const
|
|
5161
|
-
|
|
5162
|
-
return { kind: "invalid", reason, hint: `${detail} ${nextAction(job)}` };
|
|
5301
|
+
function receiptCurrencyHint(receipt, status, context, endpoint) {
|
|
5302
|
+
const settlement = receiptSettlement(receipt, status, void 0, context);
|
|
5303
|
+
return settlement.charged_micro !== void 0 && !settlement.currency ? unknownCurrencyHint(endpoint) : void 0;
|
|
5163
5304
|
}
|
|
5164
|
-
function
|
|
5165
|
-
|
|
5166
|
-
return
|
|
5305
|
+
function receiptIssuedAtIso(receipt) {
|
|
5306
|
+
const seconds = receipt.issued_at;
|
|
5307
|
+
return typeof seconds === "number" ? epochMsToIso(seconds * 1e3) : null;
|
|
5167
5308
|
}
|
|
5168
|
-
function
|
|
5169
|
-
if (!
|
|
5170
|
-
|
|
5171
|
-
if (!binding || "unbound" in binding) {
|
|
5172
|
-
if (isImplicitCreditId(receipt.credit_id)) {
|
|
5173
|
-
const expected2 = { job_id: job.id, ...fundId ? { fund_id: fundId } : {} };
|
|
5174
|
-
const reason2 = verdictReason(verifyDrawFundingReceiptChain({
|
|
5175
|
-
receipt,
|
|
5176
|
-
builder: job.builderAnchor,
|
|
5177
|
-
expectedJobId: job.id,
|
|
5178
|
-
...fundId ? { expectedFundId: fundId } : {}
|
|
5179
|
-
}));
|
|
5180
|
-
return reason2 ? invalidFunding(job, receipt, reason2, expected2) : { kind: "not_applicable" };
|
|
5181
|
-
}
|
|
5182
|
-
return {
|
|
5183
|
-
kind: "invalid",
|
|
5184
|
-
reason: "no_bound_draw",
|
|
5185
|
-
hint: `The provider signed funding for credit ${JSON.stringify(receipt.credit_id)}, but this job records no draw on it, so the local balance of that credit was not reconciled. ${nextAction(job)}`
|
|
5186
|
-
};
|
|
5309
|
+
function epochMsToIso(ms) {
|
|
5310
|
+
if (typeof ms !== "number" || !Number.isFinite(ms) || Math.abs(ms) > MAX_TIMESTAMP_MS) {
|
|
5311
|
+
return null;
|
|
5187
5312
|
}
|
|
5188
|
-
|
|
5189
|
-
job_id: job.id,
|
|
5190
|
-
credit_id: binding.creditId,
|
|
5191
|
-
draw_id: binding.drawId,
|
|
5192
|
-
caller_pubkey: binding.callerPubkey,
|
|
5193
|
-
...fundId ? { fund_id: fundId } : {}
|
|
5194
|
-
};
|
|
5195
|
-
const reason = verdictReason(verifyDrawFundingReceiptChain({
|
|
5196
|
-
receipt,
|
|
5197
|
-
builder: job.builderAnchor,
|
|
5198
|
-
expectedJobId: job.id,
|
|
5199
|
-
expectedCreditId: binding.creditId,
|
|
5200
|
-
expectedDrawId: binding.drawId,
|
|
5201
|
-
expectedCallerPubkey: binding.callerPubkey,
|
|
5202
|
-
...fundId ? { expectedFundId: fundId } : {}
|
|
5203
|
-
}));
|
|
5204
|
-
return reason ? invalidFunding(job, receipt, reason, expected) : { kind: "verified", receipt };
|
|
5313
|
+
return new Date(ms).toISOString();
|
|
5205
5314
|
}
|
|
5206
|
-
function
|
|
5207
|
-
const
|
|
5208
|
-
|
|
5315
|
+
function receiptHint(status, jobId) {
|
|
5316
|
+
const verifyCmd = jobId ? `'dvm receipts verify ${jobId}'` : "'dvm receipts verify <job-id>'";
|
|
5317
|
+
switch (status) {
|
|
5318
|
+
case "verified":
|
|
5319
|
+
return `Proof of purchase is stored locally. Re-check it any time with ${verifyCmd}, or hand over the raw bundle with 'dvm receipts export'.`;
|
|
5320
|
+
case "verified_unattested":
|
|
5321
|
+
return `The receipt's signature is valid, but this DVM publishes no builder identity to vouch for the signing key \u2014 expected for a locally-run or development DVM, not for a deployed one. Stored either way; inspect it with ${verifyCmd}.`;
|
|
5322
|
+
case "invalid":
|
|
5323
|
+
return `The job itself is unaffected \u2014 this is a problem with the proof, not the result. Run ${verifyCmd} to see which check failed before relying on this receipt as evidence.`;
|
|
5324
|
+
case "absent":
|
|
5325
|
+
return "This DVM does not issue signed receipts, so there is no proof of purchase to store. Nothing went wrong.";
|
|
5326
|
+
}
|
|
5209
5327
|
}
|
|
5210
|
-
function
|
|
5211
|
-
|
|
5212
|
-
|
|
5213
|
-
|
|
5214
|
-
|
|
5215
|
-
|
|
5216
|
-
|
|
5217
|
-
|
|
5218
|
-
|
|
5219
|
-
|
|
5220
|
-
|
|
5221
|
-
|
|
5222
|
-
|
|
5223
|
-
|
|
5224
|
-
|
|
5225
|
-
|
|
5226
|
-
|
|
5227
|
-
|
|
5228
|
-
|
|
5229
|
-
|
|
5230
|
-
|
|
5231
|
-
|
|
5232
|
-
|
|
5233
|
-
|
|
5328
|
+
function receiptFailureDetail(reason) {
|
|
5329
|
+
switch (reason) {
|
|
5330
|
+
case "job_id_mismatch":
|
|
5331
|
+
return "The receipt names a different job than the one it was collected for \u2014 it is not proof of this job, whoever signed it.";
|
|
5332
|
+
case "drain_id_mismatch":
|
|
5333
|
+
return "The receipt names a different reclaim than the one it is filed under \u2014 it is not evidence of this drain, whoever signed it.";
|
|
5334
|
+
case "draw_id_mismatch":
|
|
5335
|
+
return "The funding receipt names a different draw than the job's accepted credit draw.";
|
|
5336
|
+
case "credit_id_mismatch":
|
|
5337
|
+
return "The receipt names a different credit than the one this reclaim was against \u2014 it is not evidence of this refund, whoever signed it.";
|
|
5338
|
+
case "fund_id_mismatch":
|
|
5339
|
+
return "The receipt names a different funding operation than the caller submitted.";
|
|
5340
|
+
case "funding_amount_mismatch":
|
|
5341
|
+
return "The signed funded amount differs from the provider's funding response.";
|
|
5342
|
+
case "funding_balance_mismatch":
|
|
5343
|
+
return "The signed post-funding balance differs from the provider's fresh balance response.";
|
|
5344
|
+
case "funding_ledger_seq_mismatch":
|
|
5345
|
+
return "The signed funding sequence differs from the provider's fresh balance response.";
|
|
5346
|
+
case "funding_currency_mismatch":
|
|
5347
|
+
return "The signed funding currency differs from the credit's native currency.";
|
|
5348
|
+
case "caller_pubkey_mismatch":
|
|
5349
|
+
return "The funding receipt names a different caller than the key that submitted the funding.";
|
|
5350
|
+
case "signature_invalid":
|
|
5351
|
+
return "The receipt's signature does not verify under the key it names \u2014 the bytes were altered, or it was never signed by that key.";
|
|
5352
|
+
case "attestation_invalid":
|
|
5353
|
+
return "The DVM's published builder attestation does not verify under its own builder pubkey.";
|
|
5354
|
+
case "dvm_identity_mismatch":
|
|
5355
|
+
return "The receipt names a different immutable DVM ID than the builder attestation, so it is not evidence for this provider.";
|
|
5356
|
+
case "receipt_key_mismatch":
|
|
5357
|
+
return "The receipt was signed by a different key than the one the DVM's builder attested.";
|
|
5358
|
+
case "result_hash_mismatch":
|
|
5359
|
+
return "The receipt attests a different result than the one delivered.";
|
|
5234
5360
|
}
|
|
5235
5361
|
}
|
|
5236
|
-
|
|
5237
|
-
|
|
5238
|
-
|
|
5239
|
-
|
|
5240
|
-
|
|
5362
|
+
var MAX_TIMESTAMP_MS = 864e13;
|
|
5363
|
+
var VERDICT_PREFIX = {
|
|
5364
|
+
verified: "Verified receipt",
|
|
5365
|
+
verified_unattested: "Receipt (signed, unattested)",
|
|
5366
|
+
invalid: "UNVERIFIED receipt",
|
|
5367
|
+
absent: "No receipt"
|
|
5368
|
+
};
|
|
5369
|
+
function formatPaid(msats, rate) {
|
|
5370
|
+
if (msats === 0) return "nothing (free job)";
|
|
5371
|
+
const sats = msats % 1e3 === 0 ? msats / 1e3 : Math.round(msats / 1e3 * 100) / 100;
|
|
5372
|
+
const satsLabel = `${sats.toLocaleString("en-US")} sats`;
|
|
5373
|
+
if (rate <= 0) return satsLabel;
|
|
5374
|
+
const usd2 = msatsToUsd(msats, rate);
|
|
5375
|
+
return `~$${formatUsd(usd2)} (${satsLabel}, ${costAnchor(usd2)})`;
|
|
5241
5376
|
}
|
|
5242
5377
|
|
|
5243
5378
|
// src/lib/completion-hints.ts
|
|
@@ -5379,9 +5514,9 @@ function captureTransportReceipt(jobId, response) {
|
|
|
5379
5514
|
if (response.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
|
|
5380
5515
|
return captureJobReceipt(jobId, response.receipt, response.receiptParseError);
|
|
5381
5516
|
}
|
|
5382
|
-
function receiptJsonFields(capture, jobId) {
|
|
5517
|
+
async function receiptJsonFields(capture, jobId, report) {
|
|
5383
5518
|
const out = { receipt_verified: capture.status };
|
|
5384
|
-
if (jobId) Object.assign(out,
|
|
5519
|
+
if (jobId) Object.assign(out, report ?? await terminalSettlementReport(jobId, { receipt: capture.receipt }));
|
|
5385
5520
|
else if (capture.receipt) out.settlement = receiptSettlement(capture.receipt, capture.status);
|
|
5386
5521
|
if (capture.status !== "absent") out.receipt_display = capture.display;
|
|
5387
5522
|
if (capture.currencyHint) {
|
|
@@ -5395,20 +5530,22 @@ function receiptJsonFields(capture, jobId) {
|
|
|
5395
5530
|
if (capture.reason) out.receipt_error = capture.reason;
|
|
5396
5531
|
return out;
|
|
5397
5532
|
}
|
|
5398
|
-
function renderReceiptHuman(capture, jobId) {
|
|
5399
|
-
const fields = jobId ?
|
|
5533
|
+
async function renderReceiptHuman(capture, jobId, report) {
|
|
5534
|
+
const fields = report ?? (jobId ? await terminalSettlementReport(jobId, { receipt: capture.receipt }) : {});
|
|
5400
5535
|
if (fields.settlement) info(fields.settlement.display);
|
|
5536
|
+
if (fields.wallet_remaining) info(fields.wallet_remaining.display);
|
|
5401
5537
|
if (capture.status !== "absent") info(`\u{1F9FE} ${capture.display}`);
|
|
5402
5538
|
const hint = capture.status !== "absent" && capture.currencyHint ? capture.currencyHint : fields.settlement_hint;
|
|
5403
5539
|
if (hint) info(` ${hint}`);
|
|
5404
5540
|
}
|
|
5405
5541
|
function renderSettlementHuman(fields) {
|
|
5406
5542
|
if (fields.settlement) info(fields.settlement.display);
|
|
5543
|
+
if (fields.wallet_remaining) info(fields.wallet_remaining.display);
|
|
5407
5544
|
if (fields.settlement_hint) info(` ${fields.settlement_hint}`);
|
|
5408
5545
|
}
|
|
5409
5546
|
function observedSettlementFields(jobId, response, persistLocalState = true, currency) {
|
|
5410
5547
|
if (persistLocalState && response?.status && isTerminalJobStatus(response.status) && (response.receipt || response.receiptParseError)) captureTransportReceipt(jobId, response);
|
|
5411
|
-
return
|
|
5548
|
+
return terminalSettlementReport(jobId, { status: response?.status, receipt: response?.receipt, persistLocalState, currency });
|
|
5412
5549
|
}
|
|
5413
5550
|
function receiptTrustFields(provider) {
|
|
5414
5551
|
return {
|
|
@@ -8613,6 +8750,7 @@ async function createPendingMintQuote(amountSats, opts) {
|
|
|
8613
8750
|
);
|
|
8614
8751
|
}
|
|
8615
8752
|
const cashuWallet = await (opts.getWalletForMint ?? getWallet)(opts.mintUrl);
|
|
8753
|
+
rememberKeysetFees(opts.mintUrl, cashuWallet);
|
|
8616
8754
|
const quote = await cashuWallet.createLockedMintQuote(sats, initial.lock_pubkey);
|
|
8617
8755
|
const pending = {
|
|
8618
8756
|
mint: opts.mintUrl,
|
|
@@ -9083,6 +9221,7 @@ export {
|
|
|
9083
9221
|
recordSpendOnce,
|
|
9084
9222
|
enforceGlobalBudget,
|
|
9085
9223
|
statusSnapshot,
|
|
9224
|
+
journalFile,
|
|
9086
9225
|
extractBuilderHandle,
|
|
9087
9226
|
reservedForMarker,
|
|
9088
9227
|
inFlightTimeoutSeconds,
|
|
@@ -9103,7 +9242,6 @@ export {
|
|
|
9103
9242
|
withAcceptedUnresolved,
|
|
9104
9243
|
midJobSpendLabel,
|
|
9105
9244
|
finishBookedSubmission,
|
|
9106
|
-
journalFile,
|
|
9107
9245
|
recordReclaimIntent,
|
|
9108
9246
|
loadReclaimIntent,
|
|
9109
9247
|
clearReclaimIntent,
|
|
@@ -9150,12 +9288,16 @@ export {
|
|
|
9150
9288
|
parseStatedBudget,
|
|
9151
9289
|
floatBudgetJson,
|
|
9152
9290
|
toFloatError,
|
|
9291
|
+
isImplicitCreditId,
|
|
9292
|
+
captureDrawFundingReceipts,
|
|
9293
|
+
jobDrawFundings,
|
|
9153
9294
|
formatMicro,
|
|
9154
9295
|
settlementCurrencyHint,
|
|
9155
9296
|
unknownCurrencyHint,
|
|
9156
9297
|
receiptSettlement,
|
|
9157
9298
|
jobSettlement,
|
|
9158
9299
|
terminalSettlementFields,
|
|
9300
|
+
terminalSettlementReport,
|
|
9159
9301
|
drainReceiptsDisplay,
|
|
9160
9302
|
drainReceiptsHint,
|
|
9161
9303
|
receiptDisplay,
|
|
@@ -9165,9 +9307,6 @@ export {
|
|
|
9165
9307
|
epochMsToIso,
|
|
9166
9308
|
receiptHint,
|
|
9167
9309
|
receiptFailureDetail,
|
|
9168
|
-
isImplicitCreditId,
|
|
9169
|
-
captureDrawFundingReceipts,
|
|
9170
|
-
jobDrawFundings,
|
|
9171
9310
|
buildCompletionHintFields,
|
|
9172
9311
|
nextStepHint,
|
|
9173
9312
|
completionSnapshot,
|