moltspay 1.6.0 → 2.4.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/.env.example +23 -0
- package/CHANGELOG.md +551 -0
- package/README.md +466 -7
- package/dist/cdp/index.js.map +1 -1
- package/dist/cdp/index.mjs.map +1 -1
- package/dist/{cdp-DeohBe1o.d.ts → cdp-B5PhDUTC.d.ts} +1 -1
- package/dist/{cdp-p_eHuQpb.d.mts → cdp-D-5Hg3y_.d.mts} +1 -1
- package/dist/chains/index.d.mts +102 -1
- package/dist/chains/index.d.ts +102 -1
- package/dist/chains/index.js +66 -0
- package/dist/chains/index.js.map +1 -1
- package/dist/chains/index.mjs +57 -0
- package/dist/chains/index.mjs.map +1 -1
- package/dist/cli/index.js +6850 -2127
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/index.mjs +6857 -2128
- package/dist/cli/index.mjs.map +1 -1
- package/dist/client/index.d.mts +348 -1
- package/dist/client/index.d.ts +348 -1
- package/dist/client/index.js +1462 -43
- package/dist/client/index.js.map +1 -1
- package/dist/client/index.mjs +1469 -51
- package/dist/client/index.mjs.map +1 -1
- package/dist/client/web/index.d.mts +17 -1
- package/dist/client/web/index.mjs +11 -0
- package/dist/client/web/index.mjs.map +1 -1
- package/dist/facilitators/index.d.mts +663 -4
- package/dist/facilitators/index.d.ts +663 -4
- package/dist/facilitators/index.js +1292 -10
- package/dist/facilitators/index.js.map +1 -1
- package/dist/facilitators/index.mjs +1268 -9
- package/dist/facilitators/index.mjs.map +1 -1
- package/dist/index.d.mts +78 -3
- package/dist/index.d.ts +78 -3
- package/dist/index.js +4229 -556
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4214 -548
- package/dist/index.mjs.map +1 -1
- package/dist/mcp/index.js +1462 -45
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/index.mjs +1473 -56
- package/dist/mcp/index.mjs.map +1 -1
- package/dist/{registry-OsEO2dOu.d.mts → registry-DIo0WNoO.d.mts} +8 -1
- package/dist/{registry-OsEO2dOu.d.ts → registry-DIo0WNoO.d.ts} +8 -1
- package/dist/server/index.d.mts +336 -2
- package/dist/server/index.d.ts +336 -2
- package/dist/server/index.js +2516 -188
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +2516 -188
- package/dist/server/index.mjs.map +1 -1
- package/dist/verify/index.js.map +1 -1
- package/dist/verify/index.mjs.map +1 -1
- package/dist/wallet/index.js.map +1 -1
- package/dist/wallet/index.mjs.map +1 -1
- package/package.json +20 -2
- package/schemas/moltspay.services.schema.json +211 -6
- package/scripts/postinstall.js +91 -0
package/dist/mcp/index.mjs
CHANGED
|
@@ -12,16 +12,17 @@ import { webcrypto } from "crypto";
|
|
|
12
12
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
13
13
|
|
|
14
14
|
// src/mcp/server.ts
|
|
15
|
-
import { existsSync as existsSync3, readFileSync as
|
|
16
|
-
import { join as
|
|
15
|
+
import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
|
|
16
|
+
import { join as join5 } from "path";
|
|
17
17
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
18
18
|
import { z } from "zod";
|
|
19
19
|
|
|
20
20
|
// src/client/node/index.ts
|
|
21
|
-
import { existsSync as existsSync2, readFileSync as
|
|
22
|
-
import { homedir as
|
|
23
|
-
import { join as
|
|
24
|
-
import {
|
|
21
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync3, mkdirSync as mkdirSync3, statSync, chmodSync, readdirSync as readdirSync2 } from "fs";
|
|
22
|
+
import { homedir as homedir4 } from "os";
|
|
23
|
+
import { join as join4 } from "path";
|
|
24
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
25
|
+
import { Wallet as Wallet2, ethers as ethers3 } from "ethers";
|
|
25
26
|
|
|
26
27
|
// src/chains/index.ts
|
|
27
28
|
var CHAINS = {
|
|
@@ -347,6 +348,16 @@ function networkToChainName(network) {
|
|
|
347
348
|
// src/client/core/base64.ts
|
|
348
349
|
var BufferCtor = globalThis.Buffer;
|
|
349
350
|
|
|
351
|
+
// src/client/core/errors.ts
|
|
352
|
+
var MoltsPayError = class extends Error {
|
|
353
|
+
code;
|
|
354
|
+
constructor(code, message) {
|
|
355
|
+
super(message);
|
|
356
|
+
this.name = "MoltsPayError";
|
|
357
|
+
this.code = code;
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
|
|
350
361
|
// src/client/core/eip3009.ts
|
|
351
362
|
var EIP3009_TYPES = {
|
|
352
363
|
TransferWithAuthorization: [
|
|
@@ -483,6 +494,936 @@ function findChainByChainId(chainId) {
|
|
|
483
494
|
return void 0;
|
|
484
495
|
}
|
|
485
496
|
|
|
497
|
+
// src/client/alipay/index.ts
|
|
498
|
+
import { randomUUID } from "crypto";
|
|
499
|
+
import { mkdir, writeFile } from "fs/promises";
|
|
500
|
+
import { homedir as homedir2 } from "os";
|
|
501
|
+
import { join as join2 } from "path";
|
|
502
|
+
|
|
503
|
+
// src/client/alipay/cli.ts
|
|
504
|
+
import { spawn } from "child_process";
|
|
505
|
+
|
|
506
|
+
// src/client/alipay/log.ts
|
|
507
|
+
var RANK = { off: 0, info: 1, debug: 2 };
|
|
508
|
+
function normalizeLevel(v) {
|
|
509
|
+
const s = (v ?? "").toLowerCase();
|
|
510
|
+
return s === "info" || s === "debug" ? s : "off";
|
|
511
|
+
}
|
|
512
|
+
var level = normalizeLevel(process.env.MOLTSPAY_ALIPAY_LOG);
|
|
513
|
+
var sink = (line) => {
|
|
514
|
+
process.stderr.write(line + "\n");
|
|
515
|
+
};
|
|
516
|
+
function enabledFor(want) {
|
|
517
|
+
return RANK[level] >= RANK[want];
|
|
518
|
+
}
|
|
519
|
+
function render(event, fields) {
|
|
520
|
+
const parts = ["[moltspay:alipay]", String(fields.ts), event];
|
|
521
|
+
if (fields.flow) parts.push(`flow=${fields.flow}`);
|
|
522
|
+
if (fields.step) parts.push(`step=${fields.step}`);
|
|
523
|
+
if (typeof fields.ms === "number") parts.push(`${fields.ms}ms`);
|
|
524
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
525
|
+
if (["ts", "level", "event", "flow", "step", "ms"].includes(k)) continue;
|
|
526
|
+
parts.push(`${k}=${typeof v === "string" ? v : JSON.stringify(v)}`);
|
|
527
|
+
}
|
|
528
|
+
return parts.join(" ");
|
|
529
|
+
}
|
|
530
|
+
function emit(lvl, event, fields) {
|
|
531
|
+
if (!enabledFor(lvl)) return;
|
|
532
|
+
const full = { ts: (/* @__PURE__ */ new Date()).toISOString(), level: lvl, event, ...fields };
|
|
533
|
+
try {
|
|
534
|
+
sink(render(event, full), full);
|
|
535
|
+
} catch {
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
var alipayLog = {
|
|
539
|
+
info: (event, fields = {}) => emit("info", event, fields),
|
|
540
|
+
debug: (event, fields = {}) => emit("debug", event, fields),
|
|
541
|
+
/** True if anything at all would be logged (cheap guard for hot paths). */
|
|
542
|
+
enabled: () => level !== "off"
|
|
543
|
+
};
|
|
544
|
+
async function timeStep(step, flow, fn) {
|
|
545
|
+
if (!alipayLog.enabled()) return fn();
|
|
546
|
+
const t0 = Date.now();
|
|
547
|
+
alipayLog.debug("step.start", { flow, step });
|
|
548
|
+
try {
|
|
549
|
+
const out = await fn();
|
|
550
|
+
alipayLog.info("step.end", { flow, step, ms: Date.now() - t0, ok: true });
|
|
551
|
+
return out;
|
|
552
|
+
} catch (err2) {
|
|
553
|
+
alipayLog.info("step.end", {
|
|
554
|
+
flow,
|
|
555
|
+
step,
|
|
556
|
+
ms: Date.now() - t0,
|
|
557
|
+
ok: false,
|
|
558
|
+
err: err2 instanceof Error ? err2.message : String(err2)
|
|
559
|
+
});
|
|
560
|
+
throw err2;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// src/client/alipay/cli.ts
|
|
565
|
+
var ALLOWED_ENV = /* @__PURE__ */ new Set([
|
|
566
|
+
"AIPAY_OUTPUT_CHANNEL",
|
|
567
|
+
"AIPAY_SESSION_ID",
|
|
568
|
+
"AIPAY_FRAMEWORK",
|
|
569
|
+
"AIPAY_MODEL",
|
|
570
|
+
"AIPAY_OS",
|
|
571
|
+
// Minimal survival set for spawn to find the binary and a home dir.
|
|
572
|
+
"PATH",
|
|
573
|
+
"HOME"
|
|
574
|
+
]);
|
|
575
|
+
function filterEnv(env) {
|
|
576
|
+
return Object.fromEntries(
|
|
577
|
+
Object.entries(env).filter(([k]) => ALLOWED_ENV.has(k))
|
|
578
|
+
);
|
|
579
|
+
}
|
|
580
|
+
function makeLineSplitter(onLine) {
|
|
581
|
+
let buf = "";
|
|
582
|
+
return (chunk) => {
|
|
583
|
+
buf += chunk.toString("utf-8");
|
|
584
|
+
let nl;
|
|
585
|
+
while ((nl = buf.indexOf("\n")) !== -1) {
|
|
586
|
+
onLine(buf.slice(0, nl));
|
|
587
|
+
buf = buf.slice(nl + 1);
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
function profileEnv(step, flow) {
|
|
592
|
+
const want = process.env.MOLTSPAY_ALIPAY_CLI_PROFILE;
|
|
593
|
+
const hook = process.env.MOLTSPAY_ALIPAY_CLI_PROFILE_HOOK;
|
|
594
|
+
if (!want || !hook) return {};
|
|
595
|
+
const steps = want.split(",").map((s) => s.trim());
|
|
596
|
+
if (!steps.includes("all") && !steps.includes(step)) return {};
|
|
597
|
+
const dir = process.env.MOLTSPAY_ALIPAY_CLI_PROFILE_DIR || "/tmp";
|
|
598
|
+
const safe = `${flow ?? "noflow"}-${step}-${Date.now()}`.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
599
|
+
const out = `${dir}/cli-profile-${safe}.json`;
|
|
600
|
+
alipayLog.info("cli.profile", { flow, step, out });
|
|
601
|
+
return {
|
|
602
|
+
NODE_OPTIONS: `--require=${hook}`,
|
|
603
|
+
MOLTSPAY_CLI_PROFILE_OUT: out
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
var runCli = (args, opts = {}) => {
|
|
607
|
+
const bin = opts.bin ?? "alipay-bot";
|
|
608
|
+
const step = opts.step ?? args[0] ?? "(no-arg)";
|
|
609
|
+
const startedAt = Date.now();
|
|
610
|
+
const lines = [];
|
|
611
|
+
const collect = (line) => {
|
|
612
|
+
lines.push(line);
|
|
613
|
+
alipayLog.debug("cli.line", {
|
|
614
|
+
flow: opts.flow,
|
|
615
|
+
step,
|
|
616
|
+
ms: Date.now() - startedAt,
|
|
617
|
+
preview: line.slice(0, 120)
|
|
618
|
+
});
|
|
619
|
+
opts.onLine?.(line);
|
|
620
|
+
};
|
|
621
|
+
alipayLog.debug("step.start", { flow: opts.flow, step });
|
|
622
|
+
return new Promise((resolve, reject) => {
|
|
623
|
+
const child = spawn(bin, args, {
|
|
624
|
+
env: { ...filterEnv(process.env), ...profileEnv(step, opts.flow), ...opts.env ?? {} }
|
|
625
|
+
});
|
|
626
|
+
if (opts.signal) {
|
|
627
|
+
if (opts.signal.aborted) child.kill("SIGTERM");
|
|
628
|
+
opts.signal.addEventListener("abort", () => child.kill("SIGTERM"), { once: true });
|
|
629
|
+
}
|
|
630
|
+
let sawByte = false;
|
|
631
|
+
const onChunk = (stream) => (chunk) => {
|
|
632
|
+
const ms = Date.now() - startedAt;
|
|
633
|
+
if (!sawByte) {
|
|
634
|
+
sawByte = true;
|
|
635
|
+
alipayLog.debug("cli.firstbyte", { flow: opts.flow, step, ms });
|
|
636
|
+
}
|
|
637
|
+
alipayLog.debug("cli.chunk", { flow: opts.flow, step, ms, stream, bytes: chunk.length });
|
|
638
|
+
};
|
|
639
|
+
const onStdout = makeLineSplitter(collect);
|
|
640
|
+
const onStderr = makeLineSplitter(collect);
|
|
641
|
+
child.stdout?.on("data", onChunk("out"));
|
|
642
|
+
child.stderr?.on("data", onChunk("err"));
|
|
643
|
+
child.stdout?.on("data", onStdout);
|
|
644
|
+
child.stderr?.on("data", onStderr);
|
|
645
|
+
child.on("error", (err2) => {
|
|
646
|
+
alipayLog.info("cli.exit", {
|
|
647
|
+
flow: opts.flow,
|
|
648
|
+
step,
|
|
649
|
+
ms: Date.now() - startedAt,
|
|
650
|
+
ok: false,
|
|
651
|
+
err: err2.message
|
|
652
|
+
});
|
|
653
|
+
reject(err2);
|
|
654
|
+
});
|
|
655
|
+
child.on("close", (code) => {
|
|
656
|
+
alipayLog.info("cli.exit", {
|
|
657
|
+
flow: opts.flow,
|
|
658
|
+
step,
|
|
659
|
+
ms: Date.now() - startedAt,
|
|
660
|
+
ok: (code ?? 1) === 0,
|
|
661
|
+
code: code ?? 1
|
|
662
|
+
});
|
|
663
|
+
resolve({ exitCode: code ?? 1, lines });
|
|
664
|
+
});
|
|
665
|
+
});
|
|
666
|
+
};
|
|
667
|
+
|
|
668
|
+
// src/client/alipay/install.ts
|
|
669
|
+
import { execFile } from "child_process";
|
|
670
|
+
import { promisify } from "util";
|
|
671
|
+
|
|
672
|
+
// src/client/alipay/errors.ts
|
|
673
|
+
var AlipayCliNotFoundError = class extends MoltsPayError {
|
|
674
|
+
constructor(message) {
|
|
675
|
+
super("ALIPAY_CLI_NOT_FOUND", message);
|
|
676
|
+
this.name = "AlipayCliNotFoundError";
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
var AlipayCliVersionError = class extends MoltsPayError {
|
|
680
|
+
constructor(message) {
|
|
681
|
+
super("ALIPAY_CLI_VERSION", message);
|
|
682
|
+
this.name = "AlipayCliVersionError";
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
var NeedsWalletSetupError = class extends MoltsPayError {
|
|
686
|
+
constructor(message = "Alipay wallet not set up. Run: moltspay alipay apply") {
|
|
687
|
+
super("ALIPAY_NEEDS_WALLET_SETUP", message);
|
|
688
|
+
this.name = "NeedsWalletSetupError";
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
var AlipayPaymentRejectedError = class extends MoltsPayError {
|
|
692
|
+
constructor(message) {
|
|
693
|
+
super("ALIPAY_PAYMENT_REJECTED", message);
|
|
694
|
+
this.name = "AlipayPaymentRejectedError";
|
|
695
|
+
}
|
|
696
|
+
};
|
|
697
|
+
var AlipayPaymentTimeoutError = class extends MoltsPayError {
|
|
698
|
+
constructor(message) {
|
|
699
|
+
super("ALIPAY_PAYMENT_TIMEOUT", message);
|
|
700
|
+
this.name = "AlipayPaymentTimeoutError";
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
var AlipayProtocolError = class extends MoltsPayError {
|
|
704
|
+
constructor(message) {
|
|
705
|
+
super("ALIPAY_PROTOCOL", message);
|
|
706
|
+
this.name = "AlipayProtocolError";
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
var UnsupportedRailError = class extends MoltsPayError {
|
|
710
|
+
constructor(rail, message) {
|
|
711
|
+
super("UNSUPPORTED_RAIL", message ?? `Rail not supported by server: ${rail}`);
|
|
712
|
+
this.rail = rail;
|
|
713
|
+
this.name = "UnsupportedRailError";
|
|
714
|
+
}
|
|
715
|
+
};
|
|
716
|
+
|
|
717
|
+
// src/client/alipay/install.ts
|
|
718
|
+
var execFileAsync = promisify(execFile);
|
|
719
|
+
var MIN_CLI_VERSION = "0.3.15";
|
|
720
|
+
function semverLt(a, b) {
|
|
721
|
+
const pa = a.split(".").map((n) => parseInt(n, 10));
|
|
722
|
+
const pb = b.split(".").map((n) => parseInt(n, 10));
|
|
723
|
+
for (let i = 0; i < 3; i++) {
|
|
724
|
+
const x = pa[i] ?? 0;
|
|
725
|
+
const y = pb[i] ?? 0;
|
|
726
|
+
if (x !== y) return x < y;
|
|
727
|
+
}
|
|
728
|
+
return false;
|
|
729
|
+
}
|
|
730
|
+
function parseVersion(stdout) {
|
|
731
|
+
return stdout.match(/v?(\d+\.\d+\.\d+)/)?.[1] ?? null;
|
|
732
|
+
}
|
|
733
|
+
var defaultGetVersion = async () => {
|
|
734
|
+
const { stdout } = await execFileAsync("alipay-bot", ["--version"]);
|
|
735
|
+
return stdout;
|
|
736
|
+
};
|
|
737
|
+
async function ensureCliUncached(getVersion) {
|
|
738
|
+
let stdout;
|
|
739
|
+
try {
|
|
740
|
+
stdout = await getVersion();
|
|
741
|
+
} catch (e) {
|
|
742
|
+
if (e?.code === "ENOENT") {
|
|
743
|
+
throw new AlipayCliNotFoundError(
|
|
744
|
+
"alipay-bot not installed. Run: npx -y @alipay/agent-payment install-cli"
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
throw e;
|
|
748
|
+
}
|
|
749
|
+
const version = parseVersion(stdout);
|
|
750
|
+
if (!version || semverLt(version, MIN_CLI_VERSION)) {
|
|
751
|
+
throw new AlipayCliVersionError(
|
|
752
|
+
`alipay-bot ${version ?? "?"} found, need \u2265 ${MIN_CLI_VERSION}. Run: npx -y @alipay/agent-payment@latest update`
|
|
753
|
+
);
|
|
754
|
+
}
|
|
755
|
+
return version;
|
|
756
|
+
}
|
|
757
|
+
var cachedVersion = null;
|
|
758
|
+
var inflight = null;
|
|
759
|
+
async function ensureCli(getVersion = defaultGetVersion) {
|
|
760
|
+
if (getVersion !== defaultGetVersion) {
|
|
761
|
+
return ensureCliUncached(getVersion);
|
|
762
|
+
}
|
|
763
|
+
if (cachedVersion) return cachedVersion;
|
|
764
|
+
if (!inflight) {
|
|
765
|
+
inflight = ensureCliUncached(getVersion).then((v) => {
|
|
766
|
+
cachedVersion = v;
|
|
767
|
+
return v;
|
|
768
|
+
}).finally(() => {
|
|
769
|
+
inflight = null;
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
return inflight;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// src/client/alipay/poll.ts
|
|
776
|
+
var POLL_INTERVAL_MS = 3e3;
|
|
777
|
+
var POLL_MAX_INFLIGHT = 2;
|
|
778
|
+
function resolveMaxInflight(override) {
|
|
779
|
+
if (override !== void 0) return Math.max(1, Math.floor(override));
|
|
780
|
+
const raw = process.env.MOLTSPAY_ALIPAY_POLL_MAX_INFLIGHT;
|
|
781
|
+
if (raw !== void 0 && raw.trim() !== "") {
|
|
782
|
+
const n = Number(raw);
|
|
783
|
+
if (Number.isFinite(n) && n >= 1) return Math.floor(n);
|
|
784
|
+
}
|
|
785
|
+
return POLL_MAX_INFLIGHT;
|
|
786
|
+
}
|
|
787
|
+
function resolveLaunchGap(override) {
|
|
788
|
+
if (override !== void 0) return Math.max(0, override);
|
|
789
|
+
const raw = process.env.MOLTSPAY_ALIPAY_POLL_LAUNCH_MS;
|
|
790
|
+
if (raw !== void 0 && raw.trim() !== "") {
|
|
791
|
+
const n = Number(raw);
|
|
792
|
+
if (Number.isFinite(n) && n >= 0) return n;
|
|
793
|
+
}
|
|
794
|
+
return POLL_INTERVAL_MS;
|
|
795
|
+
}
|
|
796
|
+
function parseStatus(lines) {
|
|
797
|
+
const raw = lines.join("\n").trim();
|
|
798
|
+
try {
|
|
799
|
+
const json = JSON.parse(raw);
|
|
800
|
+
if (json && typeof json === "object") {
|
|
801
|
+
if (typeof json.success === "boolean") {
|
|
802
|
+
if (json.success) return "paid";
|
|
803
|
+
const err2 = String(json.errorCode ?? "").toUpperCase();
|
|
804
|
+
if (/UNPAID|WAIT|PENDING|PROCESS|NOTPAY/.test(err2)) return "pending";
|
|
805
|
+
if (/CLOSED|CANCEL|FAIL|REJECT|REFUSE|TIMEOUT|EXPIRE/.test(err2)) return "rejected";
|
|
806
|
+
return "pending";
|
|
807
|
+
}
|
|
808
|
+
if (typeof json.code !== "undefined") {
|
|
809
|
+
if (Number(json.code) === 200) return "paid";
|
|
810
|
+
const msg = `${json.message ?? ""}${json.reason ?? ""}`;
|
|
811
|
+
if (/关闭|失败|拒绝|取消|超时|已撤销/.test(msg)) return "rejected";
|
|
812
|
+
return "pending";
|
|
813
|
+
}
|
|
814
|
+
if (typeof json.body === "string") {
|
|
815
|
+
return classifyReportText(json.body);
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
} catch {
|
|
819
|
+
}
|
|
820
|
+
return classifyReportText(raw);
|
|
821
|
+
}
|
|
822
|
+
function classifyReportText(s) {
|
|
823
|
+
const text = s.toUpperCase();
|
|
824
|
+
if (/查询支付状态成功并获取资源/.test(s) || /资源响应状态[^0-9\n]{0,8}200/.test(s) || /TRADE_SUCCESS|TRADE_FINISHED|"STATUS":\s*"FULFILLED"/.test(text)) return "paid";
|
|
825
|
+
if (/TRADE_CLOSED|REJECTED|REFUSE|CANCEL/.test(text) || /交易关闭|支付失败|已拒绝|已取消|已撤销|交易超时/.test(s)) return "rejected";
|
|
826
|
+
if (/WAIT_BUYER_PAY|UNPAID|PENDING|WAITING/.test(text) || /交易未支付|等待付款|待支付|未支付/.test(s)) return "pending";
|
|
827
|
+
return "unknown";
|
|
828
|
+
}
|
|
829
|
+
function defaultSleep(ms, signal) {
|
|
830
|
+
return new Promise((resolve, reject) => {
|
|
831
|
+
if (signal?.aborted) return reject(new Error("aborted"));
|
|
832
|
+
const t = setTimeout(resolve, ms);
|
|
833
|
+
signal?.addEventListener(
|
|
834
|
+
"abort",
|
|
835
|
+
() => {
|
|
836
|
+
clearTimeout(t);
|
|
837
|
+
reject(new Error("aborted"));
|
|
838
|
+
},
|
|
839
|
+
{ once: true }
|
|
840
|
+
);
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
var LAUNCH = /* @__PURE__ */ Symbol("launch");
|
|
844
|
+
async function pollUntil(tradeNo, resourceUrl, opts) {
|
|
845
|
+
const runner = opts.runner ?? runCli;
|
|
846
|
+
const sleep = opts.sleep ?? defaultSleep;
|
|
847
|
+
const now = opts.now ?? Date.now;
|
|
848
|
+
const maxInflight = resolveMaxInflight(opts.maxInflight);
|
|
849
|
+
const launchGap = resolveLaunchGap(opts.launchIntervalMs);
|
|
850
|
+
const args = [
|
|
851
|
+
"402-query-payment-status",
|
|
852
|
+
"-t",
|
|
853
|
+
tradeNo,
|
|
854
|
+
"-r",
|
|
855
|
+
resourceUrl,
|
|
856
|
+
...opts.method ? ["-m", opts.method] : [],
|
|
857
|
+
...opts.data ? ["-d", opts.data] : []
|
|
858
|
+
];
|
|
859
|
+
const internal = new AbortController();
|
|
860
|
+
const signal = opts.signal ? AbortSignal.any([opts.signal, internal.signal]) : internal.signal;
|
|
861
|
+
let tick = 0;
|
|
862
|
+
let lastLaunch = -Infinity;
|
|
863
|
+
const inflight2 = /* @__PURE__ */ new Set();
|
|
864
|
+
const launch = () => {
|
|
865
|
+
tick += 1;
|
|
866
|
+
const myTick = tick;
|
|
867
|
+
lastLaunch = now();
|
|
868
|
+
const run = (async () => {
|
|
869
|
+
const { lines } = await runner(args, {
|
|
870
|
+
signal,
|
|
871
|
+
step: "query-payment-status",
|
|
872
|
+
flow: tradeNo
|
|
873
|
+
});
|
|
874
|
+
const status = parseStatus(lines);
|
|
875
|
+
alipayLog.debug("poll.tick", { flow: tradeNo, tick: myTick, status });
|
|
876
|
+
return { status, lines };
|
|
877
|
+
})();
|
|
878
|
+
const tracked = run.finally(() => {
|
|
879
|
+
inflight2.delete(tracked);
|
|
880
|
+
});
|
|
881
|
+
inflight2.add(tracked);
|
|
882
|
+
};
|
|
883
|
+
try {
|
|
884
|
+
for (; ; ) {
|
|
885
|
+
if (opts.signal?.aborted) throw new Error("aborted");
|
|
886
|
+
const expired = now() >= opts.deadline;
|
|
887
|
+
if (expired && inflight2.size === 0) {
|
|
888
|
+
throw new AlipayPaymentTimeoutError(
|
|
889
|
+
`Payment ${tradeNo} not completed before pay_before deadline`
|
|
890
|
+
);
|
|
891
|
+
}
|
|
892
|
+
while (!expired && inflight2.size < maxInflight && now() - lastLaunch >= launchGap) {
|
|
893
|
+
launch();
|
|
894
|
+
}
|
|
895
|
+
const waiters = [...inflight2];
|
|
896
|
+
if (!expired && inflight2.size < maxInflight) {
|
|
897
|
+
const untilNext = Math.max(0, launchGap - (now() - lastLaunch));
|
|
898
|
+
waiters.push(sleep(untilNext, signal).then(() => LAUNCH, () => LAUNCH));
|
|
899
|
+
}
|
|
900
|
+
const winner = await Promise.race(waiters);
|
|
901
|
+
if (winner === LAUNCH) continue;
|
|
902
|
+
if (winner.status === "paid") return { status: "paid", lines: winner.lines };
|
|
903
|
+
if (winner.status === "rejected") {
|
|
904
|
+
throw new AlipayPaymentRejectedError(`Payment ${tradeNo} was rejected`);
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
} finally {
|
|
908
|
+
internal.abort();
|
|
909
|
+
for (const p of inflight2) p.catch(() => void 0);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
// src/client/alipay/index.ts
|
|
914
|
+
var TRADE_NO_RE = /^\d{32}$/;
|
|
915
|
+
function resolveSessionId(explicit, envSession) {
|
|
916
|
+
return explicit ?? envSession ?? randomUUID();
|
|
917
|
+
}
|
|
918
|
+
function assertTradeNo(t) {
|
|
919
|
+
if (!TRADE_NO_RE.test(t)) {
|
|
920
|
+
throw new AlipayProtocolError(`invalid tradeNo (expect 32 digits): ${t}`);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
function parseTradeNo(lines) {
|
|
924
|
+
for (const line of lines) {
|
|
925
|
+
const labeled = line.match(/trade[_-]?no["'\s:=]+(\d{32})/i);
|
|
926
|
+
if (labeled) return labeled[1];
|
|
927
|
+
const bare = line.match(/\b(\d{32})\b/);
|
|
928
|
+
if (bare) return bare[1];
|
|
929
|
+
}
|
|
930
|
+
return null;
|
|
931
|
+
}
|
|
932
|
+
function parsePaymentUrl(lines) {
|
|
933
|
+
let paymentUrl;
|
|
934
|
+
let shortenUrl;
|
|
935
|
+
for (const line of lines) {
|
|
936
|
+
const m = line.match(/(alipays?:\/\/\S+|https?:\/\/\S+)/i);
|
|
937
|
+
if (!m) continue;
|
|
938
|
+
const url = m[1].replace(/[)\]`>]+$/, "");
|
|
939
|
+
if (/short|qr\.alipay|surl|\/s\//i.test(line) && !shortenUrl) shortenUrl = url;
|
|
940
|
+
else if (!paymentUrl) paymentUrl = url;
|
|
941
|
+
}
|
|
942
|
+
if (!paymentUrl && shortenUrl) paymentUrl = shortenUrl;
|
|
943
|
+
return { paymentUrl, shortenUrl };
|
|
944
|
+
}
|
|
945
|
+
function extractMedia(line) {
|
|
946
|
+
const m = line.match(/^\s*MEDIA:\s*(.+?)\s*$/);
|
|
947
|
+
return m ? m[1] : null;
|
|
948
|
+
}
|
|
949
|
+
function isWalletReady(lines) {
|
|
950
|
+
const text = lines.join("\n").trim();
|
|
951
|
+
try {
|
|
952
|
+
const json = JSON.parse(text);
|
|
953
|
+
if (json && typeof json.code !== "undefined") return Number(json.code) === 200;
|
|
954
|
+
} catch {
|
|
955
|
+
}
|
|
956
|
+
return !/未开通|未开启|NOT[_\s-]*(OPEN|BOUND|SET)|NEEDS?[_\s-]*SETUP|NO[_\s-]*WALLET/i.test(text);
|
|
957
|
+
}
|
|
958
|
+
function extractResourceFromReport(report) {
|
|
959
|
+
const label = report.search(/资源响应体/);
|
|
960
|
+
const start = report.indexOf("{", label === -1 ? 0 : label);
|
|
961
|
+
if (start === -1) return void 0;
|
|
962
|
+
let depth = 0, inStr = false, esc = false;
|
|
963
|
+
for (let i = start; i < report.length; i++) {
|
|
964
|
+
const ch = report[i];
|
|
965
|
+
if (inStr) {
|
|
966
|
+
if (esc) esc = false;
|
|
967
|
+
else if (ch === "\\") esc = true;
|
|
968
|
+
else if (ch === '"') inStr = false;
|
|
969
|
+
continue;
|
|
970
|
+
}
|
|
971
|
+
if (ch === '"') inStr = true;
|
|
972
|
+
else if (ch === "{") depth++;
|
|
973
|
+
else if (ch === "}" && --depth === 0) {
|
|
974
|
+
const slice = report.slice(start, i + 1);
|
|
975
|
+
try {
|
|
976
|
+
const obj = JSON.parse(slice);
|
|
977
|
+
const r = obj?.resourceResponse ?? obj?.result ?? obj?.data ?? obj?.body ?? obj;
|
|
978
|
+
return typeof r === "string" ? r : JSON.stringify(r);
|
|
979
|
+
} catch {
|
|
980
|
+
return slice;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
return void 0;
|
|
985
|
+
}
|
|
986
|
+
function extractBody(lines) {
|
|
987
|
+
const text = lines.join("\n").trim();
|
|
988
|
+
try {
|
|
989
|
+
const json = JSON.parse(text);
|
|
990
|
+
if (json && typeof json === "object") {
|
|
991
|
+
if (json.resourceResponse !== void 0 && json.resourceResponse !== null) {
|
|
992
|
+
const rr = json.resourceResponse;
|
|
993
|
+
const r = typeof rr === "object" ? rr.result ?? rr.data ?? rr.body ?? rr : rr;
|
|
994
|
+
return typeof r === "string" ? r : JSON.stringify(r);
|
|
995
|
+
}
|
|
996
|
+
if (typeof json.body === "string") {
|
|
997
|
+
const inner = extractResourceFromReport(json.body);
|
|
998
|
+
return inner ?? json.body;
|
|
999
|
+
}
|
|
1000
|
+
const body = json.data ?? json.result ?? json.body ?? json.resource;
|
|
1001
|
+
if (body !== void 0) return typeof body === "string" ? body : JSON.stringify(body);
|
|
1002
|
+
return text;
|
|
1003
|
+
}
|
|
1004
|
+
} catch {
|
|
1005
|
+
}
|
|
1006
|
+
const idx = lines.findIndex((l) => /^\s*BODY:/.test(l));
|
|
1007
|
+
if (idx !== -1) {
|
|
1008
|
+
const first = lines[idx].replace(/^\s*BODY:\s*/, "");
|
|
1009
|
+
return [first, ...lines.slice(idx + 1)].join("\n").trim();
|
|
1010
|
+
}
|
|
1011
|
+
return lines.filter((l) => !/^\s*(MEDIA|STATUS|INFO):/.test(l)).join("\n").trim();
|
|
1012
|
+
}
|
|
1013
|
+
var DEFAULT_WALLET_TTL_MS = 10 * 60 * 1e3;
|
|
1014
|
+
function resolveWalletTtlMs() {
|
|
1015
|
+
const raw = process.env.MOLTSPAY_ALIPAY_WALLET_TTL_MS;
|
|
1016
|
+
if (raw === void 0 || raw.trim() === "") return DEFAULT_WALLET_TTL_MS;
|
|
1017
|
+
const n = Number(raw);
|
|
1018
|
+
return Number.isFinite(n) && n >= 0 ? n : DEFAULT_WALLET_TTL_MS;
|
|
1019
|
+
}
|
|
1020
|
+
var walletReadyUntil = /* @__PURE__ */ new Map();
|
|
1021
|
+
var DEFAULT_INTENT_TTL_MS = 10 * 60 * 1e3;
|
|
1022
|
+
function resolveIntentTtlMs() {
|
|
1023
|
+
const raw = process.env.MOLTSPAY_ALIPAY_INTENT_TTL_MS;
|
|
1024
|
+
if (raw === void 0 || raw.trim() === "") return DEFAULT_INTENT_TTL_MS;
|
|
1025
|
+
const n = Number(raw);
|
|
1026
|
+
return Number.isFinite(n) && n >= 0 ? n : DEFAULT_INTENT_TTL_MS;
|
|
1027
|
+
}
|
|
1028
|
+
var intentDoneUntil = /* @__PURE__ */ new Map();
|
|
1029
|
+
var AlipayClient = class {
|
|
1030
|
+
sessionId;
|
|
1031
|
+
configDir;
|
|
1032
|
+
framework;
|
|
1033
|
+
runner;
|
|
1034
|
+
getVersion;
|
|
1035
|
+
now;
|
|
1036
|
+
/** Only the default runner may use the process-level wallet cache. */
|
|
1037
|
+
walletCacheable;
|
|
1038
|
+
/** Only the default runner may use the process-level payment-intent cache. */
|
|
1039
|
+
intentCacheable;
|
|
1040
|
+
constructor(opts = {}) {
|
|
1041
|
+
this.sessionId = resolveSessionId(opts.sessionId, process.env.AIPAY_SESSION_ID);
|
|
1042
|
+
this.configDir = opts.configDir ?? join2(homedir2(), ".moltspay");
|
|
1043
|
+
this.framework = opts.framework ?? process.env.AIPAY_FRAMEWORK ?? "openclaw";
|
|
1044
|
+
this.runner = opts.runner ?? runCli;
|
|
1045
|
+
this.getVersion = opts.getVersion;
|
|
1046
|
+
this.now = opts.now ?? Date.now;
|
|
1047
|
+
this.walletCacheable = opts.cacheWallet ?? !opts.runner;
|
|
1048
|
+
this.intentCacheable = opts.cacheIntent ?? !opts.runner;
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* Throws NeedsWalletSetupError unless alipay-bot reports an opened wallet.
|
|
1052
|
+
*
|
|
1053
|
+
* Skips the ~22s `check-wallet` spawn entirely when a prior call cached a
|
|
1054
|
+
* "ready" verdict within the TTL (see {@link DEFAULT_WALLET_TTL_MS}).
|
|
1055
|
+
*/
|
|
1056
|
+
async checkWallet(signal, flow) {
|
|
1057
|
+
const ttlMs = resolveWalletTtlMs();
|
|
1058
|
+
const cacheKey = `${this.configDir}::${this.framework}`;
|
|
1059
|
+
const useCache = this.walletCacheable && ttlMs > 0;
|
|
1060
|
+
if (useCache) {
|
|
1061
|
+
const until = walletReadyUntil.get(cacheKey);
|
|
1062
|
+
if (until !== void 0 && this.now() < until) {
|
|
1063
|
+
alipayLog.info("wallet.cache", { flow, step: "check-wallet", hit: true, ttlMsLeft: until - this.now() });
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
const { lines } = await this.runner(["check-wallet"], { signal, step: "check-wallet", flow });
|
|
1068
|
+
if (!isWalletReady(lines)) {
|
|
1069
|
+
if (this.walletCacheable) walletReadyUntil.delete(cacheKey);
|
|
1070
|
+
throw new NeedsWalletSetupError(
|
|
1071
|
+
"Alipay wallet not opened. Run: moltspay alipay apply (then: moltspay alipay bind)"
|
|
1072
|
+
);
|
|
1073
|
+
}
|
|
1074
|
+
if (useCache) {
|
|
1075
|
+
walletReadyUntil.set(cacheKey, this.now() + ttlMs);
|
|
1076
|
+
alipayLog.info("wallet.cache", { flow, step: "check-wallet", hit: false, cachedForMs: ttlMs });
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
/** Run the full 8-step flow and resolve with the resource body. */
|
|
1080
|
+
async pay402(opts) {
|
|
1081
|
+
const { resourceUrl, requirement, signal } = opts;
|
|
1082
|
+
const extra = requirement.extra ?? {};
|
|
1083
|
+
const paymentNeededHeader = String(extra.payment_needed_header ?? "");
|
|
1084
|
+
if (!paymentNeededHeader) {
|
|
1085
|
+
throw new AlipayProtocolError("alipay requirement missing extra.payment_needed_header");
|
|
1086
|
+
}
|
|
1087
|
+
const flow = this.sessionId;
|
|
1088
|
+
const flowStart = this.now();
|
|
1089
|
+
alipayLog.info("flow.start", { flow, resource: resourceUrl });
|
|
1090
|
+
const media = [];
|
|
1091
|
+
const onLine = (line) => {
|
|
1092
|
+
const m = extractMedia(line);
|
|
1093
|
+
if (m) media.push(m);
|
|
1094
|
+
else opts.onLine?.(line);
|
|
1095
|
+
};
|
|
1096
|
+
const intentSummary = opts.intentSummary?.trim() || `Pay ${requirement.amount ?? ""} ${requirement.asset ?? "CNY"}`.trim();
|
|
1097
|
+
await timeStep("ensure-cli", flow, () => ensureCli(this.getVersion));
|
|
1098
|
+
const intentTtlMs = resolveIntentTtlMs();
|
|
1099
|
+
const intentKey = `${this.configDir}::${this.framework}`;
|
|
1100
|
+
const useIntentCache = this.intentCacheable && intentTtlMs > 0;
|
|
1101
|
+
const intentUntil = useIntentCache ? intentDoneUntil.get(intentKey) : void 0;
|
|
1102
|
+
if (intentUntil !== void 0 && this.now() < intentUntil) {
|
|
1103
|
+
alipayLog.info("intent.cache", { flow, step: "payment-intent", hit: true, ttlMsLeft: intentUntil - this.now() });
|
|
1104
|
+
} else {
|
|
1105
|
+
await this.runner(
|
|
1106
|
+
[
|
|
1107
|
+
"payment-intent",
|
|
1108
|
+
"--session-id",
|
|
1109
|
+
this.sessionId,
|
|
1110
|
+
"--intent-summary",
|
|
1111
|
+
intentSummary,
|
|
1112
|
+
"--framework",
|
|
1113
|
+
this.framework
|
|
1114
|
+
],
|
|
1115
|
+
{ onLine, signal, step: "payment-intent", flow }
|
|
1116
|
+
);
|
|
1117
|
+
if (useIntentCache) {
|
|
1118
|
+
intentDoneUntil.set(intentKey, this.now() + intentTtlMs);
|
|
1119
|
+
alipayLog.info("intent.cache", { flow, step: "payment-intent", hit: false, cachedForMs: intentTtlMs });
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
await this.checkWallet(signal, flow);
|
|
1123
|
+
const reqId = String(extra.out_trade_no ?? randomUUID());
|
|
1124
|
+
const dir = join2(this.configDir, "alipay");
|
|
1125
|
+
await mkdir(dir, { recursive: true });
|
|
1126
|
+
const challengeFile = join2(dir, `402_${reqId}.txt`);
|
|
1127
|
+
await writeFile(challengeFile, paymentNeededHeader, "utf-8");
|
|
1128
|
+
const payArgs = [
|
|
1129
|
+
"402-buyer-pay",
|
|
1130
|
+
"-f",
|
|
1131
|
+
challengeFile,
|
|
1132
|
+
"-r",
|
|
1133
|
+
resourceUrl,
|
|
1134
|
+
"-s",
|
|
1135
|
+
this.sessionId,
|
|
1136
|
+
"-i",
|
|
1137
|
+
intentSummary,
|
|
1138
|
+
"-w",
|
|
1139
|
+
this.framework
|
|
1140
|
+
];
|
|
1141
|
+
if (opts.method) payArgs.push("-m", opts.method);
|
|
1142
|
+
if (opts.data) payArgs.push("-d", opts.data);
|
|
1143
|
+
const payRun = await this.runner(payArgs, { onLine, signal, step: "402-buyer-pay", flow });
|
|
1144
|
+
const tradeNo = parseTradeNo(payRun.lines);
|
|
1145
|
+
if (!tradeNo) {
|
|
1146
|
+
throw new AlipayProtocolError("402-buyer-pay did not return a tradeNo");
|
|
1147
|
+
}
|
|
1148
|
+
assertTradeNo(tradeNo);
|
|
1149
|
+
const { paymentUrl, shortenUrl } = parsePaymentUrl(payRun.lines);
|
|
1150
|
+
if (paymentUrl) {
|
|
1151
|
+
alipayLog.info("flow.pending", { flow, tradeNo, ms: this.now() - flowStart });
|
|
1152
|
+
opts.onPaymentPending?.({ paymentUrl, shortenUrl, tradeNo });
|
|
1153
|
+
}
|
|
1154
|
+
const pendingAt = this.now();
|
|
1155
|
+
const windowMs = (requirement.maxTimeoutSeconds ?? 30 * 60) * 1e3;
|
|
1156
|
+
const deadline = this.now() + (opts.timeoutMs ?? windowMs);
|
|
1157
|
+
const poll = await pollUntil(tradeNo, resourceUrl, {
|
|
1158
|
+
// No onLine: the status-poll output embeds the resource and must not reach
|
|
1159
|
+
// the log stream — the body is surfaced via the return value below (§9.3).
|
|
1160
|
+
deadline,
|
|
1161
|
+
signal,
|
|
1162
|
+
runner: this.runner,
|
|
1163
|
+
now: this.now,
|
|
1164
|
+
// Re-fetch the resource the same way it was paid (POST + body), else the
|
|
1165
|
+
// status poll defaults to GET and 404s on a POST-only `/execute`.
|
|
1166
|
+
method: opts.method,
|
|
1167
|
+
data: opts.data
|
|
1168
|
+
});
|
|
1169
|
+
alipayLog.info("flow.settled", { flow, tradeNo, ms: this.now() - pendingAt });
|
|
1170
|
+
const body = extractBody(poll.lines);
|
|
1171
|
+
void this.runner(["402-buyer-fulfillment-ack", "-t", tradeNo], {
|
|
1172
|
+
onLine,
|
|
1173
|
+
signal,
|
|
1174
|
+
step: "402-buyer-fulfillment-ack",
|
|
1175
|
+
flow
|
|
1176
|
+
}).catch(() => void 0);
|
|
1177
|
+
return { body, payment: { tradeNo, outTradeNo: reqId }, media };
|
|
1178
|
+
}
|
|
1179
|
+
};
|
|
1180
|
+
|
|
1181
|
+
// src/client/wechat/index.ts
|
|
1182
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1183
|
+
import { mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
1184
|
+
import { homedir as homedir3 } from "os";
|
|
1185
|
+
import { join as join3 } from "path";
|
|
1186
|
+
var WECHAT_SCHEME = "wechatpay-native";
|
|
1187
|
+
var WECHAT_NETWORK = "wechat";
|
|
1188
|
+
var POLL_INTERVAL_MS2 = 3e3;
|
|
1189
|
+
var TIMEOUT_MS = 5 * 60 * 1e3;
|
|
1190
|
+
var WechatClient = class {
|
|
1191
|
+
configDir;
|
|
1192
|
+
sessionDir;
|
|
1193
|
+
now;
|
|
1194
|
+
constructor(options = {}) {
|
|
1195
|
+
this.configDir = options.configDir || join3(homedir3(), ".moltspay");
|
|
1196
|
+
this.sessionDir = join3(this.configDir, "wechat-sessions");
|
|
1197
|
+
this.now = options.now ?? Date.now;
|
|
1198
|
+
}
|
|
1199
|
+
async pay402(opts) {
|
|
1200
|
+
const session = this.start402({ ...opts });
|
|
1201
|
+
const result = await this.pollSession(session.paymentSessionId, {
|
|
1202
|
+
pollIntervalMs: opts.pollIntervalMs,
|
|
1203
|
+
timeoutMs: opts.timeoutMs,
|
|
1204
|
+
signal: opts.signal
|
|
1205
|
+
});
|
|
1206
|
+
if (result.status === "paid" || result.status === "completed") {
|
|
1207
|
+
return {
|
|
1208
|
+
body: result.resultBody ?? "",
|
|
1209
|
+
status: result.lastHttpStatus ?? 200
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
throw new Error(result.lastError || `WeChat payment ended with status ${result.status}`);
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Start a recoverable WeChat payment session. This returns immediately after
|
|
1216
|
+
* persisting `out_trade_no`, QR payload, original request body, and context.
|
|
1217
|
+
*/
|
|
1218
|
+
start402(opts) {
|
|
1219
|
+
const extra = opts.requirement.extra ?? {};
|
|
1220
|
+
const codeUrl = typeof extra.code_url === "string" ? extra.code_url : "";
|
|
1221
|
+
const outTradeNo = typeof extra.out_trade_no === "string" ? extra.out_trade_no : "";
|
|
1222
|
+
if (!codeUrl || !outTradeNo) {
|
|
1223
|
+
throw new Error(
|
|
1224
|
+
"WechatClient.pay402: wechatpay-native requirement is missing extra.code_url / extra.out_trade_no"
|
|
1225
|
+
);
|
|
1226
|
+
}
|
|
1227
|
+
const now = new Date(this.now());
|
|
1228
|
+
const timeoutMs = opts.timeoutMs ?? (opts.requirement.maxTimeoutSeconds ?? TIMEOUT_MS / 1e3) * 1e3;
|
|
1229
|
+
const session = {
|
|
1230
|
+
paymentSessionId: opts.paymentSessionId ?? `mpay_sess_${randomUUID2()}`,
|
|
1231
|
+
status: "pending",
|
|
1232
|
+
resourceUrl: opts.resourceUrl,
|
|
1233
|
+
method: opts.method ?? "POST",
|
|
1234
|
+
data: opts.data,
|
|
1235
|
+
requirement: opts.requirement,
|
|
1236
|
+
codeUrl,
|
|
1237
|
+
outTradeNo,
|
|
1238
|
+
createdAt: now.toISOString(),
|
|
1239
|
+
updatedAt: now.toISOString(),
|
|
1240
|
+
expiresAt: new Date(this.now() + timeoutMs).toISOString(),
|
|
1241
|
+
context: opts.context
|
|
1242
|
+
};
|
|
1243
|
+
this.saveSession(session);
|
|
1244
|
+
opts.onPaymentPending?.({ codeUrl, outTradeNo });
|
|
1245
|
+
return session;
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Query a persisted session once by replaying the original request with the
|
|
1249
|
+
* stored `out_trade_no` proof. 200 means paid + fulfilled; 402 means pending.
|
|
1250
|
+
*/
|
|
1251
|
+
async status(identifier) {
|
|
1252
|
+
const session = this.loadSession(identifier);
|
|
1253
|
+
if (session.status === "cancelled" || session.status === "completed") return session;
|
|
1254
|
+
if (this.now() >= new Date(session.expiresAt).getTime()) {
|
|
1255
|
+
return this.updateSession(session, {
|
|
1256
|
+
status: "expired",
|
|
1257
|
+
lastError: `WeChat payment expired at ${session.expiresAt}`
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1260
|
+
const xPayment = this.buildPaymentHeader(session);
|
|
1261
|
+
const res = await fetch(session.resourceUrl, {
|
|
1262
|
+
method: session.method,
|
|
1263
|
+
headers: { "Content-Type": "application/json", "X-Payment": xPayment },
|
|
1264
|
+
body: session.method === "POST" ? session.data : void 0
|
|
1265
|
+
});
|
|
1266
|
+
const text = await res.text().catch(() => "");
|
|
1267
|
+
if (res.status === 200) {
|
|
1268
|
+
return this.updateSession(session, {
|
|
1269
|
+
status: "completed",
|
|
1270
|
+
lastHttpStatus: res.status,
|
|
1271
|
+
lastError: void 0,
|
|
1272
|
+
resultBody: text
|
|
1273
|
+
});
|
|
1274
|
+
}
|
|
1275
|
+
if (res.status === 402) {
|
|
1276
|
+
return this.updateSession(session, {
|
|
1277
|
+
status: "pending",
|
|
1278
|
+
lastHttpStatus: res.status,
|
|
1279
|
+
lastError: text.slice(0, 500) || "wechat payment pending"
|
|
1280
|
+
});
|
|
1281
|
+
}
|
|
1282
|
+
return this.updateSession(session, {
|
|
1283
|
+
status: "failed",
|
|
1284
|
+
lastHttpStatus: res.status,
|
|
1285
|
+
lastError: `WeChat /execute returned HTTP ${res.status}: ${text.slice(0, 500)}`
|
|
1286
|
+
});
|
|
1287
|
+
}
|
|
1288
|
+
/** Poll a session until it completes, expires, fails, or is aborted. */
|
|
1289
|
+
async pollSession(identifier, opts = {}) {
|
|
1290
|
+
const first = this.loadSession(identifier);
|
|
1291
|
+
const deadline = Math.min(
|
|
1292
|
+
new Date(first.expiresAt).getTime(),
|
|
1293
|
+
this.now() + (opts.timeoutMs ?? TIMEOUT_MS)
|
|
1294
|
+
);
|
|
1295
|
+
const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS2;
|
|
1296
|
+
let session = first;
|
|
1297
|
+
while (this.now() < deadline) {
|
|
1298
|
+
if (opts.signal?.aborted) throw new Error("WeChat payment aborted");
|
|
1299
|
+
session = await this.status(session.paymentSessionId);
|
|
1300
|
+
if (session.status !== "pending") return session;
|
|
1301
|
+
await new Promise((r) => setTimeout(r, interval));
|
|
1302
|
+
}
|
|
1303
|
+
return this.updateSession(session, {
|
|
1304
|
+
status: "expired",
|
|
1305
|
+
lastError: `WeChat payment timed out after ${Math.round((opts.timeoutMs ?? TIMEOUT_MS) / 1e3)}s (out_trade_no=${session.outTradeNo}, last status ${session.lastHttpStatus ?? 0})`
|
|
1306
|
+
});
|
|
1307
|
+
}
|
|
1308
|
+
/** `fulfill` is an idempotent status check: paid sessions return stored body. */
|
|
1309
|
+
async fulfill(identifier) {
|
|
1310
|
+
const session = this.loadSession(identifier);
|
|
1311
|
+
if (session.status === "completed") return session;
|
|
1312
|
+
return this.status(identifier);
|
|
1313
|
+
}
|
|
1314
|
+
/** Mark a local session cancelled. Closing the merchant order is server-side. */
|
|
1315
|
+
cancel(identifier) {
|
|
1316
|
+
const session = this.loadSession(identifier);
|
|
1317
|
+
return this.updateSession(session, {
|
|
1318
|
+
status: "cancelled",
|
|
1319
|
+
lastError: "cancelled locally"
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
listSessions() {
|
|
1323
|
+
this.ensureSessionDir();
|
|
1324
|
+
return readdirSync(this.sessionDir).filter((name) => name.endsWith(".json")).map((name) => JSON.parse(readFileSync2(join3(this.sessionDir, name), "utf-8"))).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
1325
|
+
}
|
|
1326
|
+
buildPaymentHeader(session) {
|
|
1327
|
+
const proof = {
|
|
1328
|
+
x402Version: 2,
|
|
1329
|
+
scheme: WECHAT_SCHEME,
|
|
1330
|
+
network: WECHAT_NETWORK,
|
|
1331
|
+
accepted: {
|
|
1332
|
+
scheme: WECHAT_SCHEME,
|
|
1333
|
+
network: WECHAT_NETWORK,
|
|
1334
|
+
extra: { out_trade_no: session.outTradeNo }
|
|
1335
|
+
},
|
|
1336
|
+
payload: { out_trade_no: session.outTradeNo }
|
|
1337
|
+
};
|
|
1338
|
+
return Buffer.from(JSON.stringify(proof)).toString("base64");
|
|
1339
|
+
}
|
|
1340
|
+
loadSession(identifier) {
|
|
1341
|
+
this.ensureSessionDir();
|
|
1342
|
+
const direct = join3(this.sessionDir, `${identifier}.json`);
|
|
1343
|
+
try {
|
|
1344
|
+
return JSON.parse(readFileSync2(direct, "utf-8"));
|
|
1345
|
+
} catch {
|
|
1346
|
+
const byTradeNo = this.listSessions().find((s) => s.outTradeNo === identifier);
|
|
1347
|
+
if (byTradeNo) return byTradeNo;
|
|
1348
|
+
throw new Error(`WeChat payment session not found: ${identifier}`);
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
saveSession(session) {
|
|
1352
|
+
this.ensureSessionDir();
|
|
1353
|
+
writeFileSync2(
|
|
1354
|
+
join3(this.sessionDir, `${session.paymentSessionId}.json`),
|
|
1355
|
+
JSON.stringify(session, null, 2)
|
|
1356
|
+
);
|
|
1357
|
+
}
|
|
1358
|
+
updateSession(session, updates) {
|
|
1359
|
+
const next = {
|
|
1360
|
+
...session,
|
|
1361
|
+
...updates,
|
|
1362
|
+
updatedAt: new Date(this.now()).toISOString()
|
|
1363
|
+
};
|
|
1364
|
+
this.saveSession(next);
|
|
1365
|
+
return next;
|
|
1366
|
+
}
|
|
1367
|
+
ensureSessionDir() {
|
|
1368
|
+
mkdirSync2(this.sessionDir, { recursive: true });
|
|
1369
|
+
}
|
|
1370
|
+
};
|
|
1371
|
+
|
|
1372
|
+
// src/client/alipay/router.ts
|
|
1373
|
+
var ALIPAY_RAIL = "alipay";
|
|
1374
|
+
var WECHAT_RAIL = "wechat";
|
|
1375
|
+
var BALANCE_RAIL = "balance";
|
|
1376
|
+
function railOf(req) {
|
|
1377
|
+
if (req.scheme === "alipay-aipay" || req.network === ALIPAY_RAIL) return ALIPAY_RAIL;
|
|
1378
|
+
if (req.scheme === "wechatpay-native" || req.network === WECHAT_RAIL) return WECHAT_RAIL;
|
|
1379
|
+
if (req.scheme === BALANCE_RAIL || req.network === BALANCE_RAIL) return BALANCE_RAIL;
|
|
1380
|
+
return networkToChainName(req.network) ?? req.network;
|
|
1381
|
+
}
|
|
1382
|
+
function findRail(accepts, rail) {
|
|
1383
|
+
const requirement = accepts.find((r) => railOf(r) === rail);
|
|
1384
|
+
return requirement ? { rail, requirement } : null;
|
|
1385
|
+
}
|
|
1386
|
+
function selectRail(input) {
|
|
1387
|
+
const { serverAccepts, explicitRail, preference, availability } = input;
|
|
1388
|
+
if (!serverAccepts || serverAccepts.length === 0) {
|
|
1389
|
+
throw new UnsupportedRailError(explicitRail ?? "unknown", "Server offered no payment options");
|
|
1390
|
+
}
|
|
1391
|
+
if (explicitRail) {
|
|
1392
|
+
const hit = findRail(serverAccepts, explicitRail);
|
|
1393
|
+
if (!hit) {
|
|
1394
|
+
const offered = serverAccepts.map(railOf);
|
|
1395
|
+
throw new UnsupportedRailError(
|
|
1396
|
+
explicitRail,
|
|
1397
|
+
`Server doesn't accept rail '${explicitRail}'. Offered: ${offered.join(", ")}`
|
|
1398
|
+
);
|
|
1399
|
+
}
|
|
1400
|
+
return hit;
|
|
1401
|
+
}
|
|
1402
|
+
if (preference) {
|
|
1403
|
+
for (const pref of preference) {
|
|
1404
|
+
const hit = findRail(serverAccepts, pref);
|
|
1405
|
+
if (hit) return hit;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
if (availability?.evmReady) {
|
|
1409
|
+
const evm = serverAccepts.find((r) => railOf(r) !== ALIPAY_RAIL);
|
|
1410
|
+
if (evm) return { rail: railOf(evm), requirement: evm };
|
|
1411
|
+
}
|
|
1412
|
+
if (availability?.alipayReady) {
|
|
1413
|
+
const hit = findRail(serverAccepts, ALIPAY_RAIL);
|
|
1414
|
+
if (hit) return hit;
|
|
1415
|
+
}
|
|
1416
|
+
return { rail: railOf(serverAccepts[0]), requirement: serverAccepts[0] };
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// src/facilitators/balance/auth.ts
|
|
1420
|
+
import { ethers as ethers2 } from "ethers";
|
|
1421
|
+
var BALANCE_AUTH_DOMAIN = "moltspay-balance-auth:v1";
|
|
1422
|
+
var BALANCE_AUTH_MAX_SKEW_MS = 5 * 60 * 1e3;
|
|
1423
|
+
function buildDeductMessage(f) {
|
|
1424
|
+
return [BALANCE_AUTH_DOMAIN, "balance-deduct", f.buyerId, f.requestId, f.service, String(f.timestamp)].join("\n");
|
|
1425
|
+
}
|
|
1426
|
+
|
|
486
1427
|
// src/client/node/index.ts
|
|
487
1428
|
var DEFAULT_CONFIG = {
|
|
488
1429
|
chain: "base",
|
|
@@ -499,9 +1440,13 @@ var MoltsPayClient = class {
|
|
|
499
1440
|
signer = null;
|
|
500
1441
|
todaySpending = 0;
|
|
501
1442
|
lastSpendingReset = 0;
|
|
1443
|
+
railPreference;
|
|
1444
|
+
alipaySessionId;
|
|
502
1445
|
constructor(options = {}) {
|
|
503
|
-
this.configDir = options.configDir ||
|
|
1446
|
+
this.configDir = options.configDir || join4(homedir4(), ".moltspay");
|
|
504
1447
|
this.config = this.loadConfig();
|
|
1448
|
+
this.railPreference = options.railPreference ?? this.config.railPreference;
|
|
1449
|
+
this.alipaySessionId = options.alipaySessionId;
|
|
505
1450
|
this.walletData = this.loadWallet();
|
|
506
1451
|
this.loadSpending();
|
|
507
1452
|
if (this.walletData) {
|
|
@@ -579,6 +1524,15 @@ var MoltsPayClient = class {
|
|
|
579
1524
|
* @param options - Payment options (token selection)
|
|
580
1525
|
*/
|
|
581
1526
|
async pay(serverUrl, service, params, options = {}) {
|
|
1527
|
+
if (options.rail === ALIPAY_RAIL) {
|
|
1528
|
+
return this.payViaAlipay(serverUrl, service, params, options);
|
|
1529
|
+
}
|
|
1530
|
+
if (options.rail === WECHAT_RAIL) {
|
|
1531
|
+
return this.payViaWechat(serverUrl, service, params, options);
|
|
1532
|
+
}
|
|
1533
|
+
if (options.rail === BALANCE_RAIL) {
|
|
1534
|
+
return this.payViaBalance(serverUrl, service, params, options);
|
|
1535
|
+
}
|
|
582
1536
|
if (!this.wallet || !this.walletData) {
|
|
583
1537
|
throw new Error("Client not initialized. Run: npx moltspay init");
|
|
584
1538
|
}
|
|
@@ -770,6 +1724,469 @@ Please specify: --chain <chain_name>`
|
|
|
770
1724
|
console.log(`[MoltsPay] Success! Payment: ${result.payment?.status || "claimed"}`);
|
|
771
1725
|
return result.result || result;
|
|
772
1726
|
}
|
|
1727
|
+
/**
|
|
1728
|
+
* Pay for a service over the Alipay fiat rail (2.0.0).
|
|
1729
|
+
*
|
|
1730
|
+
* Unlike the crypto path this needs no EVM wallet — it shells out to
|
|
1731
|
+
* alipay-bot via {@link AlipayClient}. Flow: hit the resource with no
|
|
1732
|
+
* payment to get the 402 challenge, confirm the server actually offers the
|
|
1733
|
+
* alipay rail (selectRail), then run the 8-step state machine and return the
|
|
1734
|
+
* resource body.
|
|
1735
|
+
*/
|
|
1736
|
+
async payViaAlipay(serverUrl, service, params, options) {
|
|
1737
|
+
const flow = this.alipaySessionId;
|
|
1738
|
+
let executeUrl = `${serverUrl}/execute`;
|
|
1739
|
+
try {
|
|
1740
|
+
const services = await timeStep(
|
|
1741
|
+
"discover-services",
|
|
1742
|
+
flow,
|
|
1743
|
+
() => this.getServices(serverUrl)
|
|
1744
|
+
);
|
|
1745
|
+
const svc = services.services?.find((s) => s.id === service);
|
|
1746
|
+
if (svc?.endpoint) executeUrl = `${serverUrl}${svc.endpoint}`;
|
|
1747
|
+
} catch {
|
|
1748
|
+
}
|
|
1749
|
+
const requestBody = options.rawData ? { service, ...params } : { service, params };
|
|
1750
|
+
const bodyJson = JSON.stringify(requestBody);
|
|
1751
|
+
const res = await timeStep(
|
|
1752
|
+
"challenge-402",
|
|
1753
|
+
flow,
|
|
1754
|
+
() => fetch(executeUrl, {
|
|
1755
|
+
method: "POST",
|
|
1756
|
+
headers: { "Content-Type": "application/json" },
|
|
1757
|
+
body: bodyJson
|
|
1758
|
+
})
|
|
1759
|
+
);
|
|
1760
|
+
if (res.status !== 402) {
|
|
1761
|
+
const data = await res.json().catch(() => ({}));
|
|
1762
|
+
if (res.ok && data.result) return data.result;
|
|
1763
|
+
throw new Error(data.error || `Expected 402, got ${res.status}`);
|
|
1764
|
+
}
|
|
1765
|
+
const header = res.headers.get(PAYMENT_REQUIRED_HEADER);
|
|
1766
|
+
if (!header) throw new Error("Missing x-payment-required header on 402");
|
|
1767
|
+
const parsed = JSON.parse(Buffer.from(header, "base64").toString("utf-8"));
|
|
1768
|
+
const accepts = Array.isArray(parsed) ? parsed : parsed.accepts ?? [parsed];
|
|
1769
|
+
const { requirement } = selectRail({
|
|
1770
|
+
serverAccepts: accepts,
|
|
1771
|
+
explicitRail: ALIPAY_RAIL,
|
|
1772
|
+
preference: this.railPreference,
|
|
1773
|
+
availability: { evmReady: this.isInitialized }
|
|
1774
|
+
});
|
|
1775
|
+
const onLine = options.onLine ?? ((line) => process.stdout.write(line + "\n"));
|
|
1776
|
+
const alipay = new AlipayClient({
|
|
1777
|
+
sessionId: this.alipaySessionId,
|
|
1778
|
+
configDir: this.configDir
|
|
1779
|
+
});
|
|
1780
|
+
const result = await alipay.pay402({
|
|
1781
|
+
resourceUrl: executeUrl,
|
|
1782
|
+
requirement,
|
|
1783
|
+
method: "POST",
|
|
1784
|
+
data: bodyJson,
|
|
1785
|
+
onLine,
|
|
1786
|
+
onPaymentPending: options.onPaymentPending,
|
|
1787
|
+
timeoutMs: options.timeoutMs,
|
|
1788
|
+
signal: options.signal
|
|
1789
|
+
});
|
|
1790
|
+
try {
|
|
1791
|
+
const json = JSON.parse(result.body);
|
|
1792
|
+
return json.result ?? json;
|
|
1793
|
+
} catch {
|
|
1794
|
+
return { body: result.body, payment: result.payment, media: result.media };
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
/**
|
|
1798
|
+
* Pay for a service over the WeChat Pay Native fiat rail (2.1.0).
|
|
1799
|
+
*
|
|
1800
|
+
* Mirrors {@link payViaAlipay} and needs no EVM wallet. The server placed the
|
|
1801
|
+
* Native order when it built the 402, so its `wechatpay-native` accepts[]
|
|
1802
|
+
* entry already carries `extra.code_url` + `extra.out_trade_no`. Flow: hit the
|
|
1803
|
+
* resource to get the 402, confirm the server offers the wechat rail, surface
|
|
1804
|
+
* the code_url (caller renders a QR), then poll the resource with the
|
|
1805
|
+
* out_trade_no proof until the server verifies the order paid and delivers.
|
|
1806
|
+
*/
|
|
1807
|
+
async payViaWechat(serverUrl, service, params, options) {
|
|
1808
|
+
const session = await this.startWechatPayment(serverUrl, service, params, options);
|
|
1809
|
+
const wechat = new WechatClient({ configDir: this.configDir });
|
|
1810
|
+
const result = await wechat.pollSession(session.paymentSessionId, {
|
|
1811
|
+
timeoutMs: options.timeoutMs,
|
|
1812
|
+
signal: options.signal
|
|
1813
|
+
});
|
|
1814
|
+
if (result.status !== "completed") {
|
|
1815
|
+
throw new Error(result.lastError || `WeChat payment ended with status ${result.status}`);
|
|
1816
|
+
}
|
|
1817
|
+
try {
|
|
1818
|
+
const json = JSON.parse(result.resultBody ?? "");
|
|
1819
|
+
return json.result ?? json;
|
|
1820
|
+
} catch {
|
|
1821
|
+
return { body: result.resultBody ?? "" };
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
/**
|
|
1825
|
+
* The ethers wallet used to sign balance-rail deductions: the client's EVM
|
|
1826
|
+
* wallet if it has one, else a per-configDir identity key persisted at
|
|
1827
|
+
* `<configDir>/balance-identity.key` (0600) so a balance-only client works
|
|
1828
|
+
* without a full crypto wallet. Under `agent 统一代付`, one key spends every
|
|
1829
|
+
* account the agent tops up.
|
|
1830
|
+
*/
|
|
1831
|
+
balanceSigner() {
|
|
1832
|
+
if (this.wallet) return this.wallet;
|
|
1833
|
+
const p = join4(this.configDir, "balance-identity.key");
|
|
1834
|
+
let pk;
|
|
1835
|
+
if (existsSync2(p)) {
|
|
1836
|
+
pk = readFileSync3(p, "utf-8").trim();
|
|
1837
|
+
} else {
|
|
1838
|
+
mkdirSync3(this.configDir, { recursive: true });
|
|
1839
|
+
pk = Wallet2.createRandom().privateKey;
|
|
1840
|
+
writeFileSync3(p, pk, { mode: 384 });
|
|
1841
|
+
}
|
|
1842
|
+
return new Wallet2(pk);
|
|
1843
|
+
}
|
|
1844
|
+
/** The balance-rail spending signer address (lowercase 0x…). Stable per
|
|
1845
|
+
* configDir; this is the identity the server TOFU-binds and later verifies. */
|
|
1846
|
+
getBalanceSignerAddress() {
|
|
1847
|
+
return this.balanceSigner().address.toLowerCase();
|
|
1848
|
+
}
|
|
1849
|
+
/** The buyer id for the balance rail: explicit option > persisted config. */
|
|
1850
|
+
resolveBuyerId(explicit) {
|
|
1851
|
+
const buyerId = explicit ?? this.config.buyerId;
|
|
1852
|
+
if (!buyerId) {
|
|
1853
|
+
throw new Error(
|
|
1854
|
+
"Balance rail needs a buyer id. Pass { buyerId } or persist one with setBuyerId()."
|
|
1855
|
+
);
|
|
1856
|
+
}
|
|
1857
|
+
return buyerId;
|
|
1858
|
+
}
|
|
1859
|
+
/**
|
|
1860
|
+
* Pay via the custodial balance rail (2.2.0, password-free).
|
|
1861
|
+
*
|
|
1862
|
+
* No wallet, no QR: the request carries `{buyer_id, request_id}` in the
|
|
1863
|
+
* X-Payment payload and the server deducts the prepaid balance atomically
|
|
1864
|
+
* before running the skill. The client-generated `request_id` makes the
|
|
1865
|
+
* charge idempotent — a network retry can never double-deduct.
|
|
1866
|
+
*/
|
|
1867
|
+
async payViaBalance(serverUrl, service, params, options) {
|
|
1868
|
+
const buyerId = this.resolveBuyerId(options.buyerId);
|
|
1869
|
+
let attempt = await this.balanceDeduct(serverUrl, service, params, options, buyerId);
|
|
1870
|
+
if (attempt.ok) return attempt.result;
|
|
1871
|
+
const fundable = attempt.status === 402 && (attempt.code === "buyer_not_found" || attempt.code === "insufficient_balance" || /insufficient balance|unknown buyer|top up first/i.test(attempt.error || ""));
|
|
1872
|
+
if (!fundable || options.autoTopup === false) {
|
|
1873
|
+
throw new Error(attempt.error || `Balance payment failed with HTTP ${attempt.status}`);
|
|
1874
|
+
}
|
|
1875
|
+
if (options.topupMode === "manual") {
|
|
1876
|
+
const order = await this.createBalanceTopupOrder(serverUrl, {
|
|
1877
|
+
pack: options.topupPack,
|
|
1878
|
+
buyerId,
|
|
1879
|
+
context: { service }
|
|
1880
|
+
});
|
|
1881
|
+
options.onTopupRequired?.(order.pack, order.codeUrl);
|
|
1882
|
+
return {
|
|
1883
|
+
status: "topup_required",
|
|
1884
|
+
out_trade_no: order.outTradeNo,
|
|
1885
|
+
code_url: order.codeUrl,
|
|
1886
|
+
pack: order.pack,
|
|
1887
|
+
server_url: serverUrl
|
|
1888
|
+
};
|
|
1889
|
+
}
|
|
1890
|
+
const credited = await this.topupBalancePack(serverUrl, {
|
|
1891
|
+
pack: options.topupPack,
|
|
1892
|
+
buyerId,
|
|
1893
|
+
pollIntervalMs: options.topupPollIntervalMs,
|
|
1894
|
+
signal: options.signal,
|
|
1895
|
+
onCodeUrl: (pack, codeUrl) => options.onTopupRequired?.(pack, codeUrl)
|
|
1896
|
+
});
|
|
1897
|
+
options.onTopupCredited?.(credited.balance);
|
|
1898
|
+
attempt = await this.balanceDeduct(serverUrl, service, params, options, buyerId);
|
|
1899
|
+
if (attempt.ok) return attempt.result;
|
|
1900
|
+
throw new Error(attempt.error || "Balance payment failed after top-up");
|
|
1901
|
+
}
|
|
1902
|
+
/** One password-free deduct attempt. Never throws on an HTTP error; the
|
|
1903
|
+
* caller inspects `{ ok, status, error }` to decide whether to auto-fund. */
|
|
1904
|
+
async balanceDeduct(serverUrl, service, params, options, buyerId) {
|
|
1905
|
+
let executeUrl = `${serverUrl}/execute`;
|
|
1906
|
+
try {
|
|
1907
|
+
const services = await this.getServices(serverUrl);
|
|
1908
|
+
const svc = services.services?.find((s) => s.id === service);
|
|
1909
|
+
if (svc?.endpoint) executeUrl = `${serverUrl}${svc.endpoint}`;
|
|
1910
|
+
} catch {
|
|
1911
|
+
}
|
|
1912
|
+
const requestBody = options.rawData ? { service, ...params } : { service, params };
|
|
1913
|
+
const requestId = randomUUID3();
|
|
1914
|
+
const timestamp = Math.floor(Date.now() / 1e3);
|
|
1915
|
+
const signature = await this.balanceSigner().signMessage(
|
|
1916
|
+
buildDeductMessage({ buyerId, requestId, service, timestamp })
|
|
1917
|
+
);
|
|
1918
|
+
const xPayment = Buffer.from(JSON.stringify({
|
|
1919
|
+
x402Version: 2,
|
|
1920
|
+
scheme: BALANCE_RAIL,
|
|
1921
|
+
network: BALANCE_RAIL,
|
|
1922
|
+
payload: { buyer_id: buyerId, request_id: requestId, auth: { timestamp, signature } }
|
|
1923
|
+
})).toString("base64");
|
|
1924
|
+
const res = await fetch(executeUrl, {
|
|
1925
|
+
method: "POST",
|
|
1926
|
+
headers: { "Content-Type": "application/json", "X-Payment": xPayment },
|
|
1927
|
+
body: JSON.stringify(requestBody),
|
|
1928
|
+
signal: options.signal
|
|
1929
|
+
});
|
|
1930
|
+
const data = await res.json().catch(() => ({}));
|
|
1931
|
+
if (!res.ok) return { ok: false, status: res.status, error: data.error, code: data.code };
|
|
1932
|
+
return { ok: true, status: res.status, result: data.result ?? data };
|
|
1933
|
+
}
|
|
1934
|
+
/**
|
|
1935
|
+
* Non-blocking: POST /balance/topup/order, persist a recoverable session, and
|
|
1936
|
+
* return at once (no polling). Use with {@link confirmBalanceTopup} for
|
|
1937
|
+
* turn-based agents; the blocking {@link topupBalancePack} is built on this.
|
|
1938
|
+
*/
|
|
1939
|
+
async createBalanceTopupOrder(serverUrl, opts = {}) {
|
|
1940
|
+
const id = this.resolveBuyerId(opts.buyerId);
|
|
1941
|
+
const orderRes = await fetch(`${serverUrl}/balance/topup/order`, {
|
|
1942
|
+
method: "POST",
|
|
1943
|
+
headers: { "Content-Type": "application/json" },
|
|
1944
|
+
// Carry the spending signer so the server binds it to the account on
|
|
1945
|
+
// confirm (topup-time binding). The same key signs deductions later.
|
|
1946
|
+
body: JSON.stringify({ buyer_id: id, pack: opts.pack, signer_address: this.getBalanceSignerAddress() })
|
|
1947
|
+
});
|
|
1948
|
+
const order = await orderRes.json().catch(() => ({}));
|
|
1949
|
+
if (!orderRes.ok) throw new Error(order.error || `Top-up order failed with HTTP ${orderRes.status}`);
|
|
1950
|
+
const maxTimeoutSeconds = order.max_timeout_seconds ?? 300;
|
|
1951
|
+
const now = Date.now();
|
|
1952
|
+
this.saveBalanceTopupSession({
|
|
1953
|
+
out_trade_no: order.out_trade_no,
|
|
1954
|
+
buyer_id: id,
|
|
1955
|
+
pack: order.pack,
|
|
1956
|
+
server_url: serverUrl,
|
|
1957
|
+
code_url: order.code_url,
|
|
1958
|
+
status: "pending",
|
|
1959
|
+
created_at: new Date(now).toISOString(),
|
|
1960
|
+
expires_at: new Date(now + maxTimeoutSeconds * 1e3).toISOString(),
|
|
1961
|
+
context: opts.context
|
|
1962
|
+
});
|
|
1963
|
+
return { outTradeNo: order.out_trade_no, codeUrl: order.code_url, pack: order.pack, maxTimeoutSeconds };
|
|
1964
|
+
}
|
|
1965
|
+
/**
|
|
1966
|
+
* One-shot: POST /balance/topup/confirm for a single order. No polling.
|
|
1967
|
+
* Updates the persisted session on credit. `serverUrl` defaults to the one
|
|
1968
|
+
* recorded in the session (recover by out_trade_no alone).
|
|
1969
|
+
*/
|
|
1970
|
+
async confirmBalanceTopup(outTradeNo, opts = {}) {
|
|
1971
|
+
const session = this.getBalanceTopupSession(outTradeNo);
|
|
1972
|
+
const serverUrl = opts.serverUrl || session?.server_url;
|
|
1973
|
+
if (!serverUrl) {
|
|
1974
|
+
return { credited: false, reason: `No server URL for ${outTradeNo}: pass serverUrl or run topup-order first` };
|
|
1975
|
+
}
|
|
1976
|
+
const confRes = await fetch(`${serverUrl}/balance/topup/confirm`, {
|
|
1977
|
+
method: "POST",
|
|
1978
|
+
headers: { "Content-Type": "application/json" },
|
|
1979
|
+
body: JSON.stringify({ out_trade_no: outTradeNo })
|
|
1980
|
+
});
|
|
1981
|
+
const conf = await confRes.json().catch(() => ({}));
|
|
1982
|
+
if (!confRes.ok) return { credited: false, reason: conf.error || `Confirm failed with HTTP ${confRes.status}` };
|
|
1983
|
+
if (conf.credited) {
|
|
1984
|
+
if (session) {
|
|
1985
|
+
session.status = "credited";
|
|
1986
|
+
session.tx_id = conf.tx_id;
|
|
1987
|
+
session.balance = conf.balance;
|
|
1988
|
+
this.saveBalanceTopupSession(session);
|
|
1989
|
+
}
|
|
1990
|
+
return { credited: true, balance: conf.balance, txId: conf.tx_id };
|
|
1991
|
+
}
|
|
1992
|
+
return { credited: false, pending: !!conf.pending, reason: conf.reason };
|
|
1993
|
+
}
|
|
1994
|
+
/**
|
|
1995
|
+
* Blocking terminal wrapper: create the order then poll confirm until the
|
|
1996
|
+
* scan is credited (or the order expires). Built on
|
|
1997
|
+
* {@link createBalanceTopupOrder} + {@link confirmBalanceTopup}.
|
|
1998
|
+
*/
|
|
1999
|
+
async topupBalancePack(serverUrl, opts = {}) {
|
|
2000
|
+
const order = await this.createBalanceTopupOrder(serverUrl, { pack: opts.pack, buyerId: opts.buyerId });
|
|
2001
|
+
opts.onCodeUrl?.(order.pack, order.codeUrl);
|
|
2002
|
+
const interval = opts.pollIntervalMs ?? 2e3;
|
|
2003
|
+
const deadline = Date.now() + order.maxTimeoutSeconds * 1e3;
|
|
2004
|
+
while (Date.now() < deadline) {
|
|
2005
|
+
if (opts.signal?.aborted) throw new Error("Top-up aborted");
|
|
2006
|
+
const conf = await this.confirmBalanceTopup(order.outTradeNo, { serverUrl });
|
|
2007
|
+
if (conf.credited) return { balance: conf.balance, outTradeNo: order.outTradeNo, txId: conf.txId };
|
|
2008
|
+
await this.sleep(interval, opts.signal);
|
|
2009
|
+
}
|
|
2010
|
+
throw new Error("Top-up timed out before the payment was confirmed");
|
|
2011
|
+
}
|
|
2012
|
+
// --- Recoverable balance top-up sessions (<configDir>/balance-topup-sessions) ---
|
|
2013
|
+
balanceTopupSessionDir() {
|
|
2014
|
+
return join4(this.configDir, "balance-topup-sessions");
|
|
2015
|
+
}
|
|
2016
|
+
saveBalanceTopupSession(session) {
|
|
2017
|
+
const dir = this.balanceTopupSessionDir();
|
|
2018
|
+
mkdirSync3(dir, { recursive: true });
|
|
2019
|
+
writeFileSync3(join4(dir, `${session.out_trade_no}.json`), JSON.stringify(session, null, 2));
|
|
2020
|
+
}
|
|
2021
|
+
/** Read a persisted top-up session by out_trade_no, or null. */
|
|
2022
|
+
getBalanceTopupSession(outTradeNo) {
|
|
2023
|
+
const p = join4(this.balanceTopupSessionDir(), `${outTradeNo}.json`);
|
|
2024
|
+
if (!existsSync2(p)) return null;
|
|
2025
|
+
try {
|
|
2026
|
+
return JSON.parse(readFileSync3(p, "utf-8"));
|
|
2027
|
+
} catch {
|
|
2028
|
+
return null;
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
/** List persisted top-up sessions, newest first. */
|
|
2032
|
+
listBalanceTopupSessions() {
|
|
2033
|
+
const dir = this.balanceTopupSessionDir();
|
|
2034
|
+
if (!existsSync2(dir)) return [];
|
|
2035
|
+
return readdirSync2(dir).filter((f) => f.endsWith(".json")).map((f) => {
|
|
2036
|
+
try {
|
|
2037
|
+
return JSON.parse(readFileSync3(join4(dir, f), "utf-8"));
|
|
2038
|
+
} catch {
|
|
2039
|
+
return null;
|
|
2040
|
+
}
|
|
2041
|
+
}).filter((s) => s !== null).sort((a, b) => (b.created_at || "").localeCompare(a.created_at || ""));
|
|
2042
|
+
}
|
|
2043
|
+
/** Abortable sleep used by the top-up poll loop. */
|
|
2044
|
+
sleep(ms, signal) {
|
|
2045
|
+
return new Promise((resolve, reject) => {
|
|
2046
|
+
if (signal?.aborted) return reject(new Error("aborted"));
|
|
2047
|
+
const t = setTimeout(resolve, ms);
|
|
2048
|
+
signal?.addEventListener("abort", () => {
|
|
2049
|
+
clearTimeout(t);
|
|
2050
|
+
reject(new Error("aborted"));
|
|
2051
|
+
}, { once: true });
|
|
2052
|
+
});
|
|
2053
|
+
}
|
|
2054
|
+
/** Persist the buyer id used by the balance rail (bearer semantics). */
|
|
2055
|
+
setBuyerId(buyerId) {
|
|
2056
|
+
this.config.buyerId = buyerId;
|
|
2057
|
+
this.saveConfig();
|
|
2058
|
+
}
|
|
2059
|
+
/** GET /balance — custodial balance, limits, and today's spend for a buyer. */
|
|
2060
|
+
async getBuyerBalance(serverUrl, buyerId) {
|
|
2061
|
+
const id = this.resolveBuyerId(buyerId);
|
|
2062
|
+
const res = await fetch(`${serverUrl}/balance?buyer_id=${encodeURIComponent(id)}`);
|
|
2063
|
+
const data = await res.json().catch(() => ({}));
|
|
2064
|
+
if (!res.ok) throw new Error(data.error || `Balance query failed with HTTP ${res.status}`);
|
|
2065
|
+
return data;
|
|
2066
|
+
}
|
|
2067
|
+
/**
|
|
2068
|
+
* POST /balance/topup — report an externally settled payment (on-chain
|
|
2069
|
+
* tx hash / Alipay trade_no / WeChat out_trade_no) so the server verifies
|
|
2070
|
+
* and credits the ledger. Idempotent per reference.
|
|
2071
|
+
*/
|
|
2072
|
+
async topupBalance(serverUrl, opts) {
|
|
2073
|
+
const id = this.resolveBuyerId(opts.buyerId);
|
|
2074
|
+
const res = await fetch(`${serverUrl}/balance/topup`, {
|
|
2075
|
+
method: "POST",
|
|
2076
|
+
headers: { "Content-Type": "application/json" },
|
|
2077
|
+
body: JSON.stringify({
|
|
2078
|
+
buyer_id: id,
|
|
2079
|
+
rail: opts.rail,
|
|
2080
|
+
amount: opts.amount,
|
|
2081
|
+
tx_hash: opts.txHash,
|
|
2082
|
+
chain: opts.chain,
|
|
2083
|
+
trade_no: opts.tradeNo,
|
|
2084
|
+
out_trade_no: opts.outTradeNo
|
|
2085
|
+
})
|
|
2086
|
+
});
|
|
2087
|
+
const data = await res.json().catch(() => ({}));
|
|
2088
|
+
if (!res.ok) throw new Error(data.error || `Top-up failed with HTTP ${res.status}`);
|
|
2089
|
+
return data;
|
|
2090
|
+
}
|
|
2091
|
+
/** GET /balance/transactions — ledger history for a buyer, newest first. */
|
|
2092
|
+
async listBalanceTransactions(serverUrl, opts = {}) {
|
|
2093
|
+
const id = this.resolveBuyerId(opts.buyerId);
|
|
2094
|
+
const qs = new URLSearchParams({ buyer_id: id });
|
|
2095
|
+
if (opts.limit) qs.set("limit", String(opts.limit));
|
|
2096
|
+
if (opts.offset) qs.set("offset", String(opts.offset));
|
|
2097
|
+
const res = await fetch(`${serverUrl}/balance/transactions?${qs}`);
|
|
2098
|
+
const data = await res.json().catch(() => ({}));
|
|
2099
|
+
if (!res.ok) throw new Error(data.error || `Transaction query failed with HTTP ${res.status}`);
|
|
2100
|
+
return data;
|
|
2101
|
+
}
|
|
2102
|
+
/**
|
|
2103
|
+
* Start a recoverable WeChat Pay Native session and return immediately with
|
|
2104
|
+
* QR metadata. The SDK client persists enough context to poll/fulfill later.
|
|
2105
|
+
*/
|
|
2106
|
+
async startWechatPayment(serverUrl, service, params, options = {}) {
|
|
2107
|
+
let executeUrl = `${serverUrl}/execute`;
|
|
2108
|
+
try {
|
|
2109
|
+
const services = await this.getServices(serverUrl);
|
|
2110
|
+
const svc = services.services?.find((s) => s.id === service);
|
|
2111
|
+
if (svc?.endpoint) executeUrl = `${serverUrl}${svc.endpoint}`;
|
|
2112
|
+
} catch {
|
|
2113
|
+
}
|
|
2114
|
+
const requestBody = options.rawData ? { service, ...params } : { service, params };
|
|
2115
|
+
const bodyJson = JSON.stringify(requestBody);
|
|
2116
|
+
const res = await fetch(executeUrl, {
|
|
2117
|
+
method: "POST",
|
|
2118
|
+
headers: { "Content-Type": "application/json" },
|
|
2119
|
+
body: bodyJson
|
|
2120
|
+
});
|
|
2121
|
+
if (res.status !== 402) {
|
|
2122
|
+
const data = await res.json().catch(() => ({}));
|
|
2123
|
+
if (res.ok && data.result) return data.result;
|
|
2124
|
+
throw new Error(data.error || `Expected 402, got ${res.status}`);
|
|
2125
|
+
}
|
|
2126
|
+
const header = res.headers.get(PAYMENT_REQUIRED_HEADER);
|
|
2127
|
+
if (!header) throw new Error("Missing x-payment-required header on 402");
|
|
2128
|
+
const parsed = JSON.parse(Buffer.from(header, "base64").toString("utf-8"));
|
|
2129
|
+
const accepts = Array.isArray(parsed) ? parsed : parsed.accepts ?? [parsed];
|
|
2130
|
+
const { requirement } = selectRail({
|
|
2131
|
+
serverAccepts: accepts,
|
|
2132
|
+
explicitRail: WECHAT_RAIL,
|
|
2133
|
+
preference: this.railPreference,
|
|
2134
|
+
availability: { evmReady: this.isInitialized }
|
|
2135
|
+
});
|
|
2136
|
+
const wechat = new WechatClient({ configDir: this.configDir });
|
|
2137
|
+
const session = wechat.start402({
|
|
2138
|
+
resourceUrl: executeUrl,
|
|
2139
|
+
requirement,
|
|
2140
|
+
method: "POST",
|
|
2141
|
+
data: bodyJson,
|
|
2142
|
+
onPaymentPending: options.onPaymentPending ? (info) => options.onPaymentPending({ paymentUrl: info.codeUrl, tradeNo: info.outTradeNo }) : void 0,
|
|
2143
|
+
timeoutMs: options.timeoutMs,
|
|
2144
|
+
signal: options.signal,
|
|
2145
|
+
context: {
|
|
2146
|
+
serverUrl,
|
|
2147
|
+
service,
|
|
2148
|
+
params,
|
|
2149
|
+
rawData: options.rawData ?? false,
|
|
2150
|
+
rail: WECHAT_RAIL
|
|
2151
|
+
}
|
|
2152
|
+
});
|
|
2153
|
+
if (options.autoPoll || options.onWechatPaymentCompleted || options.onWechatPaymentFailed) {
|
|
2154
|
+
void wechat.pollSession(session.paymentSessionId, {
|
|
2155
|
+
timeoutMs: options.timeoutMs,
|
|
2156
|
+
signal: options.signal
|
|
2157
|
+
}).then(async (finalSession) => {
|
|
2158
|
+
if (finalSession.status === "completed") {
|
|
2159
|
+
await options.onWechatPaymentCompleted?.(finalSession);
|
|
2160
|
+
} else {
|
|
2161
|
+
await options.onWechatPaymentFailed?.(finalSession);
|
|
2162
|
+
}
|
|
2163
|
+
}).catch(async (error) => {
|
|
2164
|
+
const failed = await wechat.fulfill(session.paymentSessionId).catch(() => ({
|
|
2165
|
+
...session,
|
|
2166
|
+
status: "failed",
|
|
2167
|
+
lastError: error instanceof Error ? error.message : String(error)
|
|
2168
|
+
}));
|
|
2169
|
+
await options.onWechatPaymentFailed?.(failed);
|
|
2170
|
+
});
|
|
2171
|
+
}
|
|
2172
|
+
return session;
|
|
2173
|
+
}
|
|
2174
|
+
/** Query a persisted WeChat session once. */
|
|
2175
|
+
async getWechatPaymentStatus(identifier) {
|
|
2176
|
+
return new WechatClient({ configDir: this.configDir }).status(identifier);
|
|
2177
|
+
}
|
|
2178
|
+
/** Idempotently fulfill a paid WeChat session, returning stored or fetched result. */
|
|
2179
|
+
async fulfillWechatPayment(identifier) {
|
|
2180
|
+
return new WechatClient({ configDir: this.configDir }).fulfill(identifier);
|
|
2181
|
+
}
|
|
2182
|
+
/** Mark a local WeChat session as cancelled. */
|
|
2183
|
+
cancelWechatPayment(identifier) {
|
|
2184
|
+
return new WechatClient({ configDir: this.configDir }).cancel(identifier);
|
|
2185
|
+
}
|
|
2186
|
+
/** List persisted WeChat sessions, newest first. */
|
|
2187
|
+
listWechatPaymentSessions() {
|
|
2188
|
+
return new WechatClient({ configDir: this.configDir }).listSessions();
|
|
2189
|
+
}
|
|
773
2190
|
/**
|
|
774
2191
|
* Handle MPP (Machine Payments Protocol) payment flow
|
|
775
2192
|
* Called when pay() detects WWW-Authenticate header in 402 response
|
|
@@ -865,14 +2282,14 @@ Please specify: --chain <chain_name>`
|
|
|
865
2282
|
async handleBNBPayment(executeUrl, service, params, paymentDetails, options = {}) {
|
|
866
2283
|
const { to, amount, token, chainName, chain, spender } = paymentDetails;
|
|
867
2284
|
const tokenConfig = chain.tokens[token];
|
|
868
|
-
const provider = new
|
|
2285
|
+
const provider = new ethers3.JsonRpcProvider(chain.rpc);
|
|
869
2286
|
const allowance = await this.checkAllowance(tokenConfig.address, spender, provider);
|
|
870
2287
|
const amountWeiCheck = BigInt(Math.floor(amount * 10 ** tokenConfig.decimals));
|
|
871
2288
|
if (allowance < amountWeiCheck) {
|
|
872
2289
|
const nativeBalance = await provider.getBalance(this.wallet.address);
|
|
873
|
-
const minGasBalance =
|
|
2290
|
+
const minGasBalance = ethers3.parseEther("0.0005");
|
|
874
2291
|
if (nativeBalance < minGasBalance) {
|
|
875
|
-
const nativeBNB = parseFloat(
|
|
2292
|
+
const nativeBNB = parseFloat(ethers3.formatEther(nativeBalance)).toFixed(4);
|
|
876
2293
|
const isTestnet = chainName === "bnb_testnet";
|
|
877
2294
|
if (isTestnet) {
|
|
878
2295
|
throw new Error(
|
|
@@ -1045,7 +2462,7 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1045
2462
|
* Check ERC20 allowance for a spender
|
|
1046
2463
|
*/
|
|
1047
2464
|
async checkAllowance(tokenAddress, spender, provider) {
|
|
1048
|
-
const contract = new
|
|
2465
|
+
const contract = new ethers3.Contract(
|
|
1049
2466
|
tokenAddress,
|
|
1050
2467
|
["function allowance(address owner, address spender) view returns (uint256)"],
|
|
1051
2468
|
provider
|
|
@@ -1064,7 +2481,7 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1064
2481
|
async signEIP3009(to, amount, chain, token = "USDC", domainOverride) {
|
|
1065
2482
|
const tokenConfig = chain.tokens[token];
|
|
1066
2483
|
const value = BigInt(Math.floor(amount * 10 ** tokenConfig.decimals)).toString();
|
|
1067
|
-
const nonce =
|
|
2484
|
+
const nonce = ethers3.hexlify(ethers3.randomBytes(32));
|
|
1068
2485
|
const tokenName = domainOverride?.name || tokenConfig.eip712Name || (token === "USDC" ? "USD Coin" : "Tether USD");
|
|
1069
2486
|
const tokenVersion = domainOverride?.version || "2";
|
|
1070
2487
|
const envelope = buildEIP3009TypedData({
|
|
@@ -1110,26 +2527,26 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1110
2527
|
}
|
|
1111
2528
|
// --- Config & Wallet Management ---
|
|
1112
2529
|
loadConfig() {
|
|
1113
|
-
const configPath =
|
|
2530
|
+
const configPath = join4(this.configDir, "config.json");
|
|
1114
2531
|
if (existsSync2(configPath)) {
|
|
1115
|
-
const content =
|
|
2532
|
+
const content = readFileSync3(configPath, "utf-8");
|
|
1116
2533
|
return { ...DEFAULT_CONFIG, ...JSON.parse(content) };
|
|
1117
2534
|
}
|
|
1118
2535
|
return { ...DEFAULT_CONFIG };
|
|
1119
2536
|
}
|
|
1120
2537
|
saveConfig() {
|
|
1121
|
-
|
|
1122
|
-
const configPath =
|
|
1123
|
-
|
|
2538
|
+
mkdirSync3(this.configDir, { recursive: true });
|
|
2539
|
+
const configPath = join4(this.configDir, "config.json");
|
|
2540
|
+
writeFileSync3(configPath, JSON.stringify(this.config, null, 2));
|
|
1124
2541
|
}
|
|
1125
2542
|
/**
|
|
1126
2543
|
* Load spending data from disk
|
|
1127
2544
|
*/
|
|
1128
2545
|
loadSpending() {
|
|
1129
|
-
const spendingPath =
|
|
2546
|
+
const spendingPath = join4(this.configDir, "spending.json");
|
|
1130
2547
|
if (existsSync2(spendingPath)) {
|
|
1131
2548
|
try {
|
|
1132
|
-
const data = JSON.parse(
|
|
2549
|
+
const data = JSON.parse(readFileSync3(spendingPath, "utf-8"));
|
|
1133
2550
|
const today = (/* @__PURE__ */ new Date()).setHours(0, 0, 0, 0);
|
|
1134
2551
|
if (data.date && data.date === today) {
|
|
1135
2552
|
this.todaySpending = data.amount || 0;
|
|
@@ -1148,17 +2565,17 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1148
2565
|
* Save spending data to disk
|
|
1149
2566
|
*/
|
|
1150
2567
|
saveSpending() {
|
|
1151
|
-
|
|
1152
|
-
const spendingPath =
|
|
2568
|
+
mkdirSync3(this.configDir, { recursive: true });
|
|
2569
|
+
const spendingPath = join4(this.configDir, "spending.json");
|
|
1153
2570
|
const data = {
|
|
1154
2571
|
date: this.lastSpendingReset || (/* @__PURE__ */ new Date()).setHours(0, 0, 0, 0),
|
|
1155
2572
|
amount: this.todaySpending,
|
|
1156
2573
|
updatedAt: Date.now()
|
|
1157
2574
|
};
|
|
1158
|
-
|
|
2575
|
+
writeFileSync3(spendingPath, JSON.stringify(data, null, 2));
|
|
1159
2576
|
}
|
|
1160
2577
|
loadWallet() {
|
|
1161
|
-
const walletPath =
|
|
2578
|
+
const walletPath = join4(this.configDir, "wallet.json");
|
|
1162
2579
|
if (existsSync2(walletPath)) {
|
|
1163
2580
|
if (process.platform !== "win32") {
|
|
1164
2581
|
try {
|
|
@@ -1172,7 +2589,7 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1172
2589
|
} catch {
|
|
1173
2590
|
}
|
|
1174
2591
|
}
|
|
1175
|
-
const content =
|
|
2592
|
+
const content = readFileSync3(walletPath, "utf-8");
|
|
1176
2593
|
return JSON.parse(content);
|
|
1177
2594
|
}
|
|
1178
2595
|
return null;
|
|
@@ -1181,15 +2598,15 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1181
2598
|
* Initialize a new wallet (called by CLI)
|
|
1182
2599
|
*/
|
|
1183
2600
|
static init(configDir, options) {
|
|
1184
|
-
|
|
2601
|
+
mkdirSync3(configDir, { recursive: true });
|
|
1185
2602
|
const wallet = Wallet2.createRandom();
|
|
1186
2603
|
const walletData = {
|
|
1187
2604
|
address: wallet.address,
|
|
1188
2605
|
privateKey: wallet.privateKey,
|
|
1189
2606
|
createdAt: Date.now()
|
|
1190
2607
|
};
|
|
1191
|
-
const walletPath =
|
|
1192
|
-
|
|
2608
|
+
const walletPath = join4(configDir, "wallet.json");
|
|
2609
|
+
writeFileSync3(walletPath, JSON.stringify(walletData, null, 2), { mode: 384 });
|
|
1193
2610
|
const config = {
|
|
1194
2611
|
chain: options.chain,
|
|
1195
2612
|
limits: {
|
|
@@ -1197,8 +2614,8 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1197
2614
|
maxPerDay: options.maxPerDay
|
|
1198
2615
|
}
|
|
1199
2616
|
};
|
|
1200
|
-
const configPath =
|
|
1201
|
-
|
|
2617
|
+
const configPath = join4(configDir, "config.json");
|
|
2618
|
+
writeFileSync3(configPath, JSON.stringify(config, null, 2));
|
|
1202
2619
|
return { address: wallet.address, configDir };
|
|
1203
2620
|
}
|
|
1204
2621
|
/**
|
|
@@ -1214,17 +2631,17 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1214
2631
|
} catch {
|
|
1215
2632
|
throw new Error(`Unknown chain: ${this.config.chain}`);
|
|
1216
2633
|
}
|
|
1217
|
-
const provider = new
|
|
2634
|
+
const provider = new ethers3.JsonRpcProvider(chain.rpc);
|
|
1218
2635
|
const tokenAbi = ["function balanceOf(address) view returns (uint256)"];
|
|
1219
2636
|
const [nativeBalance, usdcBalance, usdtBalance] = await Promise.all([
|
|
1220
2637
|
provider.getBalance(this.wallet.address),
|
|
1221
|
-
new
|
|
1222
|
-
new
|
|
2638
|
+
new ethers3.Contract(chain.tokens.USDC.address, tokenAbi, provider).balanceOf(this.wallet.address),
|
|
2639
|
+
new ethers3.Contract(chain.tokens.USDT.address, tokenAbi, provider).balanceOf(this.wallet.address)
|
|
1223
2640
|
]);
|
|
1224
2641
|
return {
|
|
1225
|
-
usdc: parseFloat(
|
|
1226
|
-
usdt: parseFloat(
|
|
1227
|
-
native: parseFloat(
|
|
2642
|
+
usdc: parseFloat(ethers3.formatUnits(usdcBalance, chain.tokens.USDC.decimals)),
|
|
2643
|
+
usdt: parseFloat(ethers3.formatUnits(usdtBalance, chain.tokens.USDT.decimals)),
|
|
2644
|
+
native: parseFloat(ethers3.formatEther(nativeBalance))
|
|
1228
2645
|
};
|
|
1229
2646
|
}
|
|
1230
2647
|
/**
|
|
@@ -1247,38 +2664,38 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1247
2664
|
supportedChains.map(async (chainName) => {
|
|
1248
2665
|
try {
|
|
1249
2666
|
const chain = getChain(chainName);
|
|
1250
|
-
const provider = new
|
|
2667
|
+
const provider = new ethers3.JsonRpcProvider(chain.rpc);
|
|
1251
2668
|
if (chainName === "tempo_moderato") {
|
|
1252
2669
|
const [nativeBalance, pathUSD, alphaUSD, betaUSD, thetaUSD] = await Promise.all([
|
|
1253
2670
|
provider.getBalance(this.wallet.address),
|
|
1254
|
-
new
|
|
1255
|
-
new
|
|
1256
|
-
new
|
|
1257
|
-
new
|
|
2671
|
+
new ethers3.Contract(tempoTokens.pathUSD, tokenAbi, provider).balanceOf(this.wallet.address),
|
|
2672
|
+
new ethers3.Contract(tempoTokens.alphaUSD, tokenAbi, provider).balanceOf(this.wallet.address),
|
|
2673
|
+
new ethers3.Contract(tempoTokens.betaUSD, tokenAbi, provider).balanceOf(this.wallet.address),
|
|
2674
|
+
new ethers3.Contract(tempoTokens.thetaUSD, tokenAbi, provider).balanceOf(this.wallet.address)
|
|
1258
2675
|
]);
|
|
1259
2676
|
results[chainName] = {
|
|
1260
|
-
usdc: parseFloat(
|
|
2677
|
+
usdc: parseFloat(ethers3.formatUnits(pathUSD, 6)),
|
|
1261
2678
|
// pathUSD as default USDC
|
|
1262
|
-
usdt: parseFloat(
|
|
2679
|
+
usdt: parseFloat(ethers3.formatUnits(alphaUSD, 6)),
|
|
1263
2680
|
// alphaUSD as default USDT
|
|
1264
|
-
native: parseFloat(
|
|
2681
|
+
native: parseFloat(ethers3.formatEther(nativeBalance)),
|
|
1265
2682
|
tempo: {
|
|
1266
|
-
pathUSD: parseFloat(
|
|
1267
|
-
alphaUSD: parseFloat(
|
|
1268
|
-
betaUSD: parseFloat(
|
|
1269
|
-
thetaUSD: parseFloat(
|
|
2683
|
+
pathUSD: parseFloat(ethers3.formatUnits(pathUSD, 6)),
|
|
2684
|
+
alphaUSD: parseFloat(ethers3.formatUnits(alphaUSD, 6)),
|
|
2685
|
+
betaUSD: parseFloat(ethers3.formatUnits(betaUSD, 6)),
|
|
2686
|
+
thetaUSD: parseFloat(ethers3.formatUnits(thetaUSD, 6))
|
|
1270
2687
|
}
|
|
1271
2688
|
};
|
|
1272
2689
|
} else {
|
|
1273
2690
|
const [nativeBalance, usdcBalance, usdtBalance] = await Promise.all([
|
|
1274
2691
|
provider.getBalance(this.wallet.address),
|
|
1275
|
-
new
|
|
1276
|
-
new
|
|
2692
|
+
new ethers3.Contract(chain.tokens.USDC.address, tokenAbi, provider).balanceOf(this.wallet.address),
|
|
2693
|
+
new ethers3.Contract(chain.tokens.USDT.address, tokenAbi, provider).balanceOf(this.wallet.address)
|
|
1277
2694
|
]);
|
|
1278
2695
|
results[chainName] = {
|
|
1279
|
-
usdc: parseFloat(
|
|
1280
|
-
usdt: parseFloat(
|
|
1281
|
-
native: parseFloat(
|
|
2696
|
+
usdc: parseFloat(ethers3.formatUnits(usdcBalance, chain.tokens.USDC.decimals)),
|
|
2697
|
+
usdt: parseFloat(ethers3.formatUnits(usdtBalance, chain.tokens.USDT.decimals)),
|
|
2698
|
+
native: parseFloat(ethers3.formatEther(nativeBalance))
|
|
1282
2699
|
};
|
|
1283
2700
|
}
|
|
1284
2701
|
} catch (err2) {
|
|
@@ -1436,14 +2853,14 @@ function wrap(fn) {
|
|
|
1436
2853
|
}
|
|
1437
2854
|
function getPackageVersion() {
|
|
1438
2855
|
const candidates = [
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
2856
|
+
join5(__dirname, "../../package.json"),
|
|
2857
|
+
join5(__dirname, "../package.json"),
|
|
2858
|
+
join5(process.cwd(), "node_modules/moltspay/package.json")
|
|
1442
2859
|
];
|
|
1443
2860
|
for (const loc of candidates) {
|
|
1444
2861
|
try {
|
|
1445
2862
|
if (existsSync3(loc)) {
|
|
1446
|
-
const pkg = JSON.parse(
|
|
2863
|
+
const pkg = JSON.parse(readFileSync4(loc, "utf-8"));
|
|
1447
2864
|
if (pkg.name === "moltspay") return pkg.version;
|
|
1448
2865
|
}
|
|
1449
2866
|
} catch {
|