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