@haven_ai/sdk 0.1.27-alpha.0 → 0.1.29-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1871 -1689
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +104 -163
- package/dist/index.d.ts +104 -163
- package/dist/index.js +1871 -1690
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var async_hooks = require('async_hooks');
|
|
4
|
-
var schemes = require('x402/schemes');
|
|
5
3
|
var viem = require('viem');
|
|
6
|
-
var accounts = require('viem/accounts');
|
|
7
4
|
var ethers = require('ethers');
|
|
8
5
|
var crypto = require('crypto');
|
|
6
|
+
var async_hooks = require('async_hooks');
|
|
7
|
+
var schemes = require('x402/schemes');
|
|
8
|
+
var accounts = require('viem/accounts');
|
|
9
9
|
|
|
10
10
|
// src/client.ts
|
|
11
11
|
|
|
12
12
|
// src/types.ts
|
|
13
|
+
var DEFAULT_CONFIRMATION_TIMEOUT_MS = 9e4;
|
|
13
14
|
var AgentPaymentPhase = {
|
|
14
15
|
/** The agent must sign and submit the prepared payment before Haven can relay it. */
|
|
15
16
|
AgentSignatureRequired: "agent_signature_required",
|
|
@@ -394,24 +395,6 @@ function verifySignature(hash, signature, expectedAddress) {
|
|
|
394
395
|
return false;
|
|
395
396
|
}
|
|
396
397
|
}
|
|
397
|
-
var RECEIPT_VERSION = "haven-receipt-1";
|
|
398
|
-
function defaultRecover(hash, signature) {
|
|
399
|
-
return ethers.ethers.recoverAddress(hash, signature);
|
|
400
|
-
}
|
|
401
|
-
function verifyPaymentReceipt(receipt, recover = defaultRecover) {
|
|
402
|
-
const { delegate, signHash: signHash2, signature } = receipt.authorization;
|
|
403
|
-
if (!signature) return { verified: false, reason: "missing_signature" };
|
|
404
|
-
let recovered;
|
|
405
|
-
try {
|
|
406
|
-
recovered = recover(signHash2, signature);
|
|
407
|
-
} catch {
|
|
408
|
-
return { verified: false, reason: "bad_signature" };
|
|
409
|
-
}
|
|
410
|
-
if (recovered.toLowerCase() !== delegate.toLowerCase()) {
|
|
411
|
-
return { verified: false, reason: "signer_mismatch", recoveredSigner: recovered };
|
|
412
|
-
}
|
|
413
|
-
return { verified: true, recoveredSigner: recovered };
|
|
414
|
-
}
|
|
415
398
|
|
|
416
399
|
// src/base64.ts
|
|
417
400
|
function normalizeBase64(value) {
|
|
@@ -779,7 +762,7 @@ function x402AuthorizationAmount(option) {
|
|
|
779
762
|
return amount;
|
|
780
763
|
}
|
|
781
764
|
function buildX402ExpectedMessage(context) {
|
|
782
|
-
const version = context.typedDataHash ? 2 : 1;
|
|
765
|
+
const version = context.payerDelegate ? 3 : context.typedDataHash ? 2 : 1;
|
|
783
766
|
const payload = {
|
|
784
767
|
version,
|
|
785
768
|
kind: "haven.x402.expected",
|
|
@@ -797,6 +780,12 @@ function buildX402ExpectedMessage(context) {
|
|
|
797
780
|
if (context.typedDataHash) {
|
|
798
781
|
payload.typedDataHash = context.typedDataHash.toLowerCase();
|
|
799
782
|
}
|
|
783
|
+
if (context.payerDelegate) {
|
|
784
|
+
payload.payerDelegate = context.payerDelegate.toLowerCase();
|
|
785
|
+
if (context.payerAgentId) {
|
|
786
|
+
payload.payerAgentId = context.payerAgentId;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
800
789
|
return `Haven x402 expected context v${version}
|
|
801
790
|
${stableStringify2(payload)}`;
|
|
802
791
|
}
|
|
@@ -958,61 +947,173 @@ function stableStringify2(value) {
|
|
|
958
947
|
const object = value;
|
|
959
948
|
return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableStringify2(object[key])}`).join(",")}}`;
|
|
960
949
|
}
|
|
961
|
-
function createJsonRpcProvider(url) {
|
|
962
|
-
return new ethers.ethers.JsonRpcProvider(url);
|
|
963
|
-
}
|
|
964
|
-
function createWallet(privateKey, provider) {
|
|
965
|
-
return new ethers.ethers.Wallet(privateKey, provider);
|
|
966
|
-
}
|
|
967
|
-
function createErc20Contract(address, abi, runner) {
|
|
968
|
-
return new ethers.ethers.Contract(address, abi, runner);
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
// src/client.ts
|
|
972
950
|
var DEFAULT_BASE_URL = "http://localhost:3001";
|
|
973
|
-
var
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
951
|
+
var DEFAULT_REQUEST_TIMEOUT = 3e4;
|
|
952
|
+
var HavenApiTransport = class {
|
|
953
|
+
apiKey;
|
|
954
|
+
baseUrl;
|
|
955
|
+
requestTimeout;
|
|
956
|
+
defaultHeaders;
|
|
957
|
+
requestContext = new async_hooks.AsyncLocalStorage();
|
|
958
|
+
constructor(config) {
|
|
959
|
+
this.apiKey = config.apiKey;
|
|
960
|
+
this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
961
|
+
this.requestTimeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
|
|
962
|
+
this.defaultHeaders = { ...config.defaultHeaders ?? {} };
|
|
963
|
+
}
|
|
964
|
+
/** Run `fn` with extra headers scoped to its asynchronous Haven API work. */
|
|
965
|
+
withRequestContext(headers, fn) {
|
|
966
|
+
return this.requestContext.run({ headers: { ...headers } }, fn);
|
|
967
|
+
}
|
|
968
|
+
async post(path, body) {
|
|
969
|
+
return this.request("POST", path, body);
|
|
970
|
+
}
|
|
971
|
+
async get(path) {
|
|
972
|
+
return this.request("GET", path);
|
|
973
|
+
}
|
|
974
|
+
async request(method, path, body) {
|
|
975
|
+
const url = `${this.baseUrl}${path}`;
|
|
976
|
+
const controller = new AbortController();
|
|
977
|
+
const timeout = setTimeout(() => controller.abort(), this.requestTimeout);
|
|
978
|
+
try {
|
|
979
|
+
const contextHeaders = this.requestContext.getStore()?.headers ?? {};
|
|
980
|
+
const res = await fetch(url, {
|
|
981
|
+
method,
|
|
982
|
+
headers: {
|
|
983
|
+
"Content-Type": "application/json",
|
|
984
|
+
"Authorization": `Bearer ${this.apiKey}`,
|
|
985
|
+
...this.defaultHeaders,
|
|
986
|
+
...contextHeaders
|
|
987
|
+
},
|
|
988
|
+
body: body ? JSON.stringify(body) : void 0,
|
|
989
|
+
signal: controller.signal
|
|
990
|
+
});
|
|
991
|
+
const data = await res.json();
|
|
992
|
+
if (!res.ok) {
|
|
993
|
+
const record = data;
|
|
994
|
+
const errorText = typeof record.error === "string" ? record.error : void 0;
|
|
995
|
+
const rawDetails = record.details ?? record.detail;
|
|
996
|
+
const detailsText = typeof rawDetails === "string" ? rawDetails : rawDetails != null ? JSON.stringify(rawDetails) : void 0;
|
|
997
|
+
const message = errorText && detailsText ? `${errorText}: ${detailsText}` : errorText ?? detailsText ?? "API request failed";
|
|
998
|
+
throw new HavenApiError(message, res.status, data);
|
|
999
|
+
}
|
|
1000
|
+
return data;
|
|
1001
|
+
} catch (err) {
|
|
1002
|
+
if (err instanceof HavenApiError) throw err;
|
|
1003
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
1004
|
+
throw new HavenApiError(`Request to ${path} timed out`, 408);
|
|
1005
|
+
}
|
|
1006
|
+
throw new HavenApiError(
|
|
1007
|
+
`Request to ${path} failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
1008
|
+
0
|
|
1009
|
+
);
|
|
1010
|
+
} finally {
|
|
1011
|
+
clearTimeout(timeout);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
980
1014
|
};
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
1015
|
+
|
|
1016
|
+
// src/payment-mappers.ts
|
|
1017
|
+
function mapPaymentResult(raw, buildExplorerUrl2) {
|
|
1018
|
+
return {
|
|
1019
|
+
paymentId: raw.payment_id,
|
|
1020
|
+
status: raw.status,
|
|
1021
|
+
token: raw.token,
|
|
1022
|
+
amount: raw.amount,
|
|
1023
|
+
to: raw.to,
|
|
1024
|
+
txHash: raw.tx_hash,
|
|
1025
|
+
errorMessage: raw.error_message,
|
|
1026
|
+
explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl2(raw.chain_id, raw.tx_hash) : null),
|
|
1027
|
+
fee: raw.fee ? {
|
|
1028
|
+
amount: raw.fee.amount,
|
|
1029
|
+
token: raw.fee.token,
|
|
1030
|
+
basisPoints: raw.fee.basis_points,
|
|
1031
|
+
applied: raw.fee.applied
|
|
1032
|
+
} : null,
|
|
1033
|
+
createdAt: raw.created_at,
|
|
1034
|
+
signedAt: raw.signed_at,
|
|
1035
|
+
submittedAt: raw.submitted_at,
|
|
1036
|
+
confirmedAt: raw.confirmed_at,
|
|
1037
|
+
expiresAt: raw.expires_at
|
|
1038
|
+
};
|
|
987
1039
|
}
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
1040
|
+
function mapPaymentStatusResult(raw) {
|
|
1041
|
+
return {
|
|
1042
|
+
paymentId: raw.payment_id,
|
|
1043
|
+
kind: raw.kind,
|
|
1044
|
+
rail: raw.rail,
|
|
1045
|
+
status: raw.status,
|
|
1046
|
+
phase: raw.phase,
|
|
1047
|
+
nextAction: raw.next_action,
|
|
1048
|
+
amount: raw.amount,
|
|
1049
|
+
token: raw.token,
|
|
1050
|
+
resourceUrl: raw.resource_url,
|
|
1051
|
+
merchantAddress: raw.merchant_address,
|
|
1052
|
+
payerAddress: raw.payer_address ?? null,
|
|
1053
|
+
txHash: raw.tx_hash,
|
|
1054
|
+
expiresAt: raw.expires_at,
|
|
1055
|
+
chainId: raw.chain_id,
|
|
1056
|
+
message: raw.message,
|
|
1057
|
+
fee: raw.fee ? {
|
|
1058
|
+
amount: raw.fee.amount,
|
|
1059
|
+
token: raw.fee.token,
|
|
1060
|
+
basisPoints: raw.fee.basis_points,
|
|
1061
|
+
applied: raw.fee.applied
|
|
1062
|
+
} : null,
|
|
1063
|
+
amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? null,
|
|
1064
|
+
asset: raw.asset ?? raw.x402?.asset ?? null,
|
|
1065
|
+
network: raw.network ?? raw.x402?.network ?? null,
|
|
1066
|
+
description: raw.description ?? raw.x402?.description ?? null,
|
|
1067
|
+
idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? null,
|
|
1068
|
+
x402: raw.x402 ? {
|
|
1069
|
+
amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,
|
|
1070
|
+
asset: raw.x402.asset ?? raw.asset ?? null,
|
|
1071
|
+
network: raw.x402.network ?? raw.network ?? null,
|
|
1072
|
+
resourceUrl: raw.x402.resource_url ?? raw.resource_url,
|
|
1073
|
+
merchantAddress: raw.x402.merchant_address ?? raw.merchant_address,
|
|
1074
|
+
description: raw.x402.description ?? raw.description ?? null,
|
|
1075
|
+
idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null
|
|
1076
|
+
} : void 0
|
|
1077
|
+
};
|
|
999
1078
|
}
|
|
1000
|
-
function
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1079
|
+
function mapPaymentReceipt(raw) {
|
|
1080
|
+
const receipt = {
|
|
1081
|
+
id: raw.id,
|
|
1082
|
+
paymentId: raw.payment_id,
|
|
1083
|
+
rail: raw.rail,
|
|
1084
|
+
proofStatus: raw.proof_status,
|
|
1085
|
+
txHash: raw.tx_hash,
|
|
1086
|
+
chainId: raw.chain_id,
|
|
1087
|
+
resourceUrl: raw.resource_url,
|
|
1088
|
+
merchantAddress: raw.merchant_address,
|
|
1089
|
+
payerAddress: raw.payer_address,
|
|
1090
|
+
settlementAddress: raw.settlement_address,
|
|
1091
|
+
tokenSymbol: raw.token_symbol,
|
|
1092
|
+
tokenAddress: raw.token_address,
|
|
1093
|
+
amountRaw: raw.amount_raw,
|
|
1094
|
+
amount: raw.amount_human,
|
|
1095
|
+
challengeId: raw.challenge_id,
|
|
1096
|
+
idempotencyKey: raw.idempotency_key,
|
|
1097
|
+
challengePayload: raw.challenge_payload,
|
|
1098
|
+
selectedPayment: raw.selected_payment,
|
|
1099
|
+
paymentProofHeaderName: raw.payment_proof_header_name,
|
|
1100
|
+
protocolReceiptHeaderName: raw.protocol_receipt_header_name,
|
|
1101
|
+
protocolReceiptPayload: raw.protocol_receipt_payload,
|
|
1102
|
+
merchantStatus: raw.merchant_status,
|
|
1103
|
+
confirmedAt: raw.confirmed_at,
|
|
1104
|
+
createdAt: raw.created_at,
|
|
1105
|
+
updatedAt: raw.updated_at
|
|
1106
|
+
};
|
|
1107
|
+
if ("payment_intent_id" in raw) {
|
|
1108
|
+
receipt.paymentIntentId = raw.payment_intent_id ?? null;
|
|
1005
1109
|
}
|
|
1110
|
+
if ("approval_request_id" in raw) {
|
|
1111
|
+
receipt.approvalRequestId = raw.approval_request_id ?? null;
|
|
1112
|
+
}
|
|
1113
|
+
return receipt;
|
|
1006
1114
|
}
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
const hasSpendable = allowances.some((a) => safeBigInt(a.remainingAtomic) > 0n);
|
|
1010
|
-
return hasSpendable ? "ready" : "needs_approval";
|
|
1011
|
-
}
|
|
1012
|
-
var MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
1013
|
-
var MCP_ACCEPT = "application/json, text/event-stream";
|
|
1014
|
-
var MCP_CLIENT_INFO = { name: "haven-sdk", version: "1" };
|
|
1015
|
-
var MERCHANT_BODY_SNIPPET_LIMIT = 1e3;
|
|
1115
|
+
|
|
1116
|
+
// src/payment-state.ts
|
|
1016
1117
|
var PAYMENT_STATE_STATUS_CODES = {
|
|
1017
1118
|
pending: 202,
|
|
1018
1119
|
pending_approval: 202,
|
|
@@ -1025,15 +1126,8 @@ var PAYMENT_STATE_STATUS_CODES = {
|
|
|
1025
1126
|
failed: 502,
|
|
1026
1127
|
rejected: 409
|
|
1027
1128
|
};
|
|
1028
|
-
function
|
|
1029
|
-
|
|
1030
|
-
if (network === "base-sepolia") return 84532;
|
|
1031
|
-
if (!network?.startsWith("eip155:")) return void 0;
|
|
1032
|
-
const chainId = Number(network.slice("eip155:".length));
|
|
1033
|
-
return Number.isFinite(chainId) ? chainId : void 0;
|
|
1034
|
-
}
|
|
1035
|
-
function chainIdOrNull(network) {
|
|
1036
|
-
return chainIdFromNetwork(network) ?? null;
|
|
1129
|
+
function paymentStateStatusCode(status, fallback = 502) {
|
|
1130
|
+
return PAYMENT_STATE_STATUS_CODES[status] ?? fallback;
|
|
1037
1131
|
}
|
|
1038
1132
|
function phaseForStatus(status) {
|
|
1039
1133
|
if (status === "pending_signature") return AgentPaymentPhase.AgentSignatureRequired;
|
|
@@ -1076,69 +1170,1495 @@ function messageForState(label, status, paymentId, nextAction) {
|
|
|
1076
1170
|
}
|
|
1077
1171
|
return `${label} is ${status}; next_action=${nextAction} (payment_id: ${paymentId}).`;
|
|
1078
1172
|
}
|
|
1079
|
-
function
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
const
|
|
1085
|
-
const
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1173
|
+
function paymentStateFromRaw(label, raw) {
|
|
1174
|
+
if (!raw.payment_id || !raw.status) return null;
|
|
1175
|
+
const phase = raw.phase ?? phaseForStatus(raw.status);
|
|
1176
|
+
const nextAction = raw.next_action ?? nextActionForStatus(raw.status);
|
|
1177
|
+
if (!phase || !nextAction) return null;
|
|
1178
|
+
const amount = raw.amount ?? raw.requested ?? "";
|
|
1179
|
+
const token = raw.token ?? "";
|
|
1180
|
+
const message = raw.message ?? raw.error ?? messageForState(label, raw.status, raw.payment_id, nextAction);
|
|
1181
|
+
return {
|
|
1182
|
+
paymentId: raw.payment_id,
|
|
1183
|
+
kind: raw.kind === "payment_intent" ? "payment_intent" : "approval_request",
|
|
1184
|
+
rail: raw.rail ?? "direct",
|
|
1185
|
+
status: raw.status === "pending" ? "pending_approval" : raw.status,
|
|
1186
|
+
phase,
|
|
1187
|
+
nextAction,
|
|
1188
|
+
amount,
|
|
1189
|
+
token,
|
|
1190
|
+
resourceUrl: raw.resource_url ?? null,
|
|
1191
|
+
merchantAddress: raw.merchant_address ?? raw.merchant_to ?? null,
|
|
1192
|
+
txHash: raw.tx_hash ?? null,
|
|
1193
|
+
expiresAt: raw.expires_at ?? "",
|
|
1194
|
+
chainId: raw.chain_id ?? 0,
|
|
1195
|
+
message,
|
|
1196
|
+
amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? raw.mpp?.amount_atomic ?? null,
|
|
1197
|
+
asset: raw.asset ?? raw.x402?.asset ?? raw.mpp?.asset ?? null,
|
|
1198
|
+
network: raw.network ?? raw.x402?.network ?? raw.mpp?.network ?? null,
|
|
1199
|
+
description: raw.description ?? raw.x402?.description ?? raw.mpp?.description ?? null,
|
|
1200
|
+
idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? raw.mpp?.idempotency_key ?? null,
|
|
1201
|
+
x402: raw.x402 ? {
|
|
1202
|
+
amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,
|
|
1203
|
+
asset: raw.x402.asset ?? raw.asset ?? null,
|
|
1204
|
+
network: raw.x402.network ?? raw.network ?? null,
|
|
1205
|
+
resourceUrl: raw.x402.resource_url ?? raw.resource_url ?? null,
|
|
1206
|
+
merchantAddress: raw.x402.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,
|
|
1207
|
+
description: raw.x402.description ?? raw.description ?? null,
|
|
1208
|
+
idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null
|
|
1209
|
+
} : void 0,
|
|
1210
|
+
mpp: raw.mpp ? {
|
|
1211
|
+
amountAtomic: raw.mpp.amount_atomic ?? raw.amount_atomic ?? null,
|
|
1212
|
+
asset: raw.mpp.asset ?? raw.asset ?? null,
|
|
1213
|
+
network: raw.mpp.network ?? raw.network ?? null,
|
|
1214
|
+
resourceUrl: raw.mpp.resource_url ?? raw.resource_url ?? null,
|
|
1215
|
+
merchantAddress: raw.mpp.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,
|
|
1216
|
+
description: raw.mpp.description ?? raw.description ?? null,
|
|
1217
|
+
idempotencyKey: raw.mpp.idempotency_key ?? raw.idempotency_key ?? null,
|
|
1218
|
+
challengeId: raw.mpp.challenge_id ?? raw.challenge_id ?? null
|
|
1219
|
+
} : void 0
|
|
1220
|
+
};
|
|
1100
1221
|
}
|
|
1101
|
-
function
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1222
|
+
function throwPaymentStateError(label, raw) {
|
|
1223
|
+
const statusCode = paymentStateStatusCode(raw.status);
|
|
1224
|
+
const state = paymentStateFromRaw(label, raw);
|
|
1225
|
+
if (state) {
|
|
1226
|
+
throw new HavenPaymentStateError(state.message, statusCode, state, raw);
|
|
1106
1227
|
}
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1228
|
+
if (raw.status === "pending_approval") {
|
|
1229
|
+
throw new HavenApiError(
|
|
1230
|
+
`${label} exceeds the on-chain allowance and was queued for owner approval (payment_id: ${raw.payment_id}).`,
|
|
1231
|
+
statusCode,
|
|
1232
|
+
raw
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
if (raw.status === "expired") {
|
|
1236
|
+
throw new HavenApiError(
|
|
1237
|
+
`${label} expired before it could be completed (payment_id: ${raw.payment_id}).`,
|
|
1238
|
+
statusCode,
|
|
1239
|
+
raw
|
|
1240
|
+
);
|
|
1114
1241
|
}
|
|
1242
|
+
const paymentId = raw.payment_id ? ` (payment_id: ${raw.payment_id})` : "";
|
|
1243
|
+
const message = raw.error ?? `${label} ${raw.status}${paymentId}`;
|
|
1244
|
+
throw new HavenApiError(message, statusCode, raw);
|
|
1115
1245
|
}
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1246
|
+
|
|
1247
|
+
// src/mcp-merchant-transport.ts
|
|
1248
|
+
var DEFAULT_MERCHANT_TIMEOUT = 3e5;
|
|
1249
|
+
var MCP_NOTIFICATION_TIMEOUT = 1e4;
|
|
1250
|
+
var MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
1251
|
+
var MCP_ACCEPT = "application/json, text/event-stream";
|
|
1252
|
+
var MCP_CLIENT_INFO = { name: "haven-sdk", version: "1" };
|
|
1253
|
+
var McpMerchantTransport = class {
|
|
1254
|
+
merchantTimeout;
|
|
1255
|
+
fetchImpl;
|
|
1256
|
+
requestId = 0;
|
|
1257
|
+
constructor(options = {}) {
|
|
1258
|
+
this.merchantTimeout = options.merchantTimeout ?? DEFAULT_MERCHANT_TIMEOUT;
|
|
1259
|
+
this.fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
1260
|
+
}
|
|
1261
|
+
/** Fetch a merchant with a settlement-sized timeout and caller cancellation. */
|
|
1262
|
+
async fetch(url, init = {}, timeoutMs = this.merchantTimeout) {
|
|
1263
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
1264
|
+
const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal;
|
|
1121
1265
|
try {
|
|
1122
|
-
|
|
1266
|
+
return await this.fetchImpl(url, { ...init, signal });
|
|
1267
|
+
} catch (err) {
|
|
1268
|
+
if (timeoutSignal.aborted) {
|
|
1269
|
+
throw new MerchantTimeoutError(`Merchant request timed out after ${timeoutMs}ms: ${url}`);
|
|
1270
|
+
}
|
|
1271
|
+
throw err;
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
/**
|
|
1275
|
+
* Establish an MCP Streamable-HTTP session. Any handshake failure degrades
|
|
1276
|
+
* to `undefined`, allowing the caller to fall back to plain x402.
|
|
1277
|
+
*/
|
|
1278
|
+
async initialize(url, init, wallet) {
|
|
1279
|
+
try {
|
|
1280
|
+
const headers = new Headers(init?.headers);
|
|
1281
|
+
headers.set("Content-Type", "application/json");
|
|
1282
|
+
headers.set("Accept", MCP_ACCEPT);
|
|
1283
|
+
if (wallet && !headers.has("x402-wallet")) headers.set("x402-wallet", wallet);
|
|
1284
|
+
const response = await this.fetch(url, {
|
|
1285
|
+
method: "POST",
|
|
1286
|
+
headers,
|
|
1287
|
+
body: JSON.stringify({
|
|
1288
|
+
jsonrpc: "2.0",
|
|
1289
|
+
id: ++this.requestId,
|
|
1290
|
+
method: "initialize",
|
|
1291
|
+
params: {
|
|
1292
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
1293
|
+
capabilities: {},
|
|
1294
|
+
clientInfo: MCP_CLIENT_INFO
|
|
1295
|
+
}
|
|
1296
|
+
})
|
|
1297
|
+
});
|
|
1298
|
+
if (!response.ok) return void 0;
|
|
1299
|
+
const sessionId = response.headers.get("mcp-session-id");
|
|
1300
|
+
if (!sessionId) return void 0;
|
|
1301
|
+
const message = await this.readMessage(response);
|
|
1302
|
+
if (message && "error" in message) return void 0;
|
|
1303
|
+
await this.notifyInitialized(url, init, sessionId, wallet);
|
|
1304
|
+
return sessionId;
|
|
1123
1305
|
} catch {
|
|
1306
|
+
return void 0;
|
|
1124
1307
|
}
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1308
|
+
}
|
|
1309
|
+
/** Add the MCP session and response-content negotiation headers. */
|
|
1310
|
+
withSessionHeaders(init, sessionId) {
|
|
1311
|
+
const headers = new Headers(init?.headers);
|
|
1312
|
+
headers.set("mcp-session-id", sessionId);
|
|
1313
|
+
headers.set("Accept", MCP_ACCEPT);
|
|
1314
|
+
return { ...init, headers };
|
|
1315
|
+
}
|
|
1316
|
+
/** Read one JSON-RPC message from a JSON or SSE response without consuming it. */
|
|
1317
|
+
async readMessage(response) {
|
|
1318
|
+
let text;
|
|
1319
|
+
try {
|
|
1320
|
+
text = await response.clone().text();
|
|
1321
|
+
} catch {
|
|
1322
|
+
return void 0;
|
|
1323
|
+
}
|
|
1324
|
+
if ((response.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
1325
|
+
return selectJsonRpcResult(parseSseJsonRpcMessages(text));
|
|
1131
1326
|
}
|
|
1132
|
-
|
|
1133
|
-
|
|
1327
|
+
try {
|
|
1328
|
+
return JSON.parse(text);
|
|
1329
|
+
} catch {
|
|
1330
|
+
return void 0;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* Collapse an MCP SSE response to the JSON-RPC result. Non-SSE and
|
|
1335
|
+
* unparseable responses pass through with their original body untouched.
|
|
1336
|
+
*/
|
|
1337
|
+
async surfaceResult(response) {
|
|
1338
|
+
if (!(response.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
1339
|
+
return response;
|
|
1340
|
+
}
|
|
1341
|
+
let text;
|
|
1342
|
+
try {
|
|
1343
|
+
text = await response.clone().text();
|
|
1344
|
+
} catch {
|
|
1345
|
+
return response;
|
|
1346
|
+
}
|
|
1347
|
+
const message = selectJsonRpcResult(parseSseJsonRpcMessages(text));
|
|
1348
|
+
if (!message) return response;
|
|
1349
|
+
const body = "result" in message ? message.result : message;
|
|
1350
|
+
const headers = new Headers(response.headers);
|
|
1351
|
+
headers.set("content-type", "application/json");
|
|
1352
|
+
headers.delete("content-length");
|
|
1353
|
+
headers.delete("mcp-session-id");
|
|
1354
|
+
return new Response(JSON.stringify(body), {
|
|
1355
|
+
status: response.status,
|
|
1356
|
+
statusText: response.statusText,
|
|
1357
|
+
headers
|
|
1358
|
+
});
|
|
1359
|
+
}
|
|
1360
|
+
/** Detect MCP transport from the URL or Coinbase Bazaar extension. */
|
|
1361
|
+
async detect(url, paymentRequired, response) {
|
|
1362
|
+
if (isMcpUrl(url)) return { handshakeRequired: true, source: "path" };
|
|
1363
|
+
if (paymentRequired.extensions?.bazaar != null) {
|
|
1364
|
+
return { handshakeRequired: true, source: "bazaar" };
|
|
1365
|
+
}
|
|
1366
|
+
if (await responseHasBazaarExtension(response)) {
|
|
1367
|
+
return { handshakeRequired: true, source: "bazaar" };
|
|
1368
|
+
}
|
|
1369
|
+
return void 0;
|
|
1370
|
+
}
|
|
1371
|
+
/** Identify the conventional Streamable-HTTP MCP path without probing it. */
|
|
1372
|
+
isMcpUrl(url) {
|
|
1373
|
+
return isMcpUrl(url);
|
|
1374
|
+
}
|
|
1375
|
+
/** Detect Bazaar metadata without consuming the merchant response. */
|
|
1376
|
+
hasBazaarExtension(response) {
|
|
1377
|
+
return responseHasBazaarExtension(response);
|
|
1378
|
+
}
|
|
1379
|
+
/** Deliver an already-signed x402 header without changing the caller body. */
|
|
1380
|
+
async deliverPayment(url, init, paymentHeader) {
|
|
1381
|
+
const headers = new Headers(init?.headers);
|
|
1382
|
+
headers.set("X-PAYMENT", paymentHeader);
|
|
1383
|
+
return this.fetch(url, { ...init, headers });
|
|
1384
|
+
}
|
|
1385
|
+
async notifyInitialized(url, init, sessionId, wallet) {
|
|
1386
|
+
try {
|
|
1387
|
+
const headers = new Headers(init?.headers);
|
|
1388
|
+
headers.set("Content-Type", "application/json");
|
|
1389
|
+
headers.set("Accept", MCP_ACCEPT);
|
|
1390
|
+
headers.set("mcp-session-id", sessionId);
|
|
1391
|
+
if (wallet && !headers.has("x402-wallet")) headers.set("x402-wallet", wallet);
|
|
1392
|
+
await this.fetch(
|
|
1393
|
+
url,
|
|
1394
|
+
{
|
|
1395
|
+
method: "POST",
|
|
1396
|
+
headers,
|
|
1397
|
+
body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
|
|
1398
|
+
},
|
|
1399
|
+
MCP_NOTIFICATION_TIMEOUT
|
|
1400
|
+
);
|
|
1401
|
+
} catch {
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
};
|
|
1405
|
+
async function captureMerchantResponse(response) {
|
|
1406
|
+
const merchant_body = await response.text().catch(() => "");
|
|
1407
|
+
return {
|
|
1408
|
+
merchant_status: response.status,
|
|
1409
|
+
merchant_status_text: response.statusText,
|
|
1410
|
+
merchant_headers: Object.fromEntries(response.headers.entries()),
|
|
1411
|
+
merchant_body
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
function isMcpUrl(url) {
|
|
1415
|
+
try {
|
|
1416
|
+
return new URL(url).pathname.replace(/\/+$/, "").endsWith("/mcp");
|
|
1417
|
+
} catch {
|
|
1418
|
+
return /\/mcp(?:[/?#]|$)/.test(url);
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
async function responseHasBazaarExtension(response) {
|
|
1422
|
+
try {
|
|
1423
|
+
const body = await response.clone().json();
|
|
1424
|
+
return body?.extensions?.bazaar != null;
|
|
1425
|
+
} catch {
|
|
1426
|
+
return false;
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
function parseSseJsonRpcMessages(text) {
|
|
1430
|
+
const messages = [];
|
|
1431
|
+
let dataLines = [];
|
|
1432
|
+
const flush = () => {
|
|
1433
|
+
if (dataLines.length === 0) return;
|
|
1434
|
+
try {
|
|
1435
|
+
messages.push(JSON.parse(dataLines.join("\n")));
|
|
1436
|
+
} catch {
|
|
1437
|
+
}
|
|
1438
|
+
dataLines = [];
|
|
1439
|
+
};
|
|
1440
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1441
|
+
if (line === "") {
|
|
1442
|
+
flush();
|
|
1443
|
+
continue;
|
|
1444
|
+
}
|
|
1445
|
+
if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
1446
|
+
}
|
|
1447
|
+
flush();
|
|
1448
|
+
return messages;
|
|
1449
|
+
}
|
|
1450
|
+
function selectJsonRpcResult(messages) {
|
|
1451
|
+
return messages.find((message) => "result" in message || "error" in message) ?? messages.at(-1);
|
|
1452
|
+
}
|
|
1453
|
+
var RECEIPT_VERSION = "haven-receipt-1";
|
|
1454
|
+
function defaultRecover(hash, signature) {
|
|
1455
|
+
return ethers.ethers.recoverAddress(hash, signature);
|
|
1456
|
+
}
|
|
1457
|
+
function verifyPaymentReceipt(receipt, recover = defaultRecover) {
|
|
1458
|
+
const { delegate, signHash: signHash2, signature } = receipt.authorization;
|
|
1459
|
+
if (!signature) return { verified: false, reason: "missing_signature" };
|
|
1460
|
+
let recovered;
|
|
1461
|
+
try {
|
|
1462
|
+
recovered = recover(signHash2, signature);
|
|
1463
|
+
} catch {
|
|
1464
|
+
return { verified: false, reason: "bad_signature" };
|
|
1465
|
+
}
|
|
1466
|
+
if (recovered.toLowerCase() !== delegate.toLowerCase()) {
|
|
1467
|
+
return { verified: false, reason: "signer_mismatch", recoveredSigner: recovered };
|
|
1468
|
+
}
|
|
1469
|
+
return { verified: true, recoveredSigner: recovered };
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
// src/account-reads.ts
|
|
1473
|
+
function safeBigInt(value) {
|
|
1474
|
+
try {
|
|
1475
|
+
return BigInt(value);
|
|
1476
|
+
} catch {
|
|
1477
|
+
return 0n;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
function formatAtomicAmount(atomic, decimals) {
|
|
1481
|
+
if (atomic < 0n) return "0.0";
|
|
1482
|
+
const value = atomic.toString().padStart(decimals + 1, "0");
|
|
1483
|
+
const whole = value.slice(0, value.length - decimals) || "0";
|
|
1484
|
+
const fraction = value.slice(value.length - decimals).replace(/0+$/, "") || "0";
|
|
1485
|
+
return `${whole}.${fraction}`;
|
|
1486
|
+
}
|
|
1487
|
+
function deriveReadiness(status, allowances) {
|
|
1488
|
+
if (status !== "active") return "revoked";
|
|
1489
|
+
return allowances.some((allowance) => safeBigInt(allowance.remainingAtomic) > 0n) ? "ready" : "needs_approval";
|
|
1490
|
+
}
|
|
1491
|
+
var AccountReads = class {
|
|
1492
|
+
transport;
|
|
1493
|
+
getPaymentStatus;
|
|
1494
|
+
agentInFlight = null;
|
|
1495
|
+
constructor(options) {
|
|
1496
|
+
this.transport = options.transport;
|
|
1497
|
+
this.getPaymentStatus = options.getPaymentStatus;
|
|
1498
|
+
}
|
|
1499
|
+
async getAgent() {
|
|
1500
|
+
if (this.agentInFlight) return this.agentInFlight;
|
|
1501
|
+
const request = this.fetchAgent();
|
|
1502
|
+
this.agentInFlight = request;
|
|
1503
|
+
request.finally(() => {
|
|
1504
|
+
this.agentInFlight = null;
|
|
1505
|
+
}).catch(() => {
|
|
1506
|
+
});
|
|
1507
|
+
return request;
|
|
1508
|
+
}
|
|
1509
|
+
async getAgentSummary() {
|
|
1510
|
+
const [agent, allowanceSummary] = await Promise.all([this.getAgent(), this.getAllowances()]);
|
|
1511
|
+
const allowances = allowanceSummary.allowances.map((allowance) => {
|
|
1512
|
+
const token = resolveTokenFromAddress(allowance.tokenAddress);
|
|
1513
|
+
const remainingDisplay = token ? `${formatAtomicAmount(safeBigInt(allowance.onchain.remaining), token.decimals)} ${allowance.tokenSymbol}` : `${allowance.onchain.remaining} ${allowance.tokenSymbol} (atomic; unknown decimals)`;
|
|
1514
|
+
return {
|
|
1515
|
+
tokenSymbol: allowance.tokenSymbol,
|
|
1516
|
+
remainingAtomic: allowance.onchain.remaining,
|
|
1517
|
+
remainingDisplay,
|
|
1518
|
+
configuredAmount: allowance.configuredAmount,
|
|
1519
|
+
resetPeriodMin: allowance.resetPeriodMin,
|
|
1520
|
+
isResetPending: allowance.onchain.isResetPending
|
|
1521
|
+
};
|
|
1522
|
+
});
|
|
1523
|
+
const readiness = deriveReadiness(agent.status, allowances);
|
|
1524
|
+
return { ...agent, readiness, spend_authority_readiness: readiness, allowances };
|
|
1525
|
+
}
|
|
1526
|
+
async getAllowances() {
|
|
1527
|
+
const raw = await this.transport.get("/machine-payments/allowances");
|
|
1528
|
+
return {
|
|
1529
|
+
agentId: raw.agent_id,
|
|
1530
|
+
safeAddress: raw.safe_address,
|
|
1531
|
+
delegateAddress: raw.delegate_address,
|
|
1532
|
+
chainId: raw.chain_id,
|
|
1533
|
+
allowances: raw.allowances.map((allowance) => ({
|
|
1534
|
+
id: allowance.id,
|
|
1535
|
+
tokenAddress: allowance.token_address,
|
|
1536
|
+
tokenSymbol: allowance.token_symbol,
|
|
1537
|
+
configuredAmount: allowance.configured_amount,
|
|
1538
|
+
resetPeriodMin: allowance.reset_period_min,
|
|
1539
|
+
onchain: {
|
|
1540
|
+
amount: allowance.onchain.amount,
|
|
1541
|
+
spent: allowance.onchain.spent,
|
|
1542
|
+
remaining: allowance.onchain.remaining,
|
|
1543
|
+
effectiveSpent: allowance.onchain.effective_spent,
|
|
1544
|
+
resetTimeMin: allowance.onchain.reset_time_min,
|
|
1545
|
+
lastResetMin: allowance.onchain.last_reset_min,
|
|
1546
|
+
nonce: allowance.onchain.nonce,
|
|
1547
|
+
isResetPending: allowance.onchain.is_reset_pending,
|
|
1548
|
+
remainingIsFromChain: allowance.onchain.remaining_is_from_chain
|
|
1549
|
+
}
|
|
1550
|
+
}))
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
async getPostPurchaseAllowanceSummary(paymentId) {
|
|
1554
|
+
const unavailable = (detail, payment2 = null) => ({
|
|
1555
|
+
payment: payment2,
|
|
1556
|
+
allowance: null,
|
|
1557
|
+
warnings: [{
|
|
1558
|
+
code: AgentPaymentWarningCode.AllowanceCheckUnavailable,
|
|
1559
|
+
message: `Could not read the post-purchase allowance/budget for payment ${paymentId} (${detail}). The payment itself succeeded \u2014 the on-chain policy remains the actual spend gate; this only affects the remaining-budget figure reported here.`
|
|
1560
|
+
}]
|
|
1561
|
+
});
|
|
1562
|
+
const [statusResult, agentResult, allowanceResult] = await Promise.allSettled([
|
|
1563
|
+
this.getPaymentStatus(paymentId),
|
|
1564
|
+
this.getAgent(),
|
|
1565
|
+
this.getAllowances()
|
|
1566
|
+
]);
|
|
1567
|
+
if (statusResult.status === "rejected") {
|
|
1568
|
+
return unavailable(statusResult.reason instanceof Error ? statusResult.reason.message : String(statusResult.reason));
|
|
1569
|
+
}
|
|
1570
|
+
const payment = statusResult.value;
|
|
1571
|
+
if (agentResult.status === "rejected") {
|
|
1572
|
+
return unavailable(agentResult.reason instanceof Error ? agentResult.reason.message : String(agentResult.reason), payment);
|
|
1573
|
+
}
|
|
1574
|
+
if (allowanceResult.status === "rejected") {
|
|
1575
|
+
return unavailable(allowanceResult.reason instanceof Error ? allowanceResult.reason.message : String(allowanceResult.reason), payment);
|
|
1576
|
+
}
|
|
1577
|
+
try {
|
|
1578
|
+
const tokenAddress = payment.asset ?? payment.x402?.asset ?? null;
|
|
1579
|
+
if (!tokenAddress) return unavailable("the settled payment does not carry a resolvable token address", payment);
|
|
1580
|
+
const match = allowanceResult.value.allowances.find(
|
|
1581
|
+
(allowance) => allowance.tokenAddress.toLowerCase() === tokenAddress.toLowerCase()
|
|
1582
|
+
);
|
|
1583
|
+
if (!match) return unavailable("no allowance/budget row matches the settled token", payment);
|
|
1584
|
+
const token = resolveTokenFromAddress(match.tokenAddress);
|
|
1585
|
+
const remainingDisplay = token ? `${formatAtomicAmount(safeBigInt(match.onchain.remaining), token.decimals)} ${match.tokenSymbol}` : void 0;
|
|
1586
|
+
const rail = agentResult.value.executionRail;
|
|
1587
|
+
return {
|
|
1588
|
+
payment,
|
|
1589
|
+
allowance: {
|
|
1590
|
+
rail,
|
|
1591
|
+
remaining_atomic: match.onchain.remaining,
|
|
1592
|
+
...remainingDisplay ? { remaining_display: remainingDisplay } : {},
|
|
1593
|
+
token_symbol: match.tokenSymbol,
|
|
1594
|
+
token_address: match.tokenAddress,
|
|
1595
|
+
reset_period: match.resetPeriodMin,
|
|
1596
|
+
source: rail === "delegation" ? "active_delegations" : "allowance_module"
|
|
1597
|
+
},
|
|
1598
|
+
warnings: []
|
|
1599
|
+
};
|
|
1600
|
+
} catch (error) {
|
|
1601
|
+
return unavailable(error instanceof Error ? error.message : String(error));
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
async listReceipts(options = {}) {
|
|
1605
|
+
const query = options.limit ? `?limit=${encodeURIComponent(String(options.limit))}` : "";
|
|
1606
|
+
const raw = await this.transport.get(`/machine-payments/receipts${query}`);
|
|
1607
|
+
return raw.receipts.map(mapPaymentReceipt);
|
|
1608
|
+
}
|
|
1609
|
+
async getReceipt(paymentId) {
|
|
1610
|
+
const { receipt } = await this.transport.get(`/payments/${paymentId}/receipt`);
|
|
1611
|
+
return { receipt, verification: verifyPaymentReceipt(receipt) };
|
|
1612
|
+
}
|
|
1613
|
+
async fetchAgent() {
|
|
1614
|
+
const raw = await this.transport.get("/machine-payments/agent");
|
|
1615
|
+
return {
|
|
1616
|
+
id: raw.id,
|
|
1617
|
+
name: raw.name,
|
|
1618
|
+
status: raw.status,
|
|
1619
|
+
safeAddress: raw.safe_address,
|
|
1620
|
+
delegateAddress: raw.delegate_address,
|
|
1621
|
+
chainId: raw.chain_id,
|
|
1622
|
+
executionRail: raw.execution_rail === "delegation" ? "delegation" : "legacy"
|
|
1623
|
+
};
|
|
1624
|
+
}
|
|
1625
|
+
};
|
|
1626
|
+
function createJsonRpcProvider(url) {
|
|
1627
|
+
return new ethers.ethers.JsonRpcProvider(url);
|
|
1628
|
+
}
|
|
1629
|
+
function createWallet(privateKey, provider) {
|
|
1630
|
+
return new ethers.ethers.Wallet(privateKey, provider);
|
|
1631
|
+
}
|
|
1632
|
+
function createErc20Contract(address, abi, runner) {
|
|
1633
|
+
return new ethers.ethers.Contract(address, abi, runner);
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
// src/delegate-sweep.ts
|
|
1637
|
+
function isWaitTimeout(err) {
|
|
1638
|
+
return err?.code === "TIMEOUT";
|
|
1639
|
+
}
|
|
1640
|
+
async function waitForSweepTx(tx) {
|
|
1641
|
+
let receipt;
|
|
1642
|
+
try {
|
|
1643
|
+
receipt = await tx.wait(1, DEFAULT_CONFIRMATION_TIMEOUT_MS);
|
|
1644
|
+
} catch (err) {
|
|
1645
|
+
if (!isWaitTimeout(err)) throw err;
|
|
1646
|
+
return { txHash: tx.hash, confirmation: "unconfirmed" };
|
|
1647
|
+
}
|
|
1648
|
+
if (!receipt) return { txHash: tx.hash, confirmation: "unconfirmed" };
|
|
1649
|
+
return { txHash: receipt.hash, confirmation: "confirmed" };
|
|
1650
|
+
}
|
|
1651
|
+
var DelegateSweepApi = class {
|
|
1652
|
+
constructor(options) {
|
|
1653
|
+
this.options = options;
|
|
1654
|
+
}
|
|
1655
|
+
options;
|
|
1656
|
+
async sweepDelegate() {
|
|
1657
|
+
if (!this.options.delegateKey) throw new HavenSigningError("delegateKey is required for sweepDelegate.");
|
|
1658
|
+
const agent = await this.options.getAgent();
|
|
1659
|
+
if (!agent.delegateAddress) throw new HavenApiError("Agent has no delegate address.", 422);
|
|
1660
|
+
const rpcUrl = this.options.chainRpcs[agent.chainId];
|
|
1661
|
+
if (!rpcUrl) throw new HavenApiError(`chainRpcs[${agent.chainId}] must be configured to sweep the delegate wallet.`, 422);
|
|
1662
|
+
const provider = createJsonRpcProvider(rpcUrl);
|
|
1663
|
+
const wallet = createWallet(this.options.delegateKey, provider);
|
|
1664
|
+
const transfers = [];
|
|
1665
|
+
if (isSweepableChain(agent.chainId)) {
|
|
1666
|
+
const contract = createErc20Contract(sweepUsdcAddress(agent.chainId), ["function balanceOf(address) view returns (uint256)", "function transfer(address to, uint256 amount) returns (bool)"], wallet);
|
|
1667
|
+
const balance2 = await contract.balanceOf(agent.delegateAddress);
|
|
1668
|
+
if (balance2 > 0n) {
|
|
1669
|
+
const tx = await contract.transfer(agent.safeAddress, balance2);
|
|
1670
|
+
const { txHash, confirmation } = await waitForSweepTx(tx);
|
|
1671
|
+
transfers.push({ asset: "USDC", amount: format(balance2, 6), amountAtomic: balance2.toString(), txHash, explorerUrl: this.options.buildExplorerUrl(agent.chainId, txHash), confirmation });
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
const balance = await provider.getBalance(agent.delegateAddress);
|
|
1675
|
+
if (balance > 0n) {
|
|
1676
|
+
const fee = await provider.getFeeData();
|
|
1677
|
+
const send = balance - (fee.maxFeePerGas ?? fee.gasPrice ?? 1000000n) * 21000n * 2n;
|
|
1678
|
+
if (send > 0n) {
|
|
1679
|
+
const tx = await wallet.sendTransaction({ to: agent.safeAddress, value: send });
|
|
1680
|
+
const { txHash, confirmation } = await waitForSweepTx(tx);
|
|
1681
|
+
transfers.push({ asset: "ETH", amount: format(send, 18), amountAtomic: send.toString(), txHash, explorerUrl: this.options.buildExplorerUrl(agent.chainId, txHash), confirmation });
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
return { fromAddress: agent.delegateAddress, toAddress: agent.safeAddress, chainId: agent.chainId, transfers, unconfirmed: transfers.some((t) => t.confirmation === "unconfirmed") };
|
|
1685
|
+
}
|
|
1686
|
+
prepareSweep() {
|
|
1687
|
+
return this.options.transport.post("/machine-payments/sweep/prepare", {});
|
|
1688
|
+
}
|
|
1689
|
+
submitSweep(authorization, signature) {
|
|
1690
|
+
return this.options.transport.post("/machine-payments/sweep/submit", { authorization, signature });
|
|
1691
|
+
}
|
|
1692
|
+
};
|
|
1693
|
+
function format(value, decimals) {
|
|
1694
|
+
const raw = value.toString().padStart(decimals + 1, "0");
|
|
1695
|
+
return `${raw.slice(0, -decimals) || "0"}.${raw.slice(-decimals).replace(/0+$/, "") || "0"}`;
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
// src/x402-protocol.ts
|
|
1699
|
+
var CHAIN_EXPLORER_TX = {
|
|
1700
|
+
100: "https://gnosisscan.io/tx",
|
|
1701
|
+
8453: "https://basescan.org/tx"
|
|
1702
|
+
};
|
|
1703
|
+
function buildExplorerUrl(chainId, txHash) {
|
|
1704
|
+
const base = CHAIN_EXPLORER_TX[chainId ?? 8453] ?? CHAIN_EXPLORER_TX[8453];
|
|
1705
|
+
return `${base}/${txHash}`;
|
|
1706
|
+
}
|
|
1707
|
+
function explorerUrlOrEmpty(chainId, txHash) {
|
|
1708
|
+
return txHash ? buildExplorerUrl(chainId, txHash) : "";
|
|
1709
|
+
}
|
|
1710
|
+
function chainIdFromNetwork(network) {
|
|
1711
|
+
if (network === "base") return 8453;
|
|
1712
|
+
if (network === "base-sepolia") return 84532;
|
|
1713
|
+
if (!network?.startsWith("eip155:")) return void 0;
|
|
1714
|
+
const chainId = Number(network.slice("eip155:".length));
|
|
1715
|
+
return Number.isFinite(chainId) ? chainId : void 0;
|
|
1716
|
+
}
|
|
1717
|
+
function chainIdOrNull(network) {
|
|
1718
|
+
return chainIdFromNetwork(network) ?? null;
|
|
1719
|
+
}
|
|
1720
|
+
function sameAddress3(a, b) {
|
|
1721
|
+
return Boolean(a && b && a.toLowerCase() === b.toLowerCase());
|
|
1722
|
+
}
|
|
1723
|
+
function decimalFromUsdcAtomic(value) {
|
|
1724
|
+
const amount = BigInt(value);
|
|
1725
|
+
const whole = amount / 1000000n;
|
|
1726
|
+
const fraction = (amount % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
|
|
1727
|
+
return fraction ? `${whole}.${fraction}` : whole.toString();
|
|
1728
|
+
}
|
|
1729
|
+
function normalizeDecimal(value) {
|
|
1730
|
+
if (!value.includes(".")) return value.replace(/^0+(?=\d)/, "") || "0";
|
|
1731
|
+
const [whole, fraction = ""] = value.split(".");
|
|
1732
|
+
const normalizedWhole = whole.replace(/^0+(?=\d)/, "") || "0";
|
|
1733
|
+
const normalizedFraction = fraction.replace(/0+$/, "");
|
|
1734
|
+
return normalizedFraction ? `${normalizedWhole}.${normalizedFraction}` : normalizedWhole;
|
|
1735
|
+
}
|
|
1736
|
+
function x402PayerAddress(delegateAddress, x402Wallet) {
|
|
1737
|
+
return delegateAddress ?? x402Wallet;
|
|
1738
|
+
}
|
|
1739
|
+
function withX402Wallet(init, wallet) {
|
|
1740
|
+
if (!wallet) return init;
|
|
1741
|
+
const headers = new Headers(init?.headers);
|
|
1742
|
+
if (!headers.has("x402-wallet")) {
|
|
1743
|
+
headers.set("x402-wallet", wallet);
|
|
1744
|
+
}
|
|
1745
|
+
return {
|
|
1746
|
+
...init,
|
|
1747
|
+
headers
|
|
1748
|
+
};
|
|
1749
|
+
}
|
|
1750
|
+
function snapshotRequestBody(body) {
|
|
1751
|
+
if (body == null) return void 0;
|
|
1752
|
+
if (typeof body === "string") return body;
|
|
1753
|
+
if (body instanceof URLSearchParams) return body.toString();
|
|
1754
|
+
throw new HavenApiError(
|
|
1755
|
+
"Quote helpers can only capture resumable request bodies that are strings or URLSearchParams. For streams, blobs, or binary bodies, preserve the original request yourself and call the matching resume method with fresh init.",
|
|
1756
|
+
400
|
|
1757
|
+
);
|
|
1758
|
+
}
|
|
1759
|
+
function snapshotX402Request(url, init) {
|
|
1760
|
+
return {
|
|
1761
|
+
url,
|
|
1762
|
+
method: init?.method ?? "GET",
|
|
1763
|
+
headers: Array.from(new Headers(init?.headers).entries()),
|
|
1764
|
+
body: snapshotRequestBody(init?.body)
|
|
1765
|
+
};
|
|
1766
|
+
}
|
|
1767
|
+
function requestInitFromSnapshot(request) {
|
|
1768
|
+
return {
|
|
1769
|
+
method: request.method,
|
|
1770
|
+
headers: request.headers,
|
|
1771
|
+
body: request.body
|
|
1772
|
+
};
|
|
1773
|
+
}
|
|
1774
|
+
function buildX402Quote(paymentRequired, request, idempotencyKey, mcpTransport) {
|
|
1775
|
+
const option = selectStandardPaymentOption(paymentRequired.accepts);
|
|
1776
|
+
if (!option) {
|
|
1777
|
+
throw new HavenApiError(
|
|
1778
|
+
"No compatible payment option found in x402 requirements. Haven supports standard x402 exact payments on Base USDC.",
|
|
1779
|
+
400
|
|
1780
|
+
);
|
|
1781
|
+
}
|
|
1782
|
+
const token = resolveTokenFromAddress(option.asset, option.network);
|
|
1783
|
+
return {
|
|
1784
|
+
rail: "x402",
|
|
1785
|
+
idempotencyKey: idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option),
|
|
1786
|
+
paymentRequired,
|
|
1787
|
+
accepted: option,
|
|
1788
|
+
request,
|
|
1789
|
+
...mcpTransport ? { mcpTransport } : {},
|
|
1790
|
+
resourceUrl: paymentRequired.resource.url,
|
|
1791
|
+
description: paymentRequired.resource.description ?? option.description ?? null,
|
|
1792
|
+
mimeType: paymentRequired.resource.mimeType ?? option.mimeType ?? null,
|
|
1793
|
+
amountAtomic: x402AuthorizationAmount(option),
|
|
1794
|
+
amount: decimalFromUsdcAtomic(x402AuthorizationAmount(option)),
|
|
1795
|
+
token: token?.symbol ?? "USDC",
|
|
1796
|
+
// #1351: null when the asset is unrecognised on this network — the
|
|
1797
|
+
// `token` fallback above is a LABEL, not evidence of 6 decimals, and a
|
|
1798
|
+
// human-denominated cap must fail closed rather than convert against a
|
|
1799
|
+
// guess. Same resolution as `token`, so the two never disagree.
|
|
1800
|
+
decimals: token?.decimals ?? null,
|
|
1801
|
+
asset: option.asset,
|
|
1802
|
+
network: option.network,
|
|
1803
|
+
chainId: chainIdOrNull(option.network),
|
|
1804
|
+
merchantAddress: option.payTo,
|
|
1805
|
+
maxTimeoutSeconds: option.maxTimeoutSeconds
|
|
1806
|
+
};
|
|
1807
|
+
}
|
|
1808
|
+
function buildX402Receipt(input) {
|
|
1809
|
+
const fundingExplorerUrl = input.explorerUrl || explorerUrlOrEmpty(input.chainId, input.txHash);
|
|
1810
|
+
return {
|
|
1811
|
+
success: true,
|
|
1812
|
+
paymentId: input.paymentId,
|
|
1813
|
+
txHash: input.txHash,
|
|
1814
|
+
token: input.token,
|
|
1815
|
+
amount: input.amount,
|
|
1816
|
+
to: input.to,
|
|
1817
|
+
resourceUrl: input.resourceUrl,
|
|
1818
|
+
explorerUrl: input.explorerUrl,
|
|
1819
|
+
accepted: input.accepted,
|
|
1820
|
+
paymentHeader: input.paymentHeader,
|
|
1821
|
+
merchantTo: input.merchantTo ?? input.accepted.payTo,
|
|
1822
|
+
payer: input.payer,
|
|
1823
|
+
chainId: input.chainId,
|
|
1824
|
+
haven: {
|
|
1825
|
+
paymentId: input.paymentId,
|
|
1826
|
+
fundingTxHash: input.txHash,
|
|
1827
|
+
fundingExplorerUrl
|
|
1828
|
+
},
|
|
1829
|
+
merchant: {
|
|
1830
|
+
payTo: input.merchantTo ?? input.accepted.payTo
|
|
1831
|
+
},
|
|
1832
|
+
x402: {
|
|
1833
|
+
amount: x402AuthorizationAmount(input.accepted),
|
|
1834
|
+
token: input.token,
|
|
1835
|
+
network: input.accepted.network,
|
|
1836
|
+
asset: input.accepted.asset,
|
|
1837
|
+
resource: input.accepted.resource ?? input.resourceUrl
|
|
1838
|
+
}
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
function buildX402ResumeState(input) {
|
|
1842
|
+
const token = resolveTokenFromAddress(input.accepted.asset, input.accepted.network);
|
|
1843
|
+
return {
|
|
1844
|
+
rail: "x402",
|
|
1845
|
+
paymentId: input.paymentId,
|
|
1846
|
+
idempotencyKey: input.idempotencyKey,
|
|
1847
|
+
paymentRequired: input.paymentRequired,
|
|
1848
|
+
accepted: input.accepted,
|
|
1849
|
+
url: input.request?.url ?? input.paymentRequired.resource.url,
|
|
1850
|
+
request: input.request,
|
|
1851
|
+
resourceUrl: input.paymentRequired.resource.url,
|
|
1852
|
+
description: input.paymentRequired.resource.description ?? input.accepted.description ?? null,
|
|
1853
|
+
amountAtomic: x402AuthorizationAmount(input.accepted),
|
|
1854
|
+
amount: decimalFromUsdcAtomic(x402AuthorizationAmount(input.accepted)),
|
|
1855
|
+
token: token?.symbol ?? "USDC",
|
|
1856
|
+
asset: input.accepted.asset,
|
|
1857
|
+
network: input.accepted.network,
|
|
1858
|
+
chainId: chainIdOrNull(input.accepted.network),
|
|
1859
|
+
merchantAddress: input.accepted.payTo
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
function attachX402ResumeState(err, paymentRequired, accepted, idempotencyKey, request) {
|
|
1863
|
+
if (!(err instanceof HavenPaymentStateError)) return;
|
|
1864
|
+
if (err.state.rail !== "x402") return;
|
|
1865
|
+
err.resumeState = buildX402ResumeState({
|
|
1866
|
+
paymentId: err.state.paymentId,
|
|
1867
|
+
paymentRequired,
|
|
1868
|
+
accepted,
|
|
1869
|
+
idempotencyKey,
|
|
1870
|
+
request
|
|
1871
|
+
});
|
|
1872
|
+
}
|
|
1873
|
+
function attachResumeState(err, input) {
|
|
1874
|
+
attachX402ResumeState(
|
|
1875
|
+
err,
|
|
1876
|
+
input.paymentRequired,
|
|
1877
|
+
input.accepted,
|
|
1878
|
+
input.idempotencyKey,
|
|
1879
|
+
input.request
|
|
1880
|
+
);
|
|
1881
|
+
}
|
|
1882
|
+
function assertCanResumeX402(status, paymentRequired, option) {
|
|
1883
|
+
if (status.rail !== "x402") {
|
|
1884
|
+
throw new HavenPaymentStateError(
|
|
1885
|
+
`Payment ${status.paymentId} is ${status.rail}, not x402.`,
|
|
1886
|
+
409,
|
|
1887
|
+
status
|
|
1888
|
+
);
|
|
1889
|
+
}
|
|
1890
|
+
if (status.nextAction !== AgentPaymentNextAction.RetryOriginalX402Request) {
|
|
1891
|
+
throw new HavenPaymentStateError(status.message, paymentStateStatusCode(status.status, 409), status);
|
|
1892
|
+
}
|
|
1893
|
+
if (!status.txHash) {
|
|
1894
|
+
throw new HavenApiError(
|
|
1895
|
+
`x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,
|
|
1896
|
+
502,
|
|
1897
|
+
status,
|
|
1898
|
+
status.paymentId
|
|
1899
|
+
);
|
|
1900
|
+
}
|
|
1901
|
+
if (status.resourceUrl && status.resourceUrl !== paymentRequired.resource.url) {
|
|
1902
|
+
throw new HavenApiError(
|
|
1903
|
+
"x402 resume request does not match the approved resource URL.",
|
|
1904
|
+
409,
|
|
1905
|
+
{ status, paymentRequired },
|
|
1906
|
+
status.paymentId
|
|
1907
|
+
);
|
|
1908
|
+
}
|
|
1909
|
+
if (status.merchantAddress && !sameAddress3(status.merchantAddress, option.payTo)) {
|
|
1910
|
+
throw new HavenApiError(
|
|
1911
|
+
"x402 resume request does not match the approved merchant.",
|
|
1912
|
+
409,
|
|
1913
|
+
{ status, selectedPayment: option },
|
|
1914
|
+
status.paymentId
|
|
1915
|
+
);
|
|
1916
|
+
}
|
|
1917
|
+
const optionChainId = chainIdFromNetwork(option.network);
|
|
1918
|
+
if (status.chainId && optionChainId && status.chainId !== optionChainId) {
|
|
1919
|
+
throw new HavenApiError(
|
|
1920
|
+
"x402 resume request does not match the approved network.",
|
|
1921
|
+
409,
|
|
1922
|
+
{ status, selectedPayment: option },
|
|
1923
|
+
status.paymentId
|
|
1924
|
+
);
|
|
1925
|
+
}
|
|
1926
|
+
if (status.token && status.token !== "USDC") {
|
|
1927
|
+
throw new HavenApiError(
|
|
1928
|
+
"x402 resume request does not match the approved token.",
|
|
1929
|
+
409,
|
|
1930
|
+
{ status, selectedPayment: option },
|
|
1931
|
+
status.paymentId
|
|
1932
|
+
);
|
|
1933
|
+
}
|
|
1934
|
+
const approvedAmount = status.amount ? normalizeDecimal(status.amount) : "";
|
|
1935
|
+
const requestedAmount = normalizeDecimal(decimalFromUsdcAtomic(x402AuthorizationAmount(option)));
|
|
1936
|
+
if (approvedAmount && approvedAmount !== requestedAmount) {
|
|
1937
|
+
throw new HavenApiError(
|
|
1938
|
+
"x402 resume request does not match the approved amount.",
|
|
1939
|
+
409,
|
|
1940
|
+
{ status, selectedPayment: option },
|
|
1941
|
+
status.paymentId
|
|
1942
|
+
);
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
var X402FundingLeg = class {
|
|
1946
|
+
delegateKey;
|
|
1947
|
+
delegateAddress;
|
|
1948
|
+
x402Wallet;
|
|
1949
|
+
chainRpcs;
|
|
1950
|
+
post;
|
|
1951
|
+
signForData;
|
|
1952
|
+
assertSignableAuthorizationState;
|
|
1953
|
+
/**
|
|
1954
|
+
* Receipts keyed by idempotency key, held only as long as the underlying
|
|
1955
|
+
* EIP-3009 authorization is valid. The cache belongs to this module rather
|
|
1956
|
+
* than to the facade because its expiry is read out of the authorization
|
|
1957
|
+
* header itself — a 3009 artifact.
|
|
1958
|
+
*/
|
|
1959
|
+
receiptCache = /* @__PURE__ */ new Map();
|
|
1960
|
+
constructor(options) {
|
|
1961
|
+
this.delegateKey = options.delegateKey;
|
|
1962
|
+
this.delegateAddress = options.delegateAddress;
|
|
1963
|
+
this.x402Wallet = options.x402Wallet;
|
|
1964
|
+
this.chainRpcs = options.chainRpcs;
|
|
1965
|
+
this.post = options.post;
|
|
1966
|
+
this.signForData = options.signForData;
|
|
1967
|
+
this.assertSignableAuthorizationState = options.assertSignableAuthorizationState;
|
|
1968
|
+
}
|
|
1969
|
+
// ── Receipt cache ────────────────────────────────────────────────
|
|
1970
|
+
/** A still-valid cached receipt for this key, or undefined. */
|
|
1971
|
+
cachedReceipt(idempotencyKey) {
|
|
1972
|
+
const cached = this.receiptCache.get(idempotencyKey);
|
|
1973
|
+
if (cached && cached.expiresAt > Date.now()) return cached.receipt;
|
|
1974
|
+
return void 0;
|
|
1975
|
+
}
|
|
1976
|
+
cacheReceipt(idempotencyKey, paymentHeader, receipt) {
|
|
1977
|
+
const expiresAt = getPaymentHeaderValidBefore(paymentHeader);
|
|
1978
|
+
if (expiresAt > Date.now()) {
|
|
1979
|
+
this.receiptCache.set(idempotencyKey, { expiresAt, receipt });
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
// ── Authorization ────────────────────────────────────────────────
|
|
1983
|
+
async authorize(paymentRequired, option, idempotencyKey) {
|
|
1984
|
+
const raw = await this.post("/x402", {
|
|
1985
|
+
url: paymentRequired.resource.url,
|
|
1986
|
+
payTo: this.delegateAddress,
|
|
1987
|
+
merchantPayTo: option.payTo,
|
|
1988
|
+
amount: x402AuthorizationAmount(option),
|
|
1989
|
+
asset: option.asset,
|
|
1990
|
+
network: option.network,
|
|
1991
|
+
description: paymentRequired.resource.description,
|
|
1992
|
+
idempotencyKey,
|
|
1993
|
+
// #1360: same explicit funding-leg declaration as createX402Intent —
|
|
1994
|
+
// this local-key path derives payTo from the key (never stale), but the
|
|
1995
|
+
// declaration keeps both writers of the 3009 shape loud-by-default.
|
|
1996
|
+
settlementScheme: "eip3009"
|
|
1997
|
+
});
|
|
1998
|
+
const state = paymentStateFromRaw("x402 payment", raw);
|
|
1999
|
+
const executedReplay = raw.success && raw.tx_hash ? "idempotency-collision" : state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request ? "approval-resume" : null;
|
|
2000
|
+
if (executedReplay) {
|
|
2001
|
+
const canFund = await this.delegateCanFund(
|
|
2002
|
+
raw.chain_id ?? state?.chainId ?? chainIdFromNetwork(option.network),
|
|
2003
|
+
option.asset,
|
|
2004
|
+
x402AuthorizationAmount(option)
|
|
2005
|
+
);
|
|
2006
|
+
const refuse = executedReplay === "idempotency-collision" ? canFund !== true : canFund === false;
|
|
2007
|
+
if (refuse) {
|
|
2008
|
+
const settledReceipt = state && executedReplay === "approval-resume" ? this.receiptFromStatus(paymentRequired, option, void 0, state) : this.receiptFromAuthorization(paymentRequired, option, void 0, raw);
|
|
2009
|
+
throw new X402AlreadySettledError(
|
|
2010
|
+
canFund === false ? "This x402 payment already settled \u2014 the delegate no longer holds the funds to authorize it again. To buy the same item a second time, pass a distinct `idempotencyKey`; the synthesised key intentionally collapses repeat calls for the same product within a 5-minute window so a retried request cannot pay twice." : "This x402 payment already settled, and whether the delegate can still fund a new authorization could not be verified (no `chainRpcs` entry for this chain). Refusing rather than issue an authorization that may be unfundable. To buy the same item a second time, pass a distinct `idempotencyKey`; to finish an interrupted payment, resume it by `paymentId`.",
|
|
2011
|
+
settledReceipt,
|
|
2012
|
+
canFund === false ? "settled" : "unverifiable"
|
|
2013
|
+
);
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
const paymentHeader = await this.createPaymentHeader(paymentRequired, option);
|
|
2017
|
+
if (raw.success && raw.tx_hash) {
|
|
2018
|
+
const receipt2 = this.receiptFromAuthorization(paymentRequired, option, paymentHeader, raw);
|
|
2019
|
+
this.cacheReceipt(idempotencyKey, paymentHeader, receipt2);
|
|
2020
|
+
return receipt2;
|
|
2021
|
+
}
|
|
2022
|
+
if (state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request) {
|
|
2023
|
+
const receipt2 = this.receiptFromStatus(paymentRequired, option, paymentHeader, state);
|
|
2024
|
+
this.cacheReceipt(idempotencyKey, paymentHeader, receipt2);
|
|
2025
|
+
return receipt2;
|
|
2026
|
+
}
|
|
2027
|
+
this.assertSignableAuthorizationState("x402 payment", raw);
|
|
2028
|
+
if (!raw.sign_data?.hash) {
|
|
2029
|
+
throw new HavenApiError("No sign_hash returned from x402/authorize", 500, raw);
|
|
2030
|
+
}
|
|
2031
|
+
const sig = await this.signForData(raw.sign_data);
|
|
2032
|
+
const execResult = await this.post(
|
|
2033
|
+
`/payments/${raw.payment_id}/sign`,
|
|
2034
|
+
{ signature: sig }
|
|
2035
|
+
);
|
|
2036
|
+
if (execResult.status !== "confirmed") {
|
|
2037
|
+
throwPaymentStateError("x402 payment", execResult);
|
|
2038
|
+
}
|
|
2039
|
+
await this.waitForFundingTx(
|
|
2040
|
+
execResult.tx_hash,
|
|
2041
|
+
execResult.chain_id ?? chainIdFromNetwork(option.network)
|
|
2042
|
+
);
|
|
2043
|
+
const receipt = this.receiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult);
|
|
2044
|
+
this.cacheReceipt(idempotencyKey, paymentHeader, receipt);
|
|
2045
|
+
return receipt;
|
|
2046
|
+
}
|
|
2047
|
+
// ── Header minting ───────────────────────────────────────────────
|
|
2048
|
+
async createPaymentHeader(paymentRequired, option) {
|
|
2049
|
+
if (!this.delegateKey) {
|
|
2050
|
+
throw new HavenSigningError("delegateKey is required to sign x402 payment headers.");
|
|
2051
|
+
}
|
|
2052
|
+
const account = accounts.privateKeyToAccount(this.delegateKey);
|
|
2053
|
+
const requirements = toStandardPaymentRequirements(paymentRequired, option);
|
|
2054
|
+
const header = await schemes.exact.evm.createPaymentHeader(
|
|
2055
|
+
account,
|
|
2056
|
+
paymentRequired.x402Version,
|
|
2057
|
+
requirements
|
|
2058
|
+
);
|
|
2059
|
+
if (paymentRequired.x402Version < 2) return header;
|
|
2060
|
+
const payment = decodeBase64Json(header);
|
|
2061
|
+
return encodeBase64Json({
|
|
2062
|
+
x402Version: paymentRequired.x402Version,
|
|
2063
|
+
accepted: option,
|
|
2064
|
+
payload: payment.payload
|
|
2065
|
+
});
|
|
2066
|
+
}
|
|
2067
|
+
// ── Receipt mapping ──────────────────────────────────────────────
|
|
2068
|
+
receiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult) {
|
|
2069
|
+
const txHash = execResult?.tx_hash ?? raw.tx_hash ?? "";
|
|
2070
|
+
const chainId = execResult?.chain_id ?? raw.chain_id ?? chainIdFromNetwork(option.network);
|
|
2071
|
+
const token = execResult?.token ?? raw.token ?? "USDC";
|
|
2072
|
+
const amount = execResult?.amount ?? raw.amount ?? decimalFromUsdcAtomic(x402AuthorizationAmount(option));
|
|
2073
|
+
const to = execResult?.to ?? raw.to ?? this.delegateAddress ?? "";
|
|
2074
|
+
const explorerUrl = execResult?.explorer_url ?? raw.explorer_url ?? explorerUrlOrEmpty(chainId, txHash);
|
|
2075
|
+
const merchantTo = execResult?.merchant_to ?? raw.merchant_to ?? option.payTo;
|
|
2076
|
+
const payer = raw.payer ?? raw.safe_address ?? raw.sign_data?.components.safe;
|
|
2077
|
+
return buildX402Receipt({
|
|
2078
|
+
paymentId: raw.payment_id,
|
|
2079
|
+
txHash,
|
|
2080
|
+
token,
|
|
2081
|
+
amount,
|
|
2082
|
+
to,
|
|
2083
|
+
resourceUrl: paymentRequired.resource.url,
|
|
2084
|
+
explorerUrl,
|
|
2085
|
+
accepted: option,
|
|
2086
|
+
paymentHeader,
|
|
2087
|
+
merchantTo,
|
|
2088
|
+
payer,
|
|
2089
|
+
chainId
|
|
2090
|
+
});
|
|
2091
|
+
}
|
|
2092
|
+
receiptFromStatus(paymentRequired, option, paymentHeader, status) {
|
|
2093
|
+
if (!status.txHash) {
|
|
2094
|
+
throw new HavenApiError(
|
|
2095
|
+
`x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,
|
|
2096
|
+
502,
|
|
2097
|
+
status,
|
|
2098
|
+
status.paymentId
|
|
2099
|
+
);
|
|
2100
|
+
}
|
|
2101
|
+
return buildX402Receipt({
|
|
2102
|
+
paymentId: status.paymentId,
|
|
2103
|
+
txHash: status.txHash,
|
|
2104
|
+
token: status.token || "USDC",
|
|
2105
|
+
amount: status.amount || decimalFromUsdcAtomic(x402AuthorizationAmount(option)),
|
|
2106
|
+
to: this.delegateAddress ?? "",
|
|
2107
|
+
resourceUrl: paymentRequired.resource.url,
|
|
2108
|
+
explorerUrl: explorerUrlOrEmpty(status.chainId, status.txHash),
|
|
2109
|
+
accepted: option,
|
|
2110
|
+
paymentHeader,
|
|
2111
|
+
merchantTo: status.merchantAddress ?? option.payTo,
|
|
2112
|
+
payer: this.x402Wallet,
|
|
2113
|
+
chainId: status.chainId || chainIdFromNetwork(option.network)
|
|
2114
|
+
});
|
|
2115
|
+
}
|
|
2116
|
+
// ── On-chain reads ───────────────────────────────────────────────
|
|
2117
|
+
/**
|
|
2118
|
+
* Wait for a funding tx to be mined with ≥1 confirmation before the
|
|
2119
|
+
* merchant retry, eliminating the race where the merchant's
|
|
2120
|
+
* `balanceOf(delegate)` runs before the funding block propagates.
|
|
2121
|
+
*
|
|
2122
|
+
* Skipped when `chainRpcs` does not include the chain; in that case Haven's
|
|
2123
|
+
* backend has already confirmed on-chain submission and callers accept the
|
|
2124
|
+
* small propagation window as a trade-off for not configuring an RPC URL.
|
|
2125
|
+
*/
|
|
2126
|
+
async waitForFundingTx(txHash, chainId, timeoutMs = 3e4) {
|
|
2127
|
+
if (!txHash || !chainId) return;
|
|
2128
|
+
const rpcUrl = this.chainRpcs[chainId];
|
|
2129
|
+
if (!rpcUrl) return;
|
|
2130
|
+
const provider = createJsonRpcProvider(rpcUrl);
|
|
2131
|
+
const onChainReceipt = await provider.waitForTransaction(txHash, 1, timeoutMs);
|
|
2132
|
+
if (!onChainReceipt || onChainReceipt.status !== 1) {
|
|
2133
|
+
throw new HavenApiError(
|
|
2134
|
+
"Funding tx did not confirm on-chain within the timeout window.",
|
|
2135
|
+
500,
|
|
2136
|
+
{ txHash, chainId }
|
|
2137
|
+
);
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
/**
|
|
2141
|
+
* Can the delegate EOA still fund an authorization for `amountAtomic`?
|
|
2142
|
+
*
|
|
2143
|
+
* #1521: the only question that separates a legitimate resume (funding
|
|
2144
|
+
* confirmed, merchant never paid — the delegate still holds the money) from
|
|
2145
|
+
* a replayed settled payment (funding confirmed, merchant paid, delegate
|
|
2146
|
+
* spent). The intent's own `status: 'confirmed'` is identical in both.
|
|
2147
|
+
*
|
|
2148
|
+
* The balance is asked of the CHAIN rather than of Haven's bookkeeping on
|
|
2149
|
+
* purpose: the merchant-settlement evidence record is written by this SDK
|
|
2150
|
+
* *after* the merchant call, so a client that dies between the two leaves
|
|
2151
|
+
* the backend believing the merchant was never paid — the exact case the
|
|
2152
|
+
* discriminator has to get right. The chain cannot be behind in that way.
|
|
2153
|
+
*
|
|
2154
|
+
* Returns `null` — never a guess — when `chainRpcs` has no entry for the
|
|
2155
|
+
* chain or the read fails. Callers must treat that as "unverifiable", not
|
|
2156
|
+
* as "funded".
|
|
2157
|
+
*/
|
|
2158
|
+
async delegateCanFund(chainId, tokenAddress, amountAtomic, timeoutMs = 1e4) {
|
|
2159
|
+
if (!chainId || !this.delegateAddress) return null;
|
|
2160
|
+
const rpcUrl = this.chainRpcs[chainId];
|
|
2161
|
+
if (!rpcUrl) return null;
|
|
2162
|
+
try {
|
|
2163
|
+
const provider = createJsonRpcProvider(rpcUrl);
|
|
2164
|
+
const token = createErc20Contract(
|
|
2165
|
+
tokenAddress,
|
|
2166
|
+
["function balanceOf(address) view returns (uint256)"],
|
|
2167
|
+
provider
|
|
2168
|
+
);
|
|
2169
|
+
const balance = await Promise.race([
|
|
2170
|
+
token.balanceOf(this.delegateAddress),
|
|
2171
|
+
new Promise((resolve) => setTimeout(() => resolve(null), timeoutMs).unref?.())
|
|
2172
|
+
]);
|
|
2173
|
+
if (balance === null) return null;
|
|
2174
|
+
return balance >= BigInt(amountAtomic);
|
|
2175
|
+
} catch {
|
|
2176
|
+
return null;
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
};
|
|
2180
|
+
function getPaymentHeaderValidBefore(paymentHeader) {
|
|
2181
|
+
try {
|
|
2182
|
+
const payment = decodeBase64Json(
|
|
2183
|
+
paymentHeader
|
|
2184
|
+
);
|
|
2185
|
+
const payload = payment.payload;
|
|
2186
|
+
const validBeforeSeconds = Number(payload.authorization?.validBefore);
|
|
2187
|
+
if (Number.isFinite(validBeforeSeconds)) return validBeforeSeconds * 1e3;
|
|
2188
|
+
} catch {
|
|
2189
|
+
}
|
|
2190
|
+
return 0;
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
// src/x402-erc7710.ts
|
|
2194
|
+
var X402Erc7710 = class {
|
|
2195
|
+
delegateKey;
|
|
2196
|
+
post;
|
|
2197
|
+
signForData;
|
|
2198
|
+
getAgent;
|
|
2199
|
+
constructor(options) {
|
|
2200
|
+
this.delegateKey = options.delegateKey;
|
|
2201
|
+
this.post = options.post;
|
|
2202
|
+
this.signForData = options.signForData;
|
|
2203
|
+
this.getAgent = options.getAgent;
|
|
2204
|
+
}
|
|
2205
|
+
/**
|
|
2206
|
+
* Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).
|
|
2207
|
+
*
|
|
2208
|
+
* The whole point of this path is what it does NOT do. There is no funding
|
|
2209
|
+
* leg: the merchant redeems a delegation chain and pulls from the treasury
|
|
2210
|
+
* directly, so the delegate EOA never holds the money, no sweep can strand
|
|
2211
|
+
* it, and the #713 reconciliation class does not apply. It is also why this
|
|
2212
|
+
* method is SMALLER than the 3009 path — the backend assembles the merchant
|
|
2213
|
+
* `X-PAYMENT` header in `assembleSettlementPayload`, so the SDK builds no
|
|
2214
|
+
* header locally.
|
|
2215
|
+
*
|
|
2216
|
+
* authorize (payTo = the MERCHANT) → sign the child → settle → header
|
|
2217
|
+
*
|
|
2218
|
+
* The caller then retries the merchant with that header. **Nothing has
|
|
2219
|
+
* settled when this returns** — that is why it does not return an
|
|
2220
|
+
* `X402Receipt`.
|
|
2221
|
+
*
|
|
2222
|
+
* Requires a delegation-rail account. The backend enforces that
|
|
2223
|
+
* (`validateGenericSchemeRail`), and so does this method, before building a
|
|
2224
|
+
* request the backend would only reject: an error a client can explain is
|
|
2225
|
+
* worth more than a 400 it has to decode.
|
|
2226
|
+
*
|
|
2227
|
+
* **MCP callers must pass `options.resourceUrl`.** An in-band MCP 402
|
|
2228
|
+
* challenge frequently carries no `resource` object at all, so
|
|
2229
|
+
* `paymentRequired.resource?.url` is undefined and the backend answers
|
|
2230
|
+
* "Valid url is required". The QA scenario this path was ported from falls
|
|
2231
|
+
* back to the request URL for exactly that reason — the SDK cannot, because
|
|
2232
|
+
* it never saw the request. Pass it.
|
|
2233
|
+
*/
|
|
2234
|
+
async settle(paymentRequired, options = {}) {
|
|
2235
|
+
if (!this.delegateKey) {
|
|
2236
|
+
throw new HavenSigningError(
|
|
2237
|
+
"delegateKey is required for x402 payments. Pass it in the HavenClient config."
|
|
2238
|
+
);
|
|
2239
|
+
}
|
|
2240
|
+
const prepared = await this.prepare(paymentRequired, options);
|
|
2241
|
+
const signature = await this.signForData(prepared.signData);
|
|
2242
|
+
const paymentHeader = await this.submit(prepared.paymentId, signature);
|
|
2243
|
+
return { ...prepared.settlement, paymentHeader };
|
|
2244
|
+
}
|
|
2245
|
+
/**
|
|
2246
|
+
* The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build
|
|
2247
|
+
* the request, and return the child to be signed — without signing it.
|
|
2248
|
+
*
|
|
2249
|
+
* Split out because the hosted topology cannot use `settleX402Erc7710()`:
|
|
2250
|
+
* that method signs in-process with `delegateKey`, and hosted Haven does not
|
|
2251
|
+
* have one and must not. The hosted MCP server drives these two halves with
|
|
2252
|
+
* the LOCAL signer in between, so the key stays where it belongs and the
|
|
2253
|
+
* request shaping stays in one place rather than being reimplemented.
|
|
2254
|
+
*/
|
|
2255
|
+
async prepare(paymentRequired, options = {}) {
|
|
2256
|
+
const delegationRail = options.delegationRail ?? (await this.getAgent()).executionRail === "delegation";
|
|
2257
|
+
if (!delegationRail) {
|
|
2258
|
+
throw new HavenApiError(
|
|
2259
|
+
"erc7710 settlement requires a delegation-rail account; this one is not on it. Use authorizeX402() for the standard EIP-3009 path.",
|
|
2260
|
+
400
|
|
2261
|
+
);
|
|
2262
|
+
}
|
|
2263
|
+
const selection = selectX402SettlementScheme(paymentRequired.accepts, { delegationRail });
|
|
2264
|
+
if (!selection || selection.scheme !== "erc7710") {
|
|
2265
|
+
throw new HavenApiError(
|
|
2266
|
+
"This merchant does not advertise an erc7710 settlement option (no accepts[] entry carries extra.assetTransferMethod: 'erc7710'). Use authorizeX402() for the standard EIP-3009 path.",
|
|
2267
|
+
400
|
|
2268
|
+
);
|
|
2269
|
+
}
|
|
2270
|
+
const option = selection.option;
|
|
2271
|
+
const merchantPayTo = option.payTo;
|
|
2272
|
+
const amountAtomic = x402AuthorizationAmount(option);
|
|
2273
|
+
const raw = await this.post("/x402", {
|
|
2274
|
+
url: options.resourceUrl ?? paymentRequired.resource?.url,
|
|
2275
|
+
// payTo = the MERCHANT is what selects direct settlement server-side.
|
|
2276
|
+
// The explicit settlementScheme must AGREE with that shape (#1360) —
|
|
2277
|
+
// disagreement is a 400 by design, so that a stale delegate address
|
|
2278
|
+
// becomes a loud mismatch instead of a silent reroute to the 3009 leg.
|
|
2279
|
+
payTo: merchantPayTo,
|
|
2280
|
+
settlementScheme: "erc7710",
|
|
2281
|
+
amount: amountAtomic,
|
|
2282
|
+
asset: option.asset,
|
|
2283
|
+
network: option.network,
|
|
2284
|
+
// The v2 header echoes the accepted entry field-for-field, so the quoted
|
|
2285
|
+
// timeout must round-trip or the merchant rejects the echo (#1064).
|
|
2286
|
+
maxTimeoutSeconds: option.maxTimeoutSeconds,
|
|
2287
|
+
// #1058: forward the advertised facilitators verbatim — the child becomes
|
|
2288
|
+
// redeemable ONLY by them. `null` here means the merchant advertised none
|
|
2289
|
+
// (or an empty array, which the backend 400s on), so the field is OMITTED
|
|
2290
|
+
// rather than sent empty. See x402FacilitatorAddresses.
|
|
2291
|
+
...selection.facilitatorAddresses ? { facilitatorAddresses: selection.facilitatorAddresses } : {},
|
|
2292
|
+
// #1307/#1547: persisted so the settle leg can rehydrate the merchant
|
|
2293
|
+
// call by payment_id on this scheme too, not only on the 3009 bridge.
|
|
2294
|
+
...options.mcpCallContext ? { mcpCallContext: options.mcpCallContext } : {}
|
|
2295
|
+
});
|
|
2296
|
+
if (!raw.payment_id) {
|
|
2297
|
+
throw new HavenApiError("No payment_id returned from x402/authorize", 500, raw);
|
|
2298
|
+
}
|
|
2299
|
+
const signData = raw.sign_data;
|
|
2300
|
+
if (signData?.signature_scheme !== "eip712_delegation" || !signData.typed_data) {
|
|
2301
|
+
throw new HavenApiError(
|
|
2302
|
+
`x402/authorize did not return an erc7710 settlement child (signature_scheme was ${JSON.stringify(signData?.signature_scheme)}). Refusing to sign a payload this path did not ask for.`,
|
|
2303
|
+
500,
|
|
2304
|
+
raw
|
|
2305
|
+
);
|
|
2306
|
+
}
|
|
2307
|
+
return {
|
|
2308
|
+
paymentId: raw.payment_id,
|
|
2309
|
+
signData,
|
|
2310
|
+
settlement: {
|
|
2311
|
+
paymentId: raw.payment_id,
|
|
2312
|
+
merchantPayTo,
|
|
2313
|
+
amountAtomic,
|
|
2314
|
+
asset: option.asset,
|
|
2315
|
+
network: option.network,
|
|
2316
|
+
facilitatorAddresses: selection.facilitatorAddresses
|
|
2317
|
+
}
|
|
2318
|
+
};
|
|
2319
|
+
}
|
|
2320
|
+
/**
|
|
2321
|
+
* The SETTLE half (#1456): exchange the signed child for the merchant header.
|
|
2322
|
+
*
|
|
2323
|
+
* The SDK builds no header on this path — the backend assembles the MetaMask
|
|
2324
|
+
* erc7710 payload in `assembleSettlementPayload`. Whoever produced the
|
|
2325
|
+
* signature (an in-process delegate key, or the local edge signer over the
|
|
2326
|
+
* hosted boundary) is irrelevant here.
|
|
2327
|
+
*/
|
|
2328
|
+
async submit(paymentId, signature) {
|
|
2329
|
+
const settled = await this.post(
|
|
2330
|
+
`/x402/${paymentId}/settle`,
|
|
2331
|
+
{ signature }
|
|
2332
|
+
);
|
|
2333
|
+
if (!settled.payment_header) {
|
|
2334
|
+
throw new HavenApiError(
|
|
2335
|
+
"x402 settle returned no payment_header \u2014 the merchant cannot be retried.",
|
|
2336
|
+
500,
|
|
2337
|
+
settled
|
|
2338
|
+
);
|
|
2339
|
+
}
|
|
2340
|
+
return settled.payment_header;
|
|
2341
|
+
}
|
|
2342
|
+
};
|
|
2343
|
+
|
|
2344
|
+
// src/tool-adapter.ts
|
|
2345
|
+
function toolX402PaymentRequired(input) {
|
|
2346
|
+
return {
|
|
2347
|
+
x402Version: 2,
|
|
2348
|
+
resource: { url: input.url, description: input.description },
|
|
2349
|
+
accepts: [
|
|
2350
|
+
{
|
|
2351
|
+
scheme: "exact",
|
|
2352
|
+
network: input.network,
|
|
2353
|
+
amount: input.amount,
|
|
2354
|
+
asset: input.asset,
|
|
2355
|
+
payTo: input.payTo,
|
|
2356
|
+
maxTimeoutSeconds: 30
|
|
2357
|
+
}
|
|
2358
|
+
]
|
|
2359
|
+
};
|
|
2360
|
+
}
|
|
2361
|
+
function x402ToolReceipt(receipt) {
|
|
2362
|
+
return {
|
|
2363
|
+
success: true,
|
|
2364
|
+
payment_id: receipt.paymentId,
|
|
2365
|
+
tx_hash: receipt.txHash,
|
|
2366
|
+
token: receipt.token,
|
|
2367
|
+
amount: receipt.amount,
|
|
2368
|
+
to: receipt.to,
|
|
2369
|
+
resource_url: receipt.resourceUrl,
|
|
2370
|
+
explorer_url: receipt.explorerUrl,
|
|
2371
|
+
payment_header: receipt.paymentHeader,
|
|
2372
|
+
merchant_to: receipt.merchantTo,
|
|
2373
|
+
payer: receipt.payer,
|
|
2374
|
+
chain_id: receipt.chainId,
|
|
2375
|
+
haven: receipt.haven,
|
|
2376
|
+
merchant: receipt.merchant,
|
|
2377
|
+
x402: receipt.x402
|
|
2378
|
+
};
|
|
2379
|
+
}
|
|
2380
|
+
function toolError(err) {
|
|
2381
|
+
if (err instanceof HavenPaymentStateError) {
|
|
2382
|
+
return {
|
|
2383
|
+
success: false,
|
|
2384
|
+
payment_id: err.state.paymentId,
|
|
2385
|
+
kind: err.state.kind,
|
|
2386
|
+
rail: err.state.rail,
|
|
2387
|
+
status: err.state.status,
|
|
2388
|
+
phase: err.state.phase,
|
|
2389
|
+
next_action: err.state.nextAction,
|
|
2390
|
+
tx_hash: err.state.txHash,
|
|
2391
|
+
token: err.state.token,
|
|
2392
|
+
amount: err.state.amount,
|
|
2393
|
+
resource_url: err.state.resourceUrl,
|
|
2394
|
+
merchant_address: err.state.merchantAddress,
|
|
2395
|
+
amount_atomic: err.state.amountAtomic,
|
|
2396
|
+
asset: err.state.asset,
|
|
2397
|
+
network: err.state.network,
|
|
2398
|
+
description: err.state.description,
|
|
2399
|
+
idempotency_key: err.state.idempotencyKey,
|
|
2400
|
+
x402: err.state.x402 ? {
|
|
2401
|
+
amount_atomic: err.state.x402.amountAtomic,
|
|
2402
|
+
asset: err.state.x402.asset,
|
|
2403
|
+
network: err.state.x402.network,
|
|
2404
|
+
resource_url: err.state.x402.resourceUrl,
|
|
2405
|
+
merchant_address: err.state.x402.merchantAddress,
|
|
2406
|
+
description: err.state.x402.description,
|
|
2407
|
+
idempotency_key: err.state.x402.idempotencyKey
|
|
2408
|
+
} : void 0,
|
|
2409
|
+
mpp: err.state.mpp ? {
|
|
2410
|
+
amount_atomic: err.state.mpp.amountAtomic,
|
|
2411
|
+
asset: err.state.mpp.asset,
|
|
2412
|
+
network: err.state.mpp.network,
|
|
2413
|
+
resource_url: err.state.mpp.resourceUrl,
|
|
2414
|
+
merchant_address: err.state.mpp.merchantAddress,
|
|
2415
|
+
description: err.state.mpp.description,
|
|
2416
|
+
idempotency_key: err.state.mpp.idempotencyKey,
|
|
2417
|
+
challenge_id: err.state.mpp.challengeId
|
|
2418
|
+
} : void 0,
|
|
2419
|
+
resume_state: err.resumeState,
|
|
2420
|
+
expires_at: err.state.expiresAt,
|
|
2421
|
+
chain_id: err.state.chainId,
|
|
2422
|
+
message: err.state.message,
|
|
2423
|
+
error: err.message
|
|
2424
|
+
};
|
|
2425
|
+
}
|
|
2426
|
+
if (err instanceof HavenApiError) {
|
|
2427
|
+
return {
|
|
2428
|
+
success: false,
|
|
2429
|
+
status_code: err.statusCode,
|
|
2430
|
+
error: err.message,
|
|
2431
|
+
body: err.body
|
|
2432
|
+
};
|
|
2433
|
+
}
|
|
2434
|
+
return {
|
|
2435
|
+
success: false,
|
|
2436
|
+
error: err instanceof Error ? err.message : String(err)
|
|
2437
|
+
};
|
|
2438
|
+
}
|
|
2439
|
+
|
|
2440
|
+
// src/merchant-completion.ts
|
|
2441
|
+
var MERCHANT_BODY_SNIPPET_LIMIT = 1e3;
|
|
2442
|
+
var MerchantCompletion = class {
|
|
2443
|
+
post;
|
|
2444
|
+
merchantTransport;
|
|
2445
|
+
getPaymentStatus;
|
|
2446
|
+
getAgent;
|
|
2447
|
+
delegateAddress;
|
|
2448
|
+
x402Wallet;
|
|
2449
|
+
constructor(options) {
|
|
2450
|
+
this.post = options.post;
|
|
2451
|
+
this.merchantTransport = options.merchantTransport;
|
|
2452
|
+
this.getPaymentStatus = options.getPaymentStatus;
|
|
2453
|
+
this.getAgent = options.getAgent;
|
|
2454
|
+
this.delegateAddress = options.delegateAddress;
|
|
2455
|
+
this.x402Wallet = options.x402Wallet;
|
|
2456
|
+
}
|
|
2457
|
+
async retryRequest(url, initialInit, paymentRequired, receipt) {
|
|
2458
|
+
if (!receipt.accepted) {
|
|
2459
|
+
throw new HavenApiError("No accepted x402 option was recorded for payment retry", 500);
|
|
2460
|
+
}
|
|
2461
|
+
if (!receipt.paymentHeader) {
|
|
2462
|
+
throw new HavenApiError("No x402 payment header was returned for payment retry", 500);
|
|
2463
|
+
}
|
|
2464
|
+
const retryResponse = await this.merchantTransport.deliverPayment(
|
|
2465
|
+
url,
|
|
2466
|
+
initialInit,
|
|
2467
|
+
receipt.paymentHeader
|
|
2468
|
+
);
|
|
2469
|
+
if (!retryResponse.ok) {
|
|
2470
|
+
const merchant = await captureMerchantResponse(retryResponse);
|
|
2471
|
+
await this.recordRetryRejected({
|
|
2472
|
+
rail: "x402",
|
|
2473
|
+
paymentId: receipt.paymentId,
|
|
2474
|
+
txHash: receipt.txHash,
|
|
2475
|
+
resourceUrl: receipt.resourceUrl,
|
|
2476
|
+
merchant,
|
|
2477
|
+
details: {
|
|
2478
|
+
merchant_to: receipt.merchantTo,
|
|
2479
|
+
delegate_to: receipt.to
|
|
2480
|
+
}
|
|
2481
|
+
});
|
|
2482
|
+
throw new HavenApiError(
|
|
2483
|
+
"x402 retry failed after Haven funded the delegate wallet; reconciliation may be required.",
|
|
2484
|
+
merchant.merchant_status,
|
|
2485
|
+
{
|
|
2486
|
+
marker: "x402_retry_rejected_after_funding",
|
|
2487
|
+
payment_id: receipt.paymentId,
|
|
2488
|
+
tx_hash: receipt.txHash,
|
|
2489
|
+
resource_url: receipt.resourceUrl,
|
|
2490
|
+
merchant_to: receipt.merchantTo,
|
|
2491
|
+
delegate_to: receipt.to,
|
|
2492
|
+
...merchant
|
|
2493
|
+
}
|
|
2494
|
+
);
|
|
2495
|
+
}
|
|
2496
|
+
const merchantSettlement = parseMerchantSettlement(retryResponse.headers.get("PAYMENT-RESPONSE"));
|
|
2497
|
+
if (receipt.merchant && merchantSettlement.settlementTxHash) {
|
|
2498
|
+
receipt.merchant.settlementTxHash = merchantSettlement.settlementTxHash;
|
|
2499
|
+
receipt.merchant.settlementExplorerUrl = buildExplorerUrl(
|
|
2500
|
+
receipt.chainId,
|
|
2501
|
+
merchantSettlement.settlementTxHash
|
|
2502
|
+
);
|
|
2503
|
+
}
|
|
2504
|
+
await this.reportEvidence({
|
|
2505
|
+
paymentId: receipt.paymentId,
|
|
2506
|
+
rail: "x402",
|
|
2507
|
+
txHash: receipt.txHash,
|
|
2508
|
+
resourceUrl: receipt.resourceUrl,
|
|
2509
|
+
merchantStatus: retryResponse.status,
|
|
2510
|
+
challengePayload: paymentRequired,
|
|
2511
|
+
selectedPayment: receipt.accepted,
|
|
2512
|
+
paymentProofHeaderName: "X-PAYMENT",
|
|
2513
|
+
paymentProofHeader: receipt.paymentHeader,
|
|
2514
|
+
protocolReceiptHeaderName: "PAYMENT-RESPONSE",
|
|
2515
|
+
protocolReceiptHeader: retryResponse.headers.get("PAYMENT-RESPONSE") ?? void 0
|
|
2516
|
+
});
|
|
2517
|
+
await this.reportMerchantReceipt(receipt.paymentId, retryResponse);
|
|
2518
|
+
return retryResponse;
|
|
2519
|
+
}
|
|
2520
|
+
/**
|
|
2521
|
+
* #956: capture the merchant's OWN receipt when the paid response carries
|
|
2522
|
+
* one, and report it to Haven so the reporting feed can attach it next to
|
|
2523
|
+
* the Haven-generated payment evidence (#498). Two supported signals on the
|
|
2524
|
+
* paid response:
|
|
2525
|
+
*
|
|
2526
|
+
* x-receipt-json: base64-encoded JSON receipt document (inline)
|
|
2527
|
+
* x-receipt-url: https URL to the receipt document (reference)
|
|
2528
|
+
*
|
|
2529
|
+
* Strictly best-effort: absence is the normal case, and no failure here may
|
|
2530
|
+
* ever affect the completed payment — the response is already paid for.
|
|
2531
|
+
*/
|
|
2532
|
+
async reportMerchantReceipt(paymentId, response) {
|
|
2533
|
+
try {
|
|
2534
|
+
const inlineB64 = response.headers.get("x-receipt-json");
|
|
2535
|
+
const url = response.headers.get("x-receipt-url");
|
|
2536
|
+
if (!inlineB64 && !url) return;
|
|
2537
|
+
let body = null;
|
|
2538
|
+
if (inlineB64) {
|
|
2539
|
+
if (inlineB64.length > Math.ceil(64 * 1024 * 4 / 3)) return;
|
|
2540
|
+
const decoded = JSON.parse(Buffer.from(inlineB64, "base64").toString("utf8"));
|
|
2541
|
+
if (decoded && typeof decoded === "object") body = { json: decoded };
|
|
2542
|
+
} else if (url && url.startsWith("https://") && url.length <= 2048) {
|
|
2543
|
+
body = { url };
|
|
2544
|
+
}
|
|
2545
|
+
if (!body) return;
|
|
2546
|
+
await this.post(`/machine-payments/${paymentId}/merchant-receipt`, body);
|
|
2547
|
+
} catch {
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
async resolveCompletionContext(input) {
|
|
2551
|
+
const status = await this.getPaymentStatus(input.paymentId);
|
|
2552
|
+
if (status.rail !== "x402") {
|
|
2553
|
+
throw new HavenPaymentStateError(
|
|
2554
|
+
`Payment ${status.paymentId} is ${status.rail}, not x402.`,
|
|
2555
|
+
409,
|
|
2556
|
+
status
|
|
2557
|
+
);
|
|
2558
|
+
}
|
|
2559
|
+
const readyForMerchantCompletion = input.noFundingLeg ? status.kind === "payment_intent" && status.status === "submitted" : status.nextAction === AgentPaymentNextAction.RetryOriginalX402Request || status.kind === "payment_intent" && status.status === "confirmed" && status.phase === AgentPaymentPhase.PaymentConfirmed && status.nextAction === AgentPaymentNextAction.None;
|
|
2560
|
+
if (!readyForMerchantCompletion) {
|
|
2561
|
+
throw new HavenPaymentStateError(status.message, paymentStateStatusCode(status.status, 409), status);
|
|
2562
|
+
}
|
|
2563
|
+
if (!input.noFundingLeg && !status.txHash) {
|
|
2564
|
+
throw new HavenApiError(
|
|
2565
|
+
`x402 payment ${status.paymentId} is ready for merchant completion but has no Haven transaction hash.`,
|
|
2566
|
+
502,
|
|
2567
|
+
status,
|
|
2568
|
+
status.paymentId
|
|
2569
|
+
);
|
|
2570
|
+
}
|
|
2571
|
+
const approvedResourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null;
|
|
2572
|
+
if (approvedResourceUrl && approvedResourceUrl !== input.url) {
|
|
2573
|
+
throw new HavenApiError(
|
|
2574
|
+
"x402 merchant completion does not match the approved resource URL.",
|
|
2575
|
+
409,
|
|
2576
|
+
{ status, url: input.url },
|
|
2577
|
+
status.paymentId
|
|
2578
|
+
);
|
|
2579
|
+
}
|
|
2580
|
+
return {
|
|
2581
|
+
paymentId: status.paymentId,
|
|
2582
|
+
txHash: status.txHash,
|
|
2583
|
+
resourceUrl: approvedResourceUrl ?? input.url,
|
|
2584
|
+
merchantAddress: status.merchantAddress ?? status.x402?.merchantAddress ?? null
|
|
2585
|
+
};
|
|
2586
|
+
}
|
|
2587
|
+
async resolveWalletForMerchantCall() {
|
|
2588
|
+
const localWallet = x402PayerAddress(this.delegateAddress, this.x402Wallet);
|
|
2589
|
+
if (localWallet) return localWallet;
|
|
2590
|
+
try {
|
|
2591
|
+
const agent = await this.getAgent();
|
|
2592
|
+
return agent.delegateAddress ?? void 0;
|
|
2593
|
+
} catch {
|
|
2594
|
+
return void 0;
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
// #1328: authorizeMachinePayment / authorizeMppDemoPayment / resumeAuthorizedMpp
|
|
2598
|
+
// / resumeMppPayment / fetchWithMachinePayment / retryMppRequest (the
|
|
2599
|
+
// MACHINE-PAYMENT-CHALLENGE / mpp_demo client surface) are retired — the
|
|
2600
|
+
// backend's POST /machine-payments/authorize refuses unconditionally now,
|
|
2601
|
+
// and MACHINE-PAYMENT-CHALLENGE was never produced by any other Haven
|
|
2602
|
+
// surface. Use the x402 flow (authorizeX402 / fetch / quoteX402 / payX402Quote)
|
|
2603
|
+
// for agent-to-merchant payments.
|
|
2604
|
+
async recordRetryRejected(input) {
|
|
2605
|
+
try {
|
|
2606
|
+
await this.post("/machine-payments/reconciliation-events", {
|
|
2607
|
+
paymentId: input.paymentId,
|
|
2608
|
+
rail: input.rail,
|
|
2609
|
+
eventType: "merchant_retry_rejected_after_payment",
|
|
2610
|
+
txHash: input.txHash,
|
|
2611
|
+
reason: `Merchant returned HTTP ${input.merchant.merchant_status} after Haven payment confirmation`,
|
|
2612
|
+
details: {
|
|
2613
|
+
resource_url: input.resourceUrl,
|
|
2614
|
+
retry_status: input.merchant.merchant_status,
|
|
2615
|
+
retry_body: input.merchant.merchant_body.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,
|
|
2616
|
+
...input.details
|
|
2617
|
+
}
|
|
2618
|
+
});
|
|
2619
|
+
} catch {
|
|
2620
|
+
}
|
|
2621
|
+
}
|
|
2622
|
+
async reportEvidence(input) {
|
|
2623
|
+
try {
|
|
2624
|
+
await this.post("/machine-payments/evidence", {
|
|
2625
|
+
paymentId: input.paymentId,
|
|
2626
|
+
rail: input.rail,
|
|
2627
|
+
txHash: input.txHash,
|
|
2628
|
+
resourceUrl: input.resourceUrl,
|
|
2629
|
+
merchantStatus: input.merchantStatus,
|
|
2630
|
+
challengePayload: input.challengePayload,
|
|
2631
|
+
selectedPayment: input.selectedPayment,
|
|
2632
|
+
paymentProofHeaderName: input.paymentProofHeaderName,
|
|
2633
|
+
paymentProofHeader: input.paymentProofHeader,
|
|
2634
|
+
protocolReceiptHeaderName: input.protocolReceiptHeaderName,
|
|
2635
|
+
protocolReceiptHeader: input.protocolReceiptHeader,
|
|
2636
|
+
protocolReceiptPayload: input.protocolReceiptHeader ? parseProtocolReceiptHeader(input.protocolReceiptHeader) : void 0
|
|
2637
|
+
});
|
|
2638
|
+
} catch {
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
};
|
|
2642
|
+
function parseMerchantSettlement(header) {
|
|
2643
|
+
if (!header) return {};
|
|
2644
|
+
const parsed = parseProtocolReceiptHeader(header);
|
|
2645
|
+
const tx = typeof parsed?.transaction === "string" ? parsed.transaction : typeof parsed?.txHash === "string" ? parsed.txHash : typeof parsed?.tx_hash === "string" ? parsed.tx_hash : null;
|
|
2646
|
+
return { settlementTxHash: tx };
|
|
2647
|
+
}
|
|
2648
|
+
function parseProtocolReceiptHeader(value) {
|
|
2649
|
+
try {
|
|
2650
|
+
return decodeBase64Json(value);
|
|
2651
|
+
} catch {
|
|
2652
|
+
try {
|
|
2653
|
+
return JSON.parse(value);
|
|
2654
|
+
} catch {
|
|
2655
|
+
return void 0;
|
|
1134
2656
|
}
|
|
1135
2657
|
}
|
|
1136
|
-
flush();
|
|
1137
|
-
return messages;
|
|
1138
|
-
}
|
|
1139
|
-
function selectJsonRpcResult(messages) {
|
|
1140
|
-
return messages.find((m) => "result" in m || "error" in m) ?? messages[messages.length - 1];
|
|
1141
2658
|
}
|
|
2659
|
+
|
|
2660
|
+
// src/client.ts
|
|
2661
|
+
var DEFAULT_POLLING_INTERVAL = 3e3;
|
|
1142
2662
|
function x402TypedDataDigest(typedData) {
|
|
1143
2663
|
if (!typedData || typeof typedData !== "object") return void 0;
|
|
1144
2664
|
try {
|
|
@@ -1169,48 +2689,78 @@ function mapCatalogEntry(entry) {
|
|
|
1169
2689
|
};
|
|
1170
2690
|
}
|
|
1171
2691
|
var HavenClient = class {
|
|
1172
|
-
apiKey;
|
|
1173
2692
|
delegateKey;
|
|
1174
|
-
|
|
2693
|
+
havenApi;
|
|
2694
|
+
accountReads;
|
|
2695
|
+
delegateSweep;
|
|
1175
2696
|
x402Wallet;
|
|
1176
|
-
|
|
1177
|
-
merchantTimeout;
|
|
2697
|
+
merchantTransport;
|
|
1178
2698
|
confirmationTimeout;
|
|
1179
2699
|
pollingInterval;
|
|
1180
2700
|
chainRpcs;
|
|
1181
2701
|
inFlightX402 = /* @__PURE__ */ new Map();
|
|
1182
|
-
x402ReceiptCache = /* @__PURE__ */ new Map();
|
|
1183
2702
|
/**
|
|
1184
|
-
*
|
|
1185
|
-
*
|
|
1186
|
-
* scoping so concurrent requests don't race on shared mutable state.
|
|
2703
|
+
* The EIP-3009 funding-leg lifecycle (#1618). The facade holds a reference
|
|
2704
|
+
* and delegates; it does not reimplement any of it.
|
|
1187
2705
|
*/
|
|
1188
|
-
|
|
2706
|
+
fundingLeg;
|
|
1189
2707
|
/**
|
|
1190
|
-
*
|
|
1191
|
-
*
|
|
1192
|
-
* overlapping async work — like two MCP tool dispatches in flight at
|
|
1193
|
-
* the same time — see their own headers without stepping on each other.
|
|
2708
|
+
* The erc7710 direct-settlement lifecycle (#1619). Separate from the funding
|
|
2709
|
+
* leg on purpose: this scheme has no funding leg to share.
|
|
1194
2710
|
*/
|
|
1195
|
-
|
|
1196
|
-
/**
|
|
1197
|
-
|
|
2711
|
+
erc7710;
|
|
2712
|
+
/**
|
|
2713
|
+
* Merchant delivery and the evidence trail behind it (#1620). Scheme-neutral
|
|
2714
|
+
* on purpose — both settlement schemes finish through the same door.
|
|
2715
|
+
*/
|
|
2716
|
+
merchantCompletion;
|
|
1198
2717
|
/** Delegate address derived from the private key (if provided) */
|
|
1199
2718
|
delegateAddress;
|
|
1200
2719
|
constructor(config) {
|
|
1201
|
-
this.apiKey = config.apiKey;
|
|
1202
2720
|
this.delegateKey = config.delegateKey;
|
|
1203
|
-
this.
|
|
2721
|
+
this.havenApi = new HavenApiTransport(config);
|
|
2722
|
+
this.accountReads = new AccountReads({
|
|
2723
|
+
transport: this.havenApi,
|
|
2724
|
+
getPaymentStatus: (paymentId) => this.getPaymentStatus(paymentId)
|
|
2725
|
+
});
|
|
2726
|
+
this.delegateSweep = new DelegateSweepApi({
|
|
2727
|
+
transport: this.havenApi,
|
|
2728
|
+
delegateKey: config.delegateKey,
|
|
2729
|
+
chainRpcs: config.chainRpcs ?? {},
|
|
2730
|
+
getAgent: () => this.getAgent(),
|
|
2731
|
+
buildExplorerUrl: (chainId, hash) => buildExplorerUrl(chainId, hash)
|
|
2732
|
+
});
|
|
1204
2733
|
this.x402Wallet = config.x402Wallet;
|
|
1205
|
-
this.
|
|
1206
|
-
this.
|
|
1207
|
-
this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT;
|
|
2734
|
+
this.merchantTransport = new McpMerchantTransport({ merchantTimeout: config.merchantTimeout });
|
|
2735
|
+
this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT_MS;
|
|
1208
2736
|
this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL;
|
|
1209
2737
|
this.chainRpcs = config.chainRpcs ?? {};
|
|
1210
|
-
this.defaultHeaders = { ...config.defaultHeaders ?? {} };
|
|
1211
2738
|
if (this.delegateKey) {
|
|
1212
2739
|
this.delegateAddress = addressFromKey(this.delegateKey);
|
|
1213
2740
|
}
|
|
2741
|
+
this.fundingLeg = new X402FundingLeg({
|
|
2742
|
+
delegateKey: this.delegateKey,
|
|
2743
|
+
delegateAddress: this.delegateAddress,
|
|
2744
|
+
x402Wallet: this.x402Wallet,
|
|
2745
|
+
chainRpcs: this.chainRpcs,
|
|
2746
|
+
post: (path, body) => this.post(path, body),
|
|
2747
|
+
signForData: (signData) => this.signForData(signData),
|
|
2748
|
+
assertSignableAuthorizationState: (label, raw) => this.throwIfNonSignableAuthorizationState(label, raw)
|
|
2749
|
+
});
|
|
2750
|
+
this.merchantCompletion = new MerchantCompletion({
|
|
2751
|
+
post: (path, body) => this.post(path, body),
|
|
2752
|
+
merchantTransport: this.merchantTransport,
|
|
2753
|
+
getPaymentStatus: (paymentId) => this.getPaymentStatus(paymentId),
|
|
2754
|
+
getAgent: () => this.getAgent(),
|
|
2755
|
+
delegateAddress: this.delegateAddress,
|
|
2756
|
+
x402Wallet: this.x402Wallet
|
|
2757
|
+
});
|
|
2758
|
+
this.erc7710 = new X402Erc7710({
|
|
2759
|
+
delegateKey: this.delegateKey,
|
|
2760
|
+
post: (path, body) => this.post(path, body),
|
|
2761
|
+
signForData: (signData) => this.signForData(signData),
|
|
2762
|
+
getAgent: () => this.getAgent()
|
|
2763
|
+
});
|
|
1214
2764
|
}
|
|
1215
2765
|
/**
|
|
1216
2766
|
* Run `fn` with extra Haven-API headers scoped to the async work it
|
|
@@ -1228,7 +2778,7 @@ var HavenClient = class {
|
|
|
1228
2778
|
* context.
|
|
1229
2779
|
*/
|
|
1230
2780
|
withRequestContext(headers, fn) {
|
|
1231
|
-
return this.
|
|
2781
|
+
return this.havenApi.withRequestContext(headers, fn);
|
|
1232
2782
|
}
|
|
1233
2783
|
// ── High-Level API ───────────────────────────────────────────────
|
|
1234
2784
|
/**
|
|
@@ -1264,7 +2814,7 @@ var HavenClient = class {
|
|
|
1264
2814
|
...request.idempotencyKey ? { idempotency_key: request.idempotencyKey } : {}
|
|
1265
2815
|
});
|
|
1266
2816
|
if (raw.status === "pending_approval") {
|
|
1267
|
-
|
|
2817
|
+
throwPaymentStateError("Payment", raw);
|
|
1268
2818
|
}
|
|
1269
2819
|
return {
|
|
1270
2820
|
paymentId: raw.payment_id,
|
|
@@ -1327,7 +2877,7 @@ var HavenClient = class {
|
|
|
1327
2877
|
...new TextEncoder().encode(JSON.stringify(paymentRequired)).length <= 65536 ? { paymentRequired } : {}
|
|
1328
2878
|
});
|
|
1329
2879
|
if (raw.status !== "pending_signature") {
|
|
1330
|
-
|
|
2880
|
+
throwPaymentStateError("x402 payment", raw);
|
|
1331
2881
|
}
|
|
1332
2882
|
if (!raw.sign_data?.hash) {
|
|
1333
2883
|
throw new HavenApiError("No sign_hash returned from x402/authorize", 500, raw);
|
|
@@ -1353,6 +2903,8 @@ var HavenClient = class {
|
|
|
1353
2903
|
asset: option.asset,
|
|
1354
2904
|
network: option.network,
|
|
1355
2905
|
expectedAuth: raw.x402_expected_auth,
|
|
2906
|
+
payerDelegate: raw.payer_delegate,
|
|
2907
|
+
payerAgentId: raw.payer_agent_id,
|
|
1356
2908
|
// #1138: the digest the delegation-rail expected context commits to.
|
|
1357
2909
|
// Re-derived locally, exactly like every other context field the edge
|
|
1358
2910
|
// signer is handed (amount, merchantTo, …) — none of them are trusted
|
|
@@ -1448,7 +3000,7 @@ var HavenClient = class {
|
|
|
1448
3000
|
*/
|
|
1449
3001
|
async getPayment(paymentId) {
|
|
1450
3002
|
const raw = await this.get(`/payments/${paymentId}`);
|
|
1451
|
-
return
|
|
3003
|
+
return mapPaymentResult(raw, buildExplorerUrl);
|
|
1452
3004
|
}
|
|
1453
3005
|
/**
|
|
1454
3006
|
* Get agent-actionable status for a payment intent or approval request.
|
|
@@ -1458,37 +3010,13 @@ var HavenClient = class {
|
|
|
1458
3010
|
*/
|
|
1459
3011
|
async getPaymentStatus(paymentId) {
|
|
1460
3012
|
const raw = await this.get(`/machine-payments/${paymentId}/status`);
|
|
1461
|
-
return
|
|
3013
|
+
return mapPaymentStatusResult(raw);
|
|
1462
3014
|
}
|
|
1463
3015
|
/**
|
|
1464
3016
|
* Get the agent identity tied to this API key.
|
|
1465
3017
|
*/
|
|
1466
3018
|
async getAgent() {
|
|
1467
|
-
|
|
1468
|
-
const request = this.fetchAgent();
|
|
1469
|
-
this.agentInFlight = request;
|
|
1470
|
-
request.finally(() => {
|
|
1471
|
-
this.agentInFlight = null;
|
|
1472
|
-
}).catch(() => {
|
|
1473
|
-
});
|
|
1474
|
-
return request;
|
|
1475
|
-
}
|
|
1476
|
-
agentInFlight = null;
|
|
1477
|
-
async fetchAgent() {
|
|
1478
|
-
const raw = await this.get("/machine-payments/agent");
|
|
1479
|
-
return {
|
|
1480
|
-
id: raw.id,
|
|
1481
|
-
name: raw.name,
|
|
1482
|
-
status: raw.status,
|
|
1483
|
-
safeAddress: raw.safe_address,
|
|
1484
|
-
delegateAddress: raw.delegate_address,
|
|
1485
|
-
chainId: raw.chain_id,
|
|
1486
|
-
// Defensive normalization, not trust: the backend contract is exactly
|
|
1487
|
-
// 'legacy' | 'delegation' (#1306), but an older/mismatched backend
|
|
1488
|
-
// during a rollout window should degrade to the wider legacy bucket
|
|
1489
|
-
// rather than propagate an unrecognized string.
|
|
1490
|
-
executionRail: raw.execution_rail === "delegation" ? "delegation" : "legacy"
|
|
1491
|
-
};
|
|
3019
|
+
return this.accountReads.getAgent();
|
|
1492
3020
|
}
|
|
1493
3021
|
/**
|
|
1494
3022
|
* One-shot "am I ready?" bootstrap: identity + live spend authority + a
|
|
@@ -1498,24 +3026,7 @@ var HavenClient = class {
|
|
|
1498
3026
|
* without two round trips and manual assembly.
|
|
1499
3027
|
*/
|
|
1500
3028
|
async getAgentSummary() {
|
|
1501
|
-
|
|
1502
|
-
this.getAgent(),
|
|
1503
|
-
this.getAllowances()
|
|
1504
|
-
]);
|
|
1505
|
-
const allowances = allowanceSummary.allowances.map((a) => {
|
|
1506
|
-
const token = resolveTokenFromAddress(a.tokenAddress);
|
|
1507
|
-
const remainingDisplay = token ? `${formatAtomicAmount(safeBigInt(a.onchain.remaining), token.decimals)} ${a.tokenSymbol}` : `${a.onchain.remaining} ${a.tokenSymbol} (atomic; unknown decimals)`;
|
|
1508
|
-
return {
|
|
1509
|
-
tokenSymbol: a.tokenSymbol,
|
|
1510
|
-
remainingAtomic: a.onchain.remaining,
|
|
1511
|
-
remainingDisplay,
|
|
1512
|
-
configuredAmount: a.configuredAmount,
|
|
1513
|
-
resetPeriodMin: a.resetPeriodMin,
|
|
1514
|
-
isResetPending: a.onchain.isResetPending
|
|
1515
|
-
};
|
|
1516
|
-
});
|
|
1517
|
-
const readiness = deriveReadiness(agent.status, allowances);
|
|
1518
|
-
return { ...agent, readiness, spend_authority_readiness: readiness, allowances };
|
|
3029
|
+
return this.accountReads.getAgentSummary();
|
|
1519
3030
|
}
|
|
1520
3031
|
/**
|
|
1521
3032
|
* Sweep stranded USDC and ETH from the delegate EOA back to the originating Safe.
|
|
@@ -1527,68 +3038,7 @@ var HavenClient = class {
|
|
|
1527
3038
|
* Requires `chainRpcs` to be set for the agent's chain in `HavenClientConfig`.
|
|
1528
3039
|
*/
|
|
1529
3040
|
async sweepDelegate() {
|
|
1530
|
-
|
|
1531
|
-
throw new HavenSigningError("delegateKey is required for sweepDelegate.");
|
|
1532
|
-
}
|
|
1533
|
-
const agent = await this.getAgent();
|
|
1534
|
-
const { safeAddress, delegateAddress, chainId } = agent;
|
|
1535
|
-
if (!delegateAddress) {
|
|
1536
|
-
throw new HavenApiError("Agent has no delegate address.", 422);
|
|
1537
|
-
}
|
|
1538
|
-
const rpcUrl = this.chainRpcs[chainId];
|
|
1539
|
-
if (!rpcUrl) {
|
|
1540
|
-
throw new HavenApiError(
|
|
1541
|
-
`chainRpcs[${chainId}] must be configured to sweep the delegate wallet.`,
|
|
1542
|
-
422
|
|
1543
|
-
);
|
|
1544
|
-
}
|
|
1545
|
-
const provider = createJsonRpcProvider(rpcUrl);
|
|
1546
|
-
const wallet = createWallet(this.delegateKey, provider);
|
|
1547
|
-
const ERC20_TRANSFER_ABI = ["function balanceOf(address) view returns (uint256)", "function transfer(address to, uint256 amount) returns (bool)"];
|
|
1548
|
-
const transfers = [];
|
|
1549
|
-
const usdcAddress = CHAIN_USDC[chainId];
|
|
1550
|
-
if (usdcAddress) {
|
|
1551
|
-
const usdcContract = createErc20Contract(usdcAddress, ERC20_TRANSFER_ABI, wallet);
|
|
1552
|
-
const usdcBalance = await usdcContract.balanceOf(delegateAddress);
|
|
1553
|
-
if (usdcBalance > 0n) {
|
|
1554
|
-
const tx = await usdcContract.transfer(safeAddress, usdcBalance);
|
|
1555
|
-
const receipt = await tx.wait(1);
|
|
1556
|
-
const txHash = receipt?.hash ?? tx.hash;
|
|
1557
|
-
transfers.push({
|
|
1558
|
-
asset: "USDC",
|
|
1559
|
-
amount: formatAtomicAmount(usdcBalance, 6),
|
|
1560
|
-
amountAtomic: usdcBalance.toString(),
|
|
1561
|
-
txHash,
|
|
1562
|
-
explorerUrl: buildExplorerUrl(chainId, txHash)
|
|
1563
|
-
});
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
const ethBalance = await provider.getBalance(delegateAddress);
|
|
1567
|
-
if (ethBalance > 0n) {
|
|
1568
|
-
const fee = await provider.getFeeData();
|
|
1569
|
-
const effectiveGasPrice = fee.maxFeePerGas ?? fee.gasPrice ?? 1000000n;
|
|
1570
|
-
const gasLimit = 21000n;
|
|
1571
|
-
const gasCost = effectiveGasPrice * gasLimit * 2n;
|
|
1572
|
-
const ethToSend = ethBalance > gasCost ? ethBalance - gasCost : 0n;
|
|
1573
|
-
if (ethToSend > 0n) {
|
|
1574
|
-
const tx = await wallet.sendTransaction({ to: safeAddress, value: ethToSend });
|
|
1575
|
-
const receipt = await tx.wait(1);
|
|
1576
|
-
const txHash = receipt?.hash ?? tx.hash;
|
|
1577
|
-
transfers.push({
|
|
1578
|
-
asset: "ETH",
|
|
1579
|
-
amount: formatAtomicAmount(ethToSend, 18),
|
|
1580
|
-
amountAtomic: ethToSend.toString(),
|
|
1581
|
-
txHash,
|
|
1582
|
-
explorerUrl: buildExplorerUrl(chainId, txHash)
|
|
1583
|
-
});
|
|
1584
|
-
}
|
|
1585
|
-
}
|
|
1586
|
-
return {
|
|
1587
|
-
fromAddress: delegateAddress,
|
|
1588
|
-
toAddress: safeAddress,
|
|
1589
|
-
chainId,
|
|
1590
|
-
transfers
|
|
1591
|
-
};
|
|
3041
|
+
return this.delegateSweep.sweepDelegate();
|
|
1592
3042
|
}
|
|
1593
3043
|
/**
|
|
1594
3044
|
* Hosted (keyless) split-signer sweep — step 1 of 2.
|
|
@@ -1599,7 +3049,7 @@ var HavenClient = class {
|
|
|
1599
3049
|
* edge signer's `haven_sign_sweep_delegate`. No key is required on this client.
|
|
1600
3050
|
*/
|
|
1601
3051
|
async prepareSweep() {
|
|
1602
|
-
return this.
|
|
3052
|
+
return this.delegateSweep.prepareSweep();
|
|
1603
3053
|
}
|
|
1604
3054
|
/**
|
|
1605
3055
|
* Hosted (keyless) split-signer sweep — step 2 of 2.
|
|
@@ -1609,40 +3059,13 @@ var HavenClient = class {
|
|
|
1609
3059
|
* the key.
|
|
1610
3060
|
*/
|
|
1611
3061
|
async submitSweep(authorization, signature) {
|
|
1612
|
-
return this.
|
|
1613
|
-
authorization,
|
|
1614
|
-
signature
|
|
1615
|
-
});
|
|
3062
|
+
return this.delegateSweep.submitSweep(authorization, signature);
|
|
1616
3063
|
}
|
|
1617
3064
|
/**
|
|
1618
3065
|
* Get configured and on-chain allowances for the authenticated agent.
|
|
1619
3066
|
*/
|
|
1620
3067
|
async getAllowances() {
|
|
1621
|
-
|
|
1622
|
-
return {
|
|
1623
|
-
agentId: raw.agent_id,
|
|
1624
|
-
safeAddress: raw.safe_address,
|
|
1625
|
-
delegateAddress: raw.delegate_address,
|
|
1626
|
-
chainId: raw.chain_id,
|
|
1627
|
-
allowances: raw.allowances.map((allowance) => ({
|
|
1628
|
-
id: allowance.id,
|
|
1629
|
-
tokenAddress: allowance.token_address,
|
|
1630
|
-
tokenSymbol: allowance.token_symbol,
|
|
1631
|
-
configuredAmount: allowance.configured_amount,
|
|
1632
|
-
resetPeriodMin: allowance.reset_period_min,
|
|
1633
|
-
onchain: {
|
|
1634
|
-
amount: allowance.onchain.amount,
|
|
1635
|
-
spent: allowance.onchain.spent,
|
|
1636
|
-
remaining: allowance.onchain.remaining,
|
|
1637
|
-
effectiveSpent: allowance.onchain.effective_spent,
|
|
1638
|
-
resetTimeMin: allowance.onchain.reset_time_min,
|
|
1639
|
-
lastResetMin: allowance.onchain.last_reset_min,
|
|
1640
|
-
nonce: allowance.onchain.nonce,
|
|
1641
|
-
isResetPending: allowance.onchain.is_reset_pending,
|
|
1642
|
-
remainingIsFromChain: allowance.onchain.remaining_is_from_chain
|
|
1643
|
-
}
|
|
1644
|
-
}))
|
|
1645
|
-
};
|
|
3068
|
+
return this.accountReads.getAllowances();
|
|
1646
3069
|
}
|
|
1647
3070
|
/**
|
|
1648
3071
|
* Post-purchase allowance/budget summary for a settled payment (#1310).
|
|
@@ -1673,62 +3096,7 @@ var HavenClient = class {
|
|
|
1673
3096
|
* phrase it as guaranteed-fresh.
|
|
1674
3097
|
*/
|
|
1675
3098
|
async getPostPurchaseAllowanceSummary(paymentId) {
|
|
1676
|
-
|
|
1677
|
-
payment: null,
|
|
1678
|
-
allowance: null,
|
|
1679
|
-
warnings: [
|
|
1680
|
-
{
|
|
1681
|
-
code: AgentPaymentWarningCode.AllowanceCheckUnavailable,
|
|
1682
|
-
message: `Could not read the post-purchase allowance/budget for payment ${paymentId} (${detail}). The payment itself succeeded \u2014 the on-chain policy remains the actual spend gate; this only affects the remaining-budget figure reported here.`
|
|
1683
|
-
}
|
|
1684
|
-
]
|
|
1685
|
-
});
|
|
1686
|
-
const [statusResult, agentResult, allowanceResult] = await Promise.allSettled([
|
|
1687
|
-
this.getPaymentStatus(paymentId),
|
|
1688
|
-
this.getAgent(),
|
|
1689
|
-
this.getAllowances()
|
|
1690
|
-
]);
|
|
1691
|
-
if (statusResult.status === "rejected") {
|
|
1692
|
-
return unavailable(statusResult.reason instanceof Error ? statusResult.reason.message : String(statusResult.reason));
|
|
1693
|
-
}
|
|
1694
|
-
const status = statusResult.value;
|
|
1695
|
-
if (agentResult.status === "rejected") {
|
|
1696
|
-
return { ...unavailable(agentResult.reason instanceof Error ? agentResult.reason.message : String(agentResult.reason)), payment: status };
|
|
1697
|
-
}
|
|
1698
|
-
if (allowanceResult.status === "rejected") {
|
|
1699
|
-
return { ...unavailable(allowanceResult.reason instanceof Error ? allowanceResult.reason.message : String(allowanceResult.reason)), payment: status };
|
|
1700
|
-
}
|
|
1701
|
-
try {
|
|
1702
|
-
const tokenAddress = status.asset ?? status.x402?.asset ?? null;
|
|
1703
|
-
if (!tokenAddress) {
|
|
1704
|
-
return { ...unavailable("the settled payment does not carry a resolvable token address"), payment: status };
|
|
1705
|
-
}
|
|
1706
|
-
const rail = agentResult.value.executionRail;
|
|
1707
|
-
const source = rail === "delegation" ? "active_delegations" : "allowance_module";
|
|
1708
|
-
const match = allowanceResult.value.allowances.find(
|
|
1709
|
-
(a) => a.tokenAddress.toLowerCase() === tokenAddress.toLowerCase()
|
|
1710
|
-
);
|
|
1711
|
-
if (!match) {
|
|
1712
|
-
return { ...unavailable("no allowance/budget row matches the settled token"), payment: status };
|
|
1713
|
-
}
|
|
1714
|
-
const token = resolveTokenFromAddress(match.tokenAddress);
|
|
1715
|
-
const remainingDisplay = token ? `${formatAtomicAmount(safeBigInt(match.onchain.remaining), token.decimals)} ${match.tokenSymbol}` : void 0;
|
|
1716
|
-
return {
|
|
1717
|
-
payment: status,
|
|
1718
|
-
allowance: {
|
|
1719
|
-
rail,
|
|
1720
|
-
remaining_atomic: match.onchain.remaining,
|
|
1721
|
-
...remainingDisplay ? { remaining_display: remainingDisplay } : {},
|
|
1722
|
-
token_symbol: match.tokenSymbol,
|
|
1723
|
-
token_address: match.tokenAddress,
|
|
1724
|
-
reset_period: match.resetPeriodMin,
|
|
1725
|
-
source
|
|
1726
|
-
},
|
|
1727
|
-
warnings: []
|
|
1728
|
-
};
|
|
1729
|
-
} catch (err) {
|
|
1730
|
-
return unavailable(err instanceof Error ? err.message : String(err));
|
|
1731
|
-
}
|
|
3099
|
+
return this.accountReads.getPostPurchaseAllowanceSummary(paymentId);
|
|
1732
3100
|
}
|
|
1733
3101
|
/**
|
|
1734
3102
|
* `haven_get_payment_status` convenience: fetch status and, for a
|
|
@@ -1785,9 +3153,7 @@ var HavenClient = class {
|
|
|
1785
3153
|
* List recent machine-payment receipts/evidence for bookkeeping.
|
|
1786
3154
|
*/
|
|
1787
3155
|
async listReceipts(options = {}) {
|
|
1788
|
-
|
|
1789
|
-
const raw = await this.get(`/machine-payments/receipts${query}`);
|
|
1790
|
-
return raw.receipts.map((receipt) => this.mapPaymentReceipt(receipt));
|
|
3156
|
+
return this.accountReads.listReceipts(options);
|
|
1791
3157
|
}
|
|
1792
3158
|
/**
|
|
1793
3159
|
* Fetch the verifiable receipt bundle for a settled payment and verify it
|
|
@@ -1796,10 +3162,7 @@ var HavenClient = class {
|
|
|
1796
3162
|
* authorisation, so the result is trustworthy even if the backend lied.
|
|
1797
3163
|
*/
|
|
1798
3164
|
async getReceipt(paymentId) {
|
|
1799
|
-
|
|
1800
|
-
`/payments/${paymentId}/receipt`
|
|
1801
|
-
);
|
|
1802
|
-
return { receipt, verification: verifyPaymentReceipt(receipt) };
|
|
3165
|
+
return this.accountReads.getReceipt(paymentId);
|
|
1803
3166
|
}
|
|
1804
3167
|
/**
|
|
1805
3168
|
* Rehydrate the x402 resume-state bundle for a payment id (#1328: the MPP
|
|
@@ -1852,17 +3215,16 @@ var HavenClient = class {
|
|
|
1852
3215
|
);
|
|
1853
3216
|
}
|
|
1854
3217
|
const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option);
|
|
1855
|
-
const cached = this.
|
|
1856
|
-
if (cached
|
|
3218
|
+
const cached = this.fundingLeg.cachedReceipt(idempotencyKey);
|
|
3219
|
+
if (cached) return cached;
|
|
1857
3220
|
const inFlight = this.inFlightX402.get(idempotencyKey);
|
|
1858
3221
|
if (inFlight) return inFlight;
|
|
1859
|
-
const promise = this.
|
|
3222
|
+
const promise = this.fundingLeg.authorize(paymentRequired, option, idempotencyKey);
|
|
1860
3223
|
this.inFlightX402.set(idempotencyKey, promise);
|
|
1861
3224
|
try {
|
|
1862
3225
|
return await promise;
|
|
1863
3226
|
} catch (err) {
|
|
1864
|
-
|
|
1865
|
-
rail: "x402",
|
|
3227
|
+
attachResumeState(err, {
|
|
1866
3228
|
paymentRequired,
|
|
1867
3229
|
accepted: option,
|
|
1868
3230
|
idempotencyKey
|
|
@@ -1877,9 +3239,9 @@ var HavenClient = class {
|
|
|
1877
3239
|
* payment or approval request.
|
|
1878
3240
|
*/
|
|
1879
3241
|
async quoteX402(url, init, options = {}) {
|
|
1880
|
-
const initialInit =
|
|
1881
|
-
const request =
|
|
1882
|
-
const response = await this.
|
|
3242
|
+
const initialInit = withX402Wallet(init, x402PayerAddress(this.delegateAddress, this.x402Wallet));
|
|
3243
|
+
const request = snapshotX402Request(url, initialInit);
|
|
3244
|
+
const response = await this.merchantTransport.fetch(url, initialInit);
|
|
1883
3245
|
if (response.status !== 402) {
|
|
1884
3246
|
throw new X402UnexpectedStatusError(
|
|
1885
3247
|
`Expected an x402 quote response with HTTP 402, got HTTP ${response.status}.`,
|
|
@@ -1890,8 +3252,8 @@ var HavenClient = class {
|
|
|
1890
3252
|
throw new HavenApiError("quoteX402 only supports standard x402 Payment Required responses.", 400);
|
|
1891
3253
|
}
|
|
1892
3254
|
const paymentRequired = await parsePaymentRequiredResponse(response);
|
|
1893
|
-
const mcpTransport = await this.
|
|
1894
|
-
return
|
|
3255
|
+
const mcpTransport = await this.merchantTransport.detect(url, paymentRequired, response);
|
|
3256
|
+
return buildX402Quote(paymentRequired, request, options.idempotencyKey, mcpTransport);
|
|
1895
3257
|
}
|
|
1896
3258
|
/**
|
|
1897
3259
|
* Probe an MCP tool for its x402 quote without creating a payment.
|
|
@@ -1904,8 +3266,8 @@ var HavenClient = class {
|
|
|
1904
3266
|
* callers that need a plain x402 endpoint must use {@link quoteX402}.
|
|
1905
3267
|
*/
|
|
1906
3268
|
async quoteMcpX402(url, init, options = {}) {
|
|
1907
|
-
const wallet = await this.
|
|
1908
|
-
const sessionId = await this.
|
|
3269
|
+
const wallet = await this.merchantCompletion.resolveWalletForMerchantCall();
|
|
3270
|
+
const sessionId = await this.merchantTransport.initialize(url, init, wallet);
|
|
1909
3271
|
if (!sessionId) {
|
|
1910
3272
|
throw new HavenApiError(
|
|
1911
3273
|
"The merchant did not establish an MCP session before the x402 quote. No payment was created.",
|
|
@@ -1913,238 +3275,71 @@ var HavenClient = class {
|
|
|
1913
3275
|
{ mcpSessionNotEstablished: true }
|
|
1914
3276
|
);
|
|
1915
3277
|
}
|
|
1916
|
-
let requestInit =
|
|
1917
|
-
requestInit = this.
|
|
3278
|
+
let requestInit = withX402Wallet(init, wallet);
|
|
3279
|
+
requestInit = this.merchantTransport.withSessionHeaders(requestInit, sessionId);
|
|
1918
3280
|
const quote = await this.quoteX402(url, requestInit, options);
|
|
1919
3281
|
return {
|
|
1920
3282
|
...quote,
|
|
1921
3283
|
mcpTransport: quote.mcpTransport ?? { handshakeRequired: true, source: "path" }
|
|
1922
3284
|
};
|
|
1923
3285
|
}
|
|
1924
|
-
/**
|
|
1925
|
-
* Pay a previously inspected x402 quote and retry the exact captured request.
|
|
1926
|
-
*/
|
|
1927
|
-
async payX402Quote(quote, options = {}) {
|
|
1928
|
-
const idempotencyKey = options.idempotencyKey ?? quote.idempotencyKey;
|
|
1929
|
-
try {
|
|
1930
|
-
const receipt = await this.authorizeX402(quote.paymentRequired, { idempotencyKey });
|
|
1931
|
-
return this.
|
|
1932
|
-
quote.request.url,
|
|
1933
|
-
|
|
1934
|
-
quote.paymentRequired,
|
|
1935
|
-
receipt
|
|
1936
|
-
);
|
|
1937
|
-
} catch (err) {
|
|
1938
|
-
this.attachResumeState(err, {
|
|
1939
|
-
rail: "x402",
|
|
1940
|
-
paymentRequired: quote.paymentRequired,
|
|
1941
|
-
accepted: quote.accepted,
|
|
1942
|
-
idempotencyKey,
|
|
1943
|
-
request: quote.request
|
|
1944
|
-
});
|
|
1945
|
-
throw err;
|
|
1946
|
-
}
|
|
1947
|
-
}
|
|
1948
|
-
async authorizeStandardX402(paymentRequired, option, idempotencyKey) {
|
|
1949
|
-
const raw = await this.post("/x402", {
|
|
1950
|
-
url: paymentRequired.resource.url,
|
|
1951
|
-
payTo: this.delegateAddress,
|
|
1952
|
-
merchantPayTo: option.payTo,
|
|
1953
|
-
amount: x402AuthorizationAmount(option),
|
|
1954
|
-
asset: option.asset,
|
|
1955
|
-
network: option.network,
|
|
1956
|
-
description: paymentRequired.resource.description,
|
|
1957
|
-
idempotencyKey,
|
|
1958
|
-
// #1360: same explicit funding-leg declaration as createX402Intent —
|
|
1959
|
-
// this local-key path derives payTo from the key (never stale), but the
|
|
1960
|
-
// declaration keeps both writers of the 3009 shape loud-by-default.
|
|
1961
|
-
settlementScheme: "eip3009"
|
|
1962
|
-
});
|
|
1963
|
-
const state = this.paymentStateFromRaw("x402 payment", raw);
|
|
1964
|
-
const executedReplay = raw.success && raw.tx_hash ? "idempotency-collision" : state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request ? "approval-resume" : null;
|
|
1965
|
-
if (executedReplay) {
|
|
1966
|
-
const canFund = await this.delegateCanFund(
|
|
1967
|
-
raw.chain_id ?? state?.chainId ?? chainIdFromNetwork(option.network),
|
|
1968
|
-
option.asset,
|
|
1969
|
-
x402AuthorizationAmount(option)
|
|
1970
|
-
);
|
|
1971
|
-
const refuse = executedReplay === "idempotency-collision" ? canFund !== true : canFund === false;
|
|
1972
|
-
if (refuse) {
|
|
1973
|
-
const settledReceipt = state && executedReplay === "approval-resume" ? this.mapX402ReceiptFromStatus(paymentRequired, option, void 0, state) : this.mapX402ReceiptFromAuthorization(paymentRequired, option, void 0, raw);
|
|
1974
|
-
throw new X402AlreadySettledError(
|
|
1975
|
-
canFund === false ? "This x402 payment already settled \u2014 the delegate no longer holds the funds to authorize it again. To buy the same item a second time, pass a distinct `idempotencyKey`; the synthesised key intentionally collapses repeat calls for the same product within a 5-minute window so a retried request cannot pay twice." : "This x402 payment already settled, and whether the delegate can still fund a new authorization could not be verified (no `chainRpcs` entry for this chain). Refusing rather than issue an authorization that may be unfundable. To buy the same item a second time, pass a distinct `idempotencyKey`; to finish an interrupted payment, resume it by `paymentId`.",
|
|
1976
|
-
settledReceipt,
|
|
1977
|
-
canFund === false ? "settled" : "unverifiable"
|
|
1978
|
-
);
|
|
1979
|
-
}
|
|
1980
|
-
}
|
|
1981
|
-
const paymentHeader = await this.createStandardX402Header(paymentRequired, option);
|
|
1982
|
-
if (raw.success && raw.tx_hash) {
|
|
1983
|
-
const receipt2 = this.mapX402ReceiptFromAuthorization(paymentRequired, option, paymentHeader, raw);
|
|
1984
|
-
this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt2);
|
|
1985
|
-
return receipt2;
|
|
1986
|
-
}
|
|
1987
|
-
if (state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request) {
|
|
1988
|
-
const receipt2 = this.mapX402ReceiptFromStatus(paymentRequired, option, paymentHeader, state);
|
|
1989
|
-
this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt2);
|
|
1990
|
-
return receipt2;
|
|
1991
|
-
}
|
|
1992
|
-
this.throwIfNonSignableAuthorizationState("x402 payment", raw);
|
|
1993
|
-
if (!raw.sign_data?.hash) {
|
|
1994
|
-
throw new HavenApiError("No sign_hash returned from x402/authorize", 500, raw);
|
|
1995
|
-
}
|
|
1996
|
-
const sig = await this.signForData(raw.sign_data);
|
|
1997
|
-
const execResult = await this.post(
|
|
1998
|
-
`/payments/${raw.payment_id}/sign`,
|
|
1999
|
-
{ signature: sig }
|
|
2000
|
-
);
|
|
2001
|
-
if (execResult.status !== "confirmed") {
|
|
2002
|
-
this.throwPaymentStateError("x402 payment", execResult);
|
|
2003
|
-
}
|
|
2004
|
-
await this.waitForFundingTx(
|
|
2005
|
-
execResult.tx_hash,
|
|
2006
|
-
execResult.chain_id ?? chainIdFromNetwork(option.network)
|
|
2007
|
-
);
|
|
2008
|
-
const receipt = this.mapX402ReceiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult);
|
|
2009
|
-
this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt);
|
|
2010
|
-
return receipt;
|
|
2011
|
-
}
|
|
2012
|
-
/**
|
|
2013
|
-
* Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).
|
|
2014
|
-
*
|
|
2015
|
-
* The whole point of this path is what it does NOT do. There is no funding
|
|
2016
|
-
* leg: the merchant redeems a delegation chain and pulls from the treasury
|
|
2017
|
-
* directly, so the delegate EOA never holds the money, no sweep can strand
|
|
2018
|
-
* it, and the #713 reconciliation class does not apply. It is also why this
|
|
2019
|
-
* method is SMALLER than the 3009 path — the backend assembles the merchant
|
|
2020
|
-
* `X-PAYMENT` header in `assembleSettlementPayload`, so the SDK builds no
|
|
2021
|
-
* header locally.
|
|
2022
|
-
*
|
|
2023
|
-
* authorize (payTo = the MERCHANT) → sign the child → settle → header
|
|
2024
|
-
*
|
|
2025
|
-
* The caller then retries the merchant with that header. **Nothing has
|
|
2026
|
-
* settled when this returns** — that is why it does not return an
|
|
2027
|
-
* `X402Receipt`.
|
|
2028
|
-
*
|
|
2029
|
-
* Requires a delegation-rail account. The backend enforces that
|
|
2030
|
-
* (`validateGenericSchemeRail`), and so does this method, before building a
|
|
2031
|
-
* request the backend would only reject: an error a client can explain is
|
|
2032
|
-
* worth more than a 400 it has to decode.
|
|
2033
|
-
*
|
|
2034
|
-
* **MCP callers must pass `options.resourceUrl`.** An in-band MCP 402
|
|
2035
|
-
* challenge frequently carries no `resource` object at all, so
|
|
2036
|
-
* `paymentRequired.resource?.url` is undefined and the backend answers
|
|
2037
|
-
* "Valid url is required". The QA scenario this path was ported from falls
|
|
2038
|
-
* back to the request URL for exactly that reason — the SDK cannot, because
|
|
2039
|
-
* it never saw the request. Pass it.
|
|
2040
|
-
*/
|
|
2041
|
-
async settleX402Erc7710(paymentRequired, options = {}) {
|
|
2042
|
-
if (!this.delegateKey) {
|
|
2043
|
-
throw new HavenSigningError(
|
|
2044
|
-
"delegateKey is required for x402 payments. Pass it in the HavenClient config."
|
|
2045
|
-
);
|
|
2046
|
-
}
|
|
2047
|
-
const prepared = await this.prepareX402Erc7710(paymentRequired, options);
|
|
2048
|
-
const signature = await this.signForData(prepared.signData);
|
|
2049
|
-
const paymentHeader = await this.submitX402Erc7710(prepared.paymentId, signature);
|
|
2050
|
-
return { ...prepared.settlement, paymentHeader };
|
|
2051
|
-
}
|
|
2052
|
-
/**
|
|
2053
|
-
* The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build
|
|
2054
|
-
* the request, and return the child to be signed — without signing it.
|
|
2055
|
-
*
|
|
2056
|
-
* Split out because the hosted topology cannot use `settleX402Erc7710()`:
|
|
2057
|
-
* that method signs in-process with `delegateKey`, and hosted Haven does not
|
|
2058
|
-
* have one and must not. The hosted MCP server drives these two halves with
|
|
2059
|
-
* the LOCAL signer in between, so the key stays where it belongs and the
|
|
2060
|
-
* request shaping stays in one place rather than being reimplemented.
|
|
2061
|
-
*/
|
|
2062
|
-
async prepareX402Erc7710(paymentRequired, options = {}) {
|
|
2063
|
-
const delegationRail = options.delegationRail ?? (await this.getAgent()).executionRail === "delegation";
|
|
2064
|
-
if (!delegationRail) {
|
|
2065
|
-
throw new HavenApiError(
|
|
2066
|
-
"erc7710 settlement requires a delegation-rail account; this one is not on it. Use authorizeX402() for the standard EIP-3009 path.",
|
|
2067
|
-
400
|
|
2068
|
-
);
|
|
2069
|
-
}
|
|
2070
|
-
const selection = selectX402SettlementScheme(paymentRequired.accepts, { delegationRail });
|
|
2071
|
-
if (!selection || selection.scheme !== "erc7710") {
|
|
2072
|
-
throw new HavenApiError(
|
|
2073
|
-
"This merchant does not advertise an erc7710 settlement option (no accepts[] entry carries extra.assetTransferMethod: 'erc7710'). Use authorizeX402() for the standard EIP-3009 path.",
|
|
2074
|
-
400
|
|
2075
|
-
);
|
|
2076
|
-
}
|
|
2077
|
-
const option = selection.option;
|
|
2078
|
-
const merchantPayTo = option.payTo;
|
|
2079
|
-
const amountAtomic = x402AuthorizationAmount(option);
|
|
2080
|
-
const raw = await this.post("/x402", {
|
|
2081
|
-
url: options.resourceUrl ?? paymentRequired.resource?.url,
|
|
2082
|
-
// payTo = the MERCHANT is what selects direct settlement server-side.
|
|
2083
|
-
// The explicit settlementScheme must AGREE with that shape (#1360) —
|
|
2084
|
-
// disagreement is a 400 by design, so that a stale delegate address
|
|
2085
|
-
// becomes a loud mismatch instead of a silent reroute to the 3009 leg.
|
|
2086
|
-
payTo: merchantPayTo,
|
|
2087
|
-
settlementScheme: "erc7710",
|
|
2088
|
-
amount: amountAtomic,
|
|
2089
|
-
asset: option.asset,
|
|
2090
|
-
network: option.network,
|
|
2091
|
-
// The v2 header echoes the accepted entry field-for-field, so the quoted
|
|
2092
|
-
// timeout must round-trip or the merchant rejects the echo (#1064).
|
|
2093
|
-
maxTimeoutSeconds: option.maxTimeoutSeconds,
|
|
2094
|
-
// #1058: forward the advertised facilitators verbatim — the child becomes
|
|
2095
|
-
// redeemable ONLY by them. `null` here means the merchant advertised none
|
|
2096
|
-
// (or an empty array, which the backend 400s on), so the field is OMITTED
|
|
2097
|
-
// rather than sent empty. See x402FacilitatorAddresses.
|
|
2098
|
-
...selection.facilitatorAddresses ? { facilitatorAddresses: selection.facilitatorAddresses } : {},
|
|
2099
|
-
// #1307/#1547: persisted so the settle leg can rehydrate the merchant
|
|
2100
|
-
// call by payment_id on this scheme too, not only on the 3009 bridge.
|
|
2101
|
-
...options.mcpCallContext ? { mcpCallContext: options.mcpCallContext } : {}
|
|
2102
|
-
});
|
|
2103
|
-
if (!raw.payment_id) {
|
|
2104
|
-
throw new HavenApiError("No payment_id returned from x402/authorize", 500, raw);
|
|
2105
|
-
}
|
|
2106
|
-
const signData = raw.sign_data;
|
|
2107
|
-
if (signData?.signature_scheme !== "eip712_delegation" || !signData.typed_data) {
|
|
2108
|
-
throw new HavenApiError(
|
|
2109
|
-
`x402/authorize did not return an erc7710 settlement child (signature_scheme was ${JSON.stringify(signData?.signature_scheme)}). Refusing to sign a payload this path did not ask for.`,
|
|
2110
|
-
500,
|
|
2111
|
-
raw
|
|
3286
|
+
/**
|
|
3287
|
+
* Pay a previously inspected x402 quote and retry the exact captured request.
|
|
3288
|
+
*/
|
|
3289
|
+
async payX402Quote(quote, options = {}) {
|
|
3290
|
+
const idempotencyKey = options.idempotencyKey ?? quote.idempotencyKey;
|
|
3291
|
+
try {
|
|
3292
|
+
const receipt = await this.authorizeX402(quote.paymentRequired, { idempotencyKey });
|
|
3293
|
+
return this.merchantCompletion.retryRequest(
|
|
3294
|
+
quote.request.url,
|
|
3295
|
+
requestInitFromSnapshot(quote.request),
|
|
3296
|
+
quote.paymentRequired,
|
|
3297
|
+
receipt
|
|
2112
3298
|
);
|
|
3299
|
+
} catch (err) {
|
|
3300
|
+
attachResumeState(err, {
|
|
3301
|
+
paymentRequired: quote.paymentRequired,
|
|
3302
|
+
accepted: quote.accepted,
|
|
3303
|
+
idempotencyKey,
|
|
3304
|
+
request: quote.request
|
|
3305
|
+
});
|
|
3306
|
+
throw err;
|
|
2113
3307
|
}
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
3308
|
+
}
|
|
3309
|
+
/**
|
|
3310
|
+
* Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).
|
|
3311
|
+
*
|
|
3312
|
+
* **Nothing has settled when this returns** — that is why it does not return
|
|
3313
|
+
* an `X402Receipt`; the caller still has to retry the merchant with the
|
|
3314
|
+
* header. **MCP callers must pass `options.resourceUrl`**, because an in-band
|
|
3315
|
+
* MCP 402 challenge frequently carries no `resource` object at all.
|
|
3316
|
+
*
|
|
3317
|
+
* Both caveats, and why this scheme has no funding leg, are explained where
|
|
3318
|
+
* the lifecycle lives: `x402-erc7710.ts` (#1619).
|
|
3319
|
+
*/
|
|
3320
|
+
async settleX402Erc7710(paymentRequired, options = {}) {
|
|
3321
|
+
return this.erc7710.settle(paymentRequired, options);
|
|
3322
|
+
}
|
|
3323
|
+
/**
|
|
3324
|
+
* The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build
|
|
3325
|
+
* the request, and return the child to be signed — without signing it.
|
|
3326
|
+
*
|
|
3327
|
+
* Split out because the hosted topology cannot use `settleX402Erc7710()`:
|
|
3328
|
+
* that method signs in-process with `delegateKey`, and hosted Haven does not
|
|
3329
|
+
* have one and must not.
|
|
3330
|
+
*/
|
|
3331
|
+
async prepareX402Erc7710(paymentRequired, options = {}) {
|
|
3332
|
+
return this.erc7710.prepare(paymentRequired, options);
|
|
2126
3333
|
}
|
|
2127
3334
|
/**
|
|
2128
3335
|
* The SETTLE half (#1456): exchange the signed child for the merchant header.
|
|
2129
3336
|
*
|
|
2130
3337
|
* The SDK builds no header on this path — the backend assembles the MetaMask
|
|
2131
|
-
* erc7710 payload
|
|
2132
|
-
*
|
|
2133
|
-
* hosted boundary) is irrelevant here.
|
|
3338
|
+
* erc7710 payload. Whoever produced the signature (an in-process delegate
|
|
3339
|
+
* key, or the local edge signer over the hosted boundary) is irrelevant.
|
|
2134
3340
|
*/
|
|
2135
3341
|
async submitX402Erc7710(paymentId, signature) {
|
|
2136
|
-
|
|
2137
|
-
`/x402/${paymentId}/settle`,
|
|
2138
|
-
{ signature }
|
|
2139
|
-
);
|
|
2140
|
-
if (!settled.payment_header) {
|
|
2141
|
-
throw new HavenApiError(
|
|
2142
|
-
"x402 settle returned no payment_header \u2014 the merchant cannot be retried.",
|
|
2143
|
-
500,
|
|
2144
|
-
settled
|
|
2145
|
-
);
|
|
2146
|
-
}
|
|
2147
|
-
return settled.payment_header;
|
|
3342
|
+
return this.erc7710.submit(paymentId, signature);
|
|
2148
3343
|
}
|
|
2149
3344
|
async resumeAuthorizedX402(input) {
|
|
2150
3345
|
if (!this.delegateKey) {
|
|
@@ -2163,11 +3358,11 @@ var HavenClient = class {
|
|
|
2163
3358
|
);
|
|
2164
3359
|
}
|
|
2165
3360
|
const idempotencyKey = input.idempotencyKey ?? buildX402IdempotencyKey(input.paymentRequired, option);
|
|
2166
|
-
const cached = this.
|
|
2167
|
-
if (cached
|
|
3361
|
+
const cached = this.fundingLeg.cachedReceipt(idempotencyKey);
|
|
3362
|
+
if (cached) return cached;
|
|
2168
3363
|
const status = await this.getPaymentStatus(input.paymentId);
|
|
2169
|
-
|
|
2170
|
-
const canFund = await this.delegateCanFund(
|
|
3364
|
+
assertCanResumeX402(status, input.paymentRequired, option);
|
|
3365
|
+
const canFund = await this.fundingLeg.delegateCanFund(
|
|
2171
3366
|
status.chainId ?? chainIdFromNetwork(option.network),
|
|
2172
3367
|
option.asset,
|
|
2173
3368
|
x402AuthorizationAmount(option)
|
|
@@ -2175,20 +3370,20 @@ var HavenClient = class {
|
|
|
2175
3370
|
if (canFund === false) {
|
|
2176
3371
|
throw new X402AlreadySettledError(
|
|
2177
3372
|
`x402 payment ${status.paymentId} has already settled \u2014 the delegate no longer holds the funds to authorize it again, so there is nothing left to resume.`,
|
|
2178
|
-
this.
|
|
3373
|
+
this.fundingLeg.receiptFromStatus(input.paymentRequired, option, void 0, status),
|
|
2179
3374
|
"settled"
|
|
2180
3375
|
);
|
|
2181
3376
|
}
|
|
2182
|
-
const paymentHeader = await this.
|
|
2183
|
-
const receipt = this.
|
|
2184
|
-
this.
|
|
3377
|
+
const paymentHeader = await this.fundingLeg.createPaymentHeader(input.paymentRequired, option);
|
|
3378
|
+
const receipt = this.fundingLeg.receiptFromStatus(input.paymentRequired, option, paymentHeader, status);
|
|
3379
|
+
this.fundingLeg.cacheReceipt(idempotencyKey, paymentHeader, receipt);
|
|
2185
3380
|
return receipt;
|
|
2186
3381
|
}
|
|
2187
3382
|
async resumeX402Payment(input) {
|
|
2188
3383
|
const inputInit = "init" in input ? input.init : void 0;
|
|
2189
|
-
const initialInit =
|
|
2190
|
-
inputInit ?? (input.request ?
|
|
2191
|
-
this.
|
|
3384
|
+
const initialInit = withX402Wallet(
|
|
3385
|
+
inputInit ?? (input.request ? requestInitFromSnapshot(input.request) : void 0),
|
|
3386
|
+
x402PayerAddress(this.delegateAddress, this.x402Wallet)
|
|
2192
3387
|
);
|
|
2193
3388
|
let paymentRequired = input.paymentRequired;
|
|
2194
3389
|
const url = input.url ?? input.request?.url;
|
|
@@ -2196,7 +3391,7 @@ var HavenClient = class {
|
|
|
2196
3391
|
if (!url) {
|
|
2197
3392
|
throw new HavenApiError("x402 resume requires the original URL or a captured request snapshot.", 400);
|
|
2198
3393
|
}
|
|
2199
|
-
const response = await this.
|
|
3394
|
+
const response = await this.merchantTransport.fetch(url, initialInit);
|
|
2200
3395
|
if (response.status !== 402) {
|
|
2201
3396
|
throw new HavenApiError("Expected the original x402 request to return HTTP 402 before resuming.", 400);
|
|
2202
3397
|
}
|
|
@@ -2207,7 +3402,7 @@ var HavenClient = class {
|
|
|
2207
3402
|
paymentRequired,
|
|
2208
3403
|
idempotencyKey: input.idempotencyKey
|
|
2209
3404
|
});
|
|
2210
|
-
return this.
|
|
3405
|
+
return this.merchantCompletion.retryRequest(url ?? paymentRequired.resource.url, initialInit, paymentRequired, receipt);
|
|
2211
3406
|
}
|
|
2212
3407
|
/**
|
|
2213
3408
|
* Fetch wrapper that automatically handles HTTP 402 responses.
|
|
@@ -2221,268 +3416,57 @@ var HavenClient = class {
|
|
|
2221
3416
|
* ```
|
|
2222
3417
|
*
|
|
2223
3418
|
* **MCP-over-x402 auto-handshake (issue #315):** when the endpoint is
|
|
2224
|
-
* MCP-shaped — the URL path ends in `/mcp`, or the 402 body carries a
|
|
2225
|
-
* Coinbase Bazaar `extensions.bazaar` block — the SDK runs the MCP
|
|
2226
|
-
* `initialize` handshake, threads the resulting `mcp-session-id`,
|
|
2227
|
-
* `Accept: application/json, text/event-stream`, and `x402-wallet` headers
|
|
2228
|
-
* through every request, and collapses SSE responses to the JSON-RPC
|
|
2229
|
-
* `result`. The caller just passes `(url, { body })` and never sees the
|
|
2230
|
-
* protocol plumbing. A non-MCP server (handshake error / no session id)
|
|
2231
|
-
* falls back to standard x402 behaviour.
|
|
2232
|
-
*
|
|
2233
|
-
* Requires `delegateKey` to be set in the client config.
|
|
2234
|
-
*/
|
|
2235
|
-
async fetch(url, init, options = {}) {
|
|
2236
|
-
let mcpSessionId;
|
|
2237
|
-
if (isMcpUrl(url)) {
|
|
2238
|
-
mcpSessionId = await this.mcpInitialize(url, init);
|
|
2239
|
-
}
|
|
2240
|
-
let requestInit = this.withX402Wallet(init, this.x402PayerAddress());
|
|
2241
|
-
if (mcpSessionId) requestInit = this.withMcpHeaders(requestInit, mcpSessionId);
|
|
2242
|
-
const response = await this.merchantFetch(url, requestInit);
|
|
2243
|
-
if (response.status !== 402) {
|
|
2244
|
-
return mcpSessionId ? this.surfaceMcpResult(response) : response;
|
|
2245
|
-
}
|
|
2246
|
-
let paymentRequired;
|
|
2247
|
-
try {
|
|
2248
|
-
paymentRequired = await parsePaymentRequiredResponse(response);
|
|
2249
|
-
} catch {
|
|
2250
|
-
return response;
|
|
2251
|
-
}
|
|
2252
|
-
if (!mcpSessionId && await responseHasBazaarExtension(response)) {
|
|
2253
|
-
mcpSessionId = await this.mcpInitialize(url, init);
|
|
2254
|
-
if (mcpSessionId) requestInit = this.withMcpHeaders(requestInit, mcpSessionId);
|
|
2255
|
-
}
|
|
2256
|
-
const request = this.snapshotX402Request(url, requestInit);
|
|
2257
|
-
const option = selectStandardPaymentOption(paymentRequired.accepts);
|
|
2258
|
-
const idempotencyKey = options.idempotencyKey ?? (option ? buildX402IdempotencyKey(paymentRequired, option) : void 0);
|
|
2259
|
-
let receipt;
|
|
2260
|
-
try {
|
|
2261
|
-
receipt = await this.authorizeX402(paymentRequired, options);
|
|
2262
|
-
} catch (err) {
|
|
2263
|
-
if (option && idempotencyKey) {
|
|
2264
|
-
this.attachResumeState(err, {
|
|
2265
|
-
rail: "x402",
|
|
2266
|
-
paymentRequired,
|
|
2267
|
-
accepted: option,
|
|
2268
|
-
idempotencyKey,
|
|
2269
|
-
request
|
|
2270
|
-
});
|
|
2271
|
-
}
|
|
2272
|
-
throw err;
|
|
2273
|
-
}
|
|
2274
|
-
const retryResponse = await this.retryX402Request(url, requestInit, paymentRequired, receipt);
|
|
2275
|
-
return mcpSessionId ? this.surfaceMcpResult(retryResponse) : retryResponse;
|
|
2276
|
-
}
|
|
2277
|
-
// ── MCP-over-x402 transport helpers (issue #315) ─────────────────
|
|
2278
|
-
/**
|
|
2279
|
-
* Run the MCP `initialize` handshake against a Streamable-HTTP endpoint and
|
|
2280
|
-
* return the `mcp-session-id` the server assigns.
|
|
2281
|
-
*
|
|
2282
|
-
* Returns `undefined` whenever the endpoint is not actually an MCP server —
|
|
2283
|
-
* a transport/HTTP error, a missing session id, or a JSON-RPC error in the
|
|
2284
|
-
* handshake response — so the caller can fall back to plain x402.
|
|
2285
|
-
*/
|
|
2286
|
-
async mcpInitialize(url, init, wallet = this.x402PayerAddress()) {
|
|
2287
|
-
try {
|
|
2288
|
-
const headers = new Headers(init?.headers);
|
|
2289
|
-
headers.set("Content-Type", "application/json");
|
|
2290
|
-
headers.set("Accept", MCP_ACCEPT);
|
|
2291
|
-
if (wallet && !headers.has("x402-wallet")) headers.set("x402-wallet", wallet);
|
|
2292
|
-
const response = await this.merchantFetch(url, {
|
|
2293
|
-
method: "POST",
|
|
2294
|
-
headers,
|
|
2295
|
-
body: JSON.stringify({
|
|
2296
|
-
jsonrpc: "2.0",
|
|
2297
|
-
id: ++this.mcpRequestId,
|
|
2298
|
-
method: "initialize",
|
|
2299
|
-
params: {
|
|
2300
|
-
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
2301
|
-
capabilities: {},
|
|
2302
|
-
clientInfo: MCP_CLIENT_INFO
|
|
2303
|
-
}
|
|
2304
|
-
})
|
|
2305
|
-
});
|
|
2306
|
-
if (!response.ok) return void 0;
|
|
2307
|
-
const sessionId = response.headers.get("mcp-session-id");
|
|
2308
|
-
if (!sessionId) return void 0;
|
|
2309
|
-
const message = await this.readMcpMessage(response);
|
|
2310
|
-
if (message && "error" in message) return void 0;
|
|
2311
|
-
await this.mcpNotifyInitialized(url, init, sessionId, wallet);
|
|
2312
|
-
return sessionId;
|
|
2313
|
-
} catch {
|
|
2314
|
-
return void 0;
|
|
2315
|
-
}
|
|
2316
|
-
}
|
|
2317
|
-
/**
|
|
2318
|
-
* Send the MCP `notifications/initialized` notification that completes the
|
|
2319
|
-
* lifecycle handshake. Best-effort: the session is already established, so a
|
|
2320
|
-
* failed notification must not abort the payment.
|
|
2321
|
-
*/
|
|
2322
|
-
async mcpNotifyInitialized(url, init, sessionId, wallet = this.x402PayerAddress()) {
|
|
2323
|
-
try {
|
|
2324
|
-
const headers = new Headers(init?.headers);
|
|
2325
|
-
headers.set("Content-Type", "application/json");
|
|
2326
|
-
headers.set("Accept", MCP_ACCEPT);
|
|
2327
|
-
headers.set("mcp-session-id", sessionId);
|
|
2328
|
-
if (wallet && !headers.has("x402-wallet")) headers.set("x402-wallet", wallet);
|
|
2329
|
-
await this.merchantFetch(
|
|
2330
|
-
url,
|
|
2331
|
-
{
|
|
2332
|
-
method: "POST",
|
|
2333
|
-
headers,
|
|
2334
|
-
body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
|
|
2335
|
-
},
|
|
2336
|
-
NOTIFY_TIMEOUT
|
|
2337
|
-
);
|
|
2338
|
-
} catch {
|
|
2339
|
-
}
|
|
2340
|
-
}
|
|
2341
|
-
/** Read a single JSON-RPC message from an MCP response (JSON or SSE body). */
|
|
2342
|
-
async readMcpMessage(response) {
|
|
2343
|
-
let text;
|
|
2344
|
-
try {
|
|
2345
|
-
text = await response.clone().text();
|
|
2346
|
-
} catch {
|
|
2347
|
-
return void 0;
|
|
2348
|
-
}
|
|
2349
|
-
if ((response.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
2350
|
-
return selectJsonRpcResult(parseSseJsonRpcMessages(text));
|
|
2351
|
-
}
|
|
2352
|
-
try {
|
|
2353
|
-
return JSON.parse(text);
|
|
2354
|
-
} catch {
|
|
2355
|
-
return void 0;
|
|
2356
|
-
}
|
|
2357
|
-
}
|
|
2358
|
-
/** Add the MCP transport headers (session id + SSE Accept) to a request. */
|
|
2359
|
-
withMcpHeaders(init, sessionId) {
|
|
2360
|
-
const headers = new Headers(init?.headers);
|
|
2361
|
-
headers.set("mcp-session-id", sessionId);
|
|
2362
|
-
headers.set("Accept", MCP_ACCEPT);
|
|
2363
|
-
return { ...init, headers };
|
|
2364
|
-
}
|
|
2365
|
-
/**
|
|
2366
|
-
* Collapse an MCP SSE response into a plain JSON response carrying the
|
|
2367
|
-
* JSON-RPC `result`, so callers of `fetch()` never see raw SSE framing.
|
|
2368
|
-
* Non-SSE responses pass through untouched.
|
|
2369
|
-
*/
|
|
2370
|
-
async surfaceMcpResult(response) {
|
|
2371
|
-
if (!(response.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
2372
|
-
return response;
|
|
2373
|
-
}
|
|
2374
|
-
let text;
|
|
2375
|
-
try {
|
|
2376
|
-
text = await response.clone().text();
|
|
2377
|
-
} catch {
|
|
2378
|
-
return response;
|
|
2379
|
-
}
|
|
2380
|
-
const message = selectJsonRpcResult(parseSseJsonRpcMessages(text));
|
|
2381
|
-
if (!message) return response;
|
|
2382
|
-
const body = "result" in message ? message.result : message;
|
|
2383
|
-
const headers = new Headers(response.headers);
|
|
2384
|
-
headers.set("content-type", "application/json");
|
|
2385
|
-
headers.delete("content-length");
|
|
2386
|
-
headers.delete("mcp-session-id");
|
|
2387
|
-
return new Response(JSON.stringify(body), {
|
|
2388
|
-
status: response.status,
|
|
2389
|
-
statusText: response.statusText,
|
|
2390
|
-
headers
|
|
2391
|
-
});
|
|
2392
|
-
}
|
|
2393
|
-
async retryX402Request(url, initialInit, paymentRequired, receipt) {
|
|
2394
|
-
if (!receipt.accepted) {
|
|
2395
|
-
throw new HavenApiError("No accepted x402 option was recorded for payment retry", 500);
|
|
2396
|
-
}
|
|
2397
|
-
if (!receipt.paymentHeader) {
|
|
2398
|
-
throw new HavenApiError("No x402 payment header was returned for payment retry", 500);
|
|
2399
|
-
}
|
|
2400
|
-
const retryHeaders = new Headers(initialInit?.headers);
|
|
2401
|
-
retryHeaders.set("X-PAYMENT", receipt.paymentHeader);
|
|
2402
|
-
const retryResponse = await this.merchantFetch(url, {
|
|
2403
|
-
...initialInit,
|
|
2404
|
-
headers: retryHeaders
|
|
2405
|
-
});
|
|
2406
|
-
if (!retryResponse.ok) {
|
|
2407
|
-
const merchant = await captureMerchantResponse(retryResponse);
|
|
2408
|
-
await this.recordMerchantRetryRejected({
|
|
2409
|
-
rail: "x402",
|
|
2410
|
-
paymentId: receipt.paymentId,
|
|
2411
|
-
txHash: receipt.txHash,
|
|
2412
|
-
resourceUrl: receipt.resourceUrl,
|
|
2413
|
-
merchant,
|
|
2414
|
-
details: {
|
|
2415
|
-
merchant_to: receipt.merchantTo,
|
|
2416
|
-
delegate_to: receipt.to
|
|
2417
|
-
}
|
|
2418
|
-
});
|
|
2419
|
-
throw new HavenApiError(
|
|
2420
|
-
"x402 retry failed after Haven funded the delegate wallet; reconciliation may be required.",
|
|
2421
|
-
merchant.merchant_status,
|
|
2422
|
-
{
|
|
2423
|
-
marker: "x402_retry_rejected_after_funding",
|
|
2424
|
-
payment_id: receipt.paymentId,
|
|
2425
|
-
tx_hash: receipt.txHash,
|
|
2426
|
-
resource_url: receipt.resourceUrl,
|
|
2427
|
-
merchant_to: receipt.merchantTo,
|
|
2428
|
-
delegate_to: receipt.to,
|
|
2429
|
-
...merchant
|
|
2430
|
-
}
|
|
2431
|
-
);
|
|
2432
|
-
}
|
|
2433
|
-
const merchantSettlement = parseMerchantSettlement(retryResponse.headers.get("PAYMENT-RESPONSE"));
|
|
2434
|
-
if (receipt.merchant && merchantSettlement.settlementTxHash) {
|
|
2435
|
-
receipt.merchant.settlementTxHash = merchantSettlement.settlementTxHash;
|
|
2436
|
-
receipt.merchant.settlementExplorerUrl = buildExplorerUrl(
|
|
2437
|
-
receipt.chainId,
|
|
2438
|
-
merchantSettlement.settlementTxHash
|
|
2439
|
-
);
|
|
2440
|
-
}
|
|
2441
|
-
await this.reportMachinePaymentEvidence({
|
|
2442
|
-
paymentId: receipt.paymentId,
|
|
2443
|
-
rail: "x402",
|
|
2444
|
-
txHash: receipt.txHash,
|
|
2445
|
-
resourceUrl: receipt.resourceUrl,
|
|
2446
|
-
merchantStatus: retryResponse.status,
|
|
2447
|
-
challengePayload: paymentRequired,
|
|
2448
|
-
selectedPayment: receipt.accepted,
|
|
2449
|
-
paymentProofHeaderName: "X-PAYMENT",
|
|
2450
|
-
paymentProofHeader: receipt.paymentHeader,
|
|
2451
|
-
protocolReceiptHeaderName: "PAYMENT-RESPONSE",
|
|
2452
|
-
protocolReceiptHeader: retryResponse.headers.get("PAYMENT-RESPONSE") ?? void 0
|
|
2453
|
-
});
|
|
2454
|
-
await this.reportMerchantReceipt(receipt.paymentId, retryResponse);
|
|
2455
|
-
return retryResponse;
|
|
2456
|
-
}
|
|
2457
|
-
/**
|
|
2458
|
-
* #956: capture the merchant's OWN receipt when the paid response carries
|
|
2459
|
-
* one, and report it to Haven so the reporting feed can attach it next to
|
|
2460
|
-
* the Haven-generated payment evidence (#498). Two supported signals on the
|
|
2461
|
-
* paid response:
|
|
2462
|
-
*
|
|
2463
|
-
* x-receipt-json: base64-encoded JSON receipt document (inline)
|
|
2464
|
-
* x-receipt-url: https URL to the receipt document (reference)
|
|
3419
|
+
* MCP-shaped — the URL path ends in `/mcp`, or the 402 body carries a
|
|
3420
|
+
* Coinbase Bazaar `extensions.bazaar` block — the SDK runs the MCP
|
|
3421
|
+
* `initialize` handshake, threads the resulting `mcp-session-id`,
|
|
3422
|
+
* `Accept: application/json, text/event-stream`, and `x402-wallet` headers
|
|
3423
|
+
* through every request, and collapses SSE responses to the JSON-RPC
|
|
3424
|
+
* `result`. The caller just passes `(url, { body })` and never sees the
|
|
3425
|
+
* protocol plumbing. A non-MCP server (handshake error / no session id)
|
|
3426
|
+
* falls back to standard x402 behaviour.
|
|
2465
3427
|
*
|
|
2466
|
-
*
|
|
2467
|
-
* ever affect the completed payment — the response is already paid for.
|
|
3428
|
+
* Requires `delegateKey` to be set in the client config.
|
|
2468
3429
|
*/
|
|
2469
|
-
async
|
|
3430
|
+
async fetch(url, init, options = {}) {
|
|
3431
|
+
let mcpSessionId;
|
|
3432
|
+
if (this.merchantTransport.isMcpUrl(url)) {
|
|
3433
|
+
mcpSessionId = await this.merchantTransport.initialize(url, init);
|
|
3434
|
+
}
|
|
3435
|
+
let requestInit = withX402Wallet(init, x402PayerAddress(this.delegateAddress, this.x402Wallet));
|
|
3436
|
+
if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId);
|
|
3437
|
+
const response = await this.merchantTransport.fetch(url, requestInit);
|
|
3438
|
+
if (response.status !== 402) {
|
|
3439
|
+
return mcpSessionId ? this.merchantTransport.surfaceResult(response) : response;
|
|
3440
|
+
}
|
|
3441
|
+
let paymentRequired;
|
|
2470
3442
|
try {
|
|
2471
|
-
|
|
2472
|
-
const url = response.headers.get("x-receipt-url");
|
|
2473
|
-
if (!inlineB64 && !url) return;
|
|
2474
|
-
let body = null;
|
|
2475
|
-
if (inlineB64) {
|
|
2476
|
-
if (inlineB64.length > Math.ceil(64 * 1024 * 4 / 3)) return;
|
|
2477
|
-
const decoded = JSON.parse(Buffer.from(inlineB64, "base64").toString("utf8"));
|
|
2478
|
-
if (decoded && typeof decoded === "object") body = { json: decoded };
|
|
2479
|
-
} else if (url && url.startsWith("https://") && url.length <= 2048) {
|
|
2480
|
-
body = { url };
|
|
2481
|
-
}
|
|
2482
|
-
if (!body) return;
|
|
2483
|
-
await this.post(`/machine-payments/${paymentId}/merchant-receipt`, body);
|
|
3443
|
+
paymentRequired = await parsePaymentRequiredResponse(response);
|
|
2484
3444
|
} catch {
|
|
3445
|
+
return response;
|
|
3446
|
+
}
|
|
3447
|
+
if (!mcpSessionId && await this.merchantTransport.hasBazaarExtension(response)) {
|
|
3448
|
+
mcpSessionId = await this.merchantTransport.initialize(url, init);
|
|
3449
|
+
if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId);
|
|
3450
|
+
}
|
|
3451
|
+
const request = snapshotX402Request(url, requestInit);
|
|
3452
|
+
const option = selectStandardPaymentOption(paymentRequired.accepts);
|
|
3453
|
+
const idempotencyKey = options.idempotencyKey ?? (option ? buildX402IdempotencyKey(paymentRequired, option) : void 0);
|
|
3454
|
+
let receipt;
|
|
3455
|
+
try {
|
|
3456
|
+
receipt = await this.authorizeX402(paymentRequired, options);
|
|
3457
|
+
} catch (err) {
|
|
3458
|
+
if (option && idempotencyKey) {
|
|
3459
|
+
attachResumeState(err, {
|
|
3460
|
+
paymentRequired,
|
|
3461
|
+
accepted: option,
|
|
3462
|
+
idempotencyKey,
|
|
3463
|
+
request
|
|
3464
|
+
});
|
|
3465
|
+
}
|
|
3466
|
+
throw err;
|
|
2485
3467
|
}
|
|
3468
|
+
const retryResponse = await this.merchantCompletion.retryRequest(url, requestInit, paymentRequired, receipt);
|
|
3469
|
+
return mcpSessionId ? this.merchantTransport.surfaceResult(retryResponse) : retryResponse;
|
|
2486
3470
|
}
|
|
2487
3471
|
/**
|
|
2488
3472
|
* Deliver an already-signed x402 payment header to the merchant and return
|
|
@@ -2507,7 +3491,7 @@ var HavenClient = class {
|
|
|
2507
3491
|
* and before delivering the X-PAYMENT header, so the merchant's
|
|
2508
3492
|
* balanceOf(delegate) / transferWithAuthorization verification sees the funded
|
|
2509
3493
|
* balance — otherwise it rejects with "Payment verification failed". The
|
|
2510
|
-
* SDK's local path already does this (see
|
|
3494
|
+
* SDK's local path already does this (see `X402FundingLeg.authorize`); the hosted
|
|
2511
3495
|
* split flow regressed when the 5→3 collapse removed the incidental
|
|
2512
3496
|
* inter-call latency that used to mask it.
|
|
2513
3497
|
*
|
|
@@ -2524,28 +3508,25 @@ var HavenClient = class {
|
|
|
2524
3508
|
*/
|
|
2525
3509
|
async ensureFundingConfirmed(paymentId, fundingTxHash) {
|
|
2526
3510
|
const status = await this.getPaymentStatus(paymentId);
|
|
2527
|
-
await this.waitForFundingTx(fundingTxHash ?? status.txHash ?? void 0, status.chainId);
|
|
3511
|
+
await this.fundingLeg.waitForFundingTx(fundingTxHash ?? status.txHash ?? void 0, status.chainId);
|
|
2528
3512
|
}
|
|
2529
3513
|
async completeX402MerchantCall(input) {
|
|
2530
|
-
const evidenceContext = await this.
|
|
3514
|
+
const evidenceContext = await this.merchantCompletion.resolveCompletionContext({
|
|
2531
3515
|
paymentId: input.paymentId,
|
|
2532
3516
|
url: input.url,
|
|
2533
3517
|
noFundingLeg: input.noFundingLeg === true
|
|
2534
3518
|
});
|
|
2535
3519
|
const fundingTxHash = evidenceContext.txHash;
|
|
2536
|
-
const shouldHandshakeMcp = isMcpUrl(input.url) || input.mcpTransport?.handshakeRequired === true;
|
|
2537
|
-
const x402Wallet = shouldHandshakeMcp ? await this.
|
|
3520
|
+
const shouldHandshakeMcp = this.merchantTransport.isMcpUrl(input.url) || input.mcpTransport?.handshakeRequired === true;
|
|
3521
|
+
const x402Wallet = shouldHandshakeMcp ? await this.merchantCompletion.resolveWalletForMerchantCall() : x402PayerAddress(this.delegateAddress, this.x402Wallet);
|
|
2538
3522
|
let mcpSessionId;
|
|
2539
3523
|
if (shouldHandshakeMcp) {
|
|
2540
|
-
mcpSessionId = await this.
|
|
3524
|
+
mcpSessionId = await this.merchantTransport.initialize(input.url, input.init, x402Wallet);
|
|
2541
3525
|
}
|
|
2542
|
-
let requestInit =
|
|
2543
|
-
if (mcpSessionId) requestInit = this.
|
|
2544
|
-
const
|
|
2545
|
-
|
|
2546
|
-
requestInit = { ...requestInit, headers };
|
|
2547
|
-
const response = await this.merchantFetch(input.url, requestInit);
|
|
2548
|
-
const surfaced = mcpSessionId ? await this.surfaceMcpResult(response) : response;
|
|
3526
|
+
let requestInit = withX402Wallet(input.init, x402Wallet) ?? {};
|
|
3527
|
+
if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId);
|
|
3528
|
+
const response = await this.merchantTransport.deliverPayment(input.url, requestInit, input.paymentHeader);
|
|
3529
|
+
const surfaced = mcpSessionId ? await this.merchantTransport.surfaceResult(response) : response;
|
|
2549
3530
|
const protocolReceiptHeader = surfaced.headers.get("PAYMENT-RESPONSE") ?? void 0;
|
|
2550
3531
|
const settlement = parseMerchantSettlement(protocolReceiptHeader ?? null);
|
|
2551
3532
|
const text = await surfaced.text();
|
|
@@ -2557,7 +3538,7 @@ var HavenClient = class {
|
|
|
2557
3538
|
}
|
|
2558
3539
|
if (!surfaced.ok) {
|
|
2559
3540
|
if (!input.noFundingLeg && fundingTxHash) {
|
|
2560
|
-
await this.
|
|
3541
|
+
await this.merchantCompletion.recordRetryRejected({
|
|
2561
3542
|
rail: "x402",
|
|
2562
3543
|
paymentId: evidenceContext.paymentId,
|
|
2563
3544
|
txHash: fundingTxHash,
|
|
@@ -2575,7 +3556,7 @@ var HavenClient = class {
|
|
|
2575
3556
|
}
|
|
2576
3557
|
} else {
|
|
2577
3558
|
if (!input.noFundingLeg && fundingTxHash) {
|
|
2578
|
-
await this.
|
|
3559
|
+
await this.merchantCompletion.reportEvidence({
|
|
2579
3560
|
paymentId: evidenceContext.paymentId,
|
|
2580
3561
|
rail: "x402",
|
|
2581
3562
|
txHash: fundingTxHash,
|
|
@@ -2587,7 +3568,7 @@ var HavenClient = class {
|
|
|
2587
3568
|
protocolReceiptHeader
|
|
2588
3569
|
});
|
|
2589
3570
|
}
|
|
2590
|
-
await this.reportMerchantReceipt(evidenceContext.paymentId, surfaced);
|
|
3571
|
+
await this.merchantCompletion.reportMerchantReceipt(evidenceContext.paymentId, surfaced);
|
|
2591
3572
|
}
|
|
2592
3573
|
return {
|
|
2593
3574
|
status: surfaced.status,
|
|
@@ -2617,271 +3598,11 @@ var HavenClient = class {
|
|
|
2617
3598
|
arguments: raw.arguments ?? {},
|
|
2618
3599
|
...raw.mcp_transport ? {
|
|
2619
3600
|
mcpTransport: {
|
|
2620
|
-
handshakeRequired: raw.mcp_transport.handshake_required,
|
|
2621
|
-
source: raw.mcp_transport.source
|
|
2622
|
-
}
|
|
2623
|
-
} : {}
|
|
2624
|
-
};
|
|
2625
|
-
}
|
|
2626
|
-
async resolveX402MerchantCompletionContext(input) {
|
|
2627
|
-
const status = await this.getPaymentStatus(input.paymentId);
|
|
2628
|
-
if (status.rail !== "x402") {
|
|
2629
|
-
throw new HavenPaymentStateError(
|
|
2630
|
-
`Payment ${status.paymentId} is ${status.rail}, not x402.`,
|
|
2631
|
-
409,
|
|
2632
|
-
status
|
|
2633
|
-
);
|
|
2634
|
-
}
|
|
2635
|
-
const readyForMerchantCompletion = input.noFundingLeg ? status.kind === "payment_intent" && status.status === "submitted" : status.nextAction === AgentPaymentNextAction.RetryOriginalX402Request || status.kind === "payment_intent" && status.status === "confirmed" && status.phase === AgentPaymentPhase.PaymentConfirmed && status.nextAction === AgentPaymentNextAction.None;
|
|
2636
|
-
if (!readyForMerchantCompletion) {
|
|
2637
|
-
throw new HavenPaymentStateError(status.message, PAYMENT_STATE_STATUS_CODES[status.status] ?? 409, status);
|
|
2638
|
-
}
|
|
2639
|
-
if (!input.noFundingLeg && !status.txHash) {
|
|
2640
|
-
throw new HavenApiError(
|
|
2641
|
-
`x402 payment ${status.paymentId} is ready for merchant completion but has no Haven transaction hash.`,
|
|
2642
|
-
502,
|
|
2643
|
-
status,
|
|
2644
|
-
status.paymentId
|
|
2645
|
-
);
|
|
2646
|
-
}
|
|
2647
|
-
const approvedResourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null;
|
|
2648
|
-
if (approvedResourceUrl && approvedResourceUrl !== input.url) {
|
|
2649
|
-
throw new HavenApiError(
|
|
2650
|
-
"x402 merchant completion does not match the approved resource URL.",
|
|
2651
|
-
409,
|
|
2652
|
-
{ status, url: input.url },
|
|
2653
|
-
status.paymentId
|
|
2654
|
-
);
|
|
2655
|
-
}
|
|
2656
|
-
return {
|
|
2657
|
-
paymentId: status.paymentId,
|
|
2658
|
-
txHash: status.txHash,
|
|
2659
|
-
resourceUrl: approvedResourceUrl ?? input.url,
|
|
2660
|
-
merchantAddress: status.merchantAddress ?? status.x402?.merchantAddress ?? null
|
|
2661
|
-
};
|
|
2662
|
-
}
|
|
2663
|
-
async resolveX402WalletForMerchantCall() {
|
|
2664
|
-
const localWallet = this.x402PayerAddress();
|
|
2665
|
-
if (localWallet) return localWallet;
|
|
2666
|
-
try {
|
|
2667
|
-
const agent = await this.getAgent();
|
|
2668
|
-
return agent.delegateAddress ?? void 0;
|
|
2669
|
-
} catch {
|
|
2670
|
-
return void 0;
|
|
2671
|
-
}
|
|
2672
|
-
}
|
|
2673
|
-
// #1328: authorizeMachinePayment / authorizeMppDemoPayment / resumeAuthorizedMpp
|
|
2674
|
-
// / resumeMppPayment / fetchWithMachinePayment / retryMppRequest (the
|
|
2675
|
-
// MACHINE-PAYMENT-CHALLENGE / mpp_demo client surface) are retired — the
|
|
2676
|
-
// backend's POST /machine-payments/authorize refuses unconditionally now,
|
|
2677
|
-
// and MACHINE-PAYMENT-CHALLENGE was never produced by any other Haven
|
|
2678
|
-
// surface. Use the x402 flow (authorizeX402 / fetch / quoteX402 / payX402Quote)
|
|
2679
|
-
// for agent-to-merchant payments.
|
|
2680
|
-
assertCanResumeX402(status, paymentRequired, option) {
|
|
2681
|
-
if (status.rail !== "x402") {
|
|
2682
|
-
throw new HavenPaymentStateError(
|
|
2683
|
-
`Payment ${status.paymentId} is ${status.rail}, not x402.`,
|
|
2684
|
-
409,
|
|
2685
|
-
status
|
|
2686
|
-
);
|
|
2687
|
-
}
|
|
2688
|
-
if (status.nextAction !== AgentPaymentNextAction.RetryOriginalX402Request) {
|
|
2689
|
-
throw new HavenPaymentStateError(status.message, PAYMENT_STATE_STATUS_CODES[status.status] ?? 409, status);
|
|
2690
|
-
}
|
|
2691
|
-
if (!status.txHash) {
|
|
2692
|
-
throw new HavenApiError(
|
|
2693
|
-
`x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,
|
|
2694
|
-
502,
|
|
2695
|
-
status,
|
|
2696
|
-
status.paymentId
|
|
2697
|
-
);
|
|
2698
|
-
}
|
|
2699
|
-
if (status.resourceUrl && status.resourceUrl !== paymentRequired.resource.url) {
|
|
2700
|
-
throw new HavenApiError(
|
|
2701
|
-
"x402 resume request does not match the approved resource URL.",
|
|
2702
|
-
409,
|
|
2703
|
-
{ status, paymentRequired },
|
|
2704
|
-
status.paymentId
|
|
2705
|
-
);
|
|
2706
|
-
}
|
|
2707
|
-
if (status.merchantAddress && !sameAddress3(status.merchantAddress, option.payTo)) {
|
|
2708
|
-
throw new HavenApiError(
|
|
2709
|
-
"x402 resume request does not match the approved merchant.",
|
|
2710
|
-
409,
|
|
2711
|
-
{ status, selectedPayment: option },
|
|
2712
|
-
status.paymentId
|
|
2713
|
-
);
|
|
2714
|
-
}
|
|
2715
|
-
const optionChainId = chainIdFromNetwork(option.network);
|
|
2716
|
-
if (status.chainId && optionChainId && status.chainId !== optionChainId) {
|
|
2717
|
-
throw new HavenApiError(
|
|
2718
|
-
"x402 resume request does not match the approved network.",
|
|
2719
|
-
409,
|
|
2720
|
-
{ status, selectedPayment: option },
|
|
2721
|
-
status.paymentId
|
|
2722
|
-
);
|
|
2723
|
-
}
|
|
2724
|
-
if (status.token && status.token !== "USDC") {
|
|
2725
|
-
throw new HavenApiError(
|
|
2726
|
-
"x402 resume request does not match the approved token.",
|
|
2727
|
-
409,
|
|
2728
|
-
{ status, selectedPayment: option },
|
|
2729
|
-
status.paymentId
|
|
2730
|
-
);
|
|
2731
|
-
}
|
|
2732
|
-
const approvedAmount = status.amount ? normalizeDecimal(status.amount) : "";
|
|
2733
|
-
const requestedAmount = normalizeDecimal(decimalFromUsdcAtomic(x402AuthorizationAmount(option)));
|
|
2734
|
-
if (approvedAmount && approvedAmount !== requestedAmount) {
|
|
2735
|
-
throw new HavenApiError(
|
|
2736
|
-
"x402 resume request does not match the approved amount.",
|
|
2737
|
-
409,
|
|
2738
|
-
{ status, selectedPayment: option },
|
|
2739
|
-
status.paymentId
|
|
2740
|
-
);
|
|
2741
|
-
}
|
|
2742
|
-
}
|
|
2743
|
-
mapX402ReceiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult) {
|
|
2744
|
-
const txHash = execResult?.tx_hash ?? raw.tx_hash ?? "";
|
|
2745
|
-
const chainId = execResult?.chain_id ?? raw.chain_id ?? chainIdFromNetwork(option.network);
|
|
2746
|
-
const token = execResult?.token ?? raw.token ?? "USDC";
|
|
2747
|
-
const amount = execResult?.amount ?? raw.amount ?? decimalFromUsdcAtomic(x402AuthorizationAmount(option));
|
|
2748
|
-
const to = execResult?.to ?? raw.to ?? this.delegateAddress ?? "";
|
|
2749
|
-
const explorerUrl = execResult?.explorer_url ?? raw.explorer_url ?? explorerUrlOrEmpty(chainId, txHash);
|
|
2750
|
-
const merchantTo = execResult?.merchant_to ?? raw.merchant_to ?? option.payTo;
|
|
2751
|
-
const payer = raw.payer ?? raw.safe_address ?? raw.sign_data?.components.safe;
|
|
2752
|
-
return this.buildX402Receipt({
|
|
2753
|
-
paymentId: raw.payment_id,
|
|
2754
|
-
txHash,
|
|
2755
|
-
token,
|
|
2756
|
-
amount,
|
|
2757
|
-
to,
|
|
2758
|
-
resourceUrl: paymentRequired.resource.url,
|
|
2759
|
-
explorerUrl,
|
|
2760
|
-
accepted: option,
|
|
2761
|
-
paymentHeader,
|
|
2762
|
-
merchantTo,
|
|
2763
|
-
payer,
|
|
2764
|
-
chainId
|
|
2765
|
-
});
|
|
2766
|
-
}
|
|
2767
|
-
mapX402ReceiptFromStatus(paymentRequired, option, paymentHeader, status) {
|
|
2768
|
-
if (!status.txHash) {
|
|
2769
|
-
throw new HavenApiError(
|
|
2770
|
-
`x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,
|
|
2771
|
-
502,
|
|
2772
|
-
status,
|
|
2773
|
-
status.paymentId
|
|
2774
|
-
);
|
|
2775
|
-
}
|
|
2776
|
-
return this.buildX402Receipt({
|
|
2777
|
-
paymentId: status.paymentId,
|
|
2778
|
-
txHash: status.txHash,
|
|
2779
|
-
token: status.token || "USDC",
|
|
2780
|
-
amount: status.amount || decimalFromUsdcAtomic(x402AuthorizationAmount(option)),
|
|
2781
|
-
to: this.delegateAddress ?? "",
|
|
2782
|
-
resourceUrl: paymentRequired.resource.url,
|
|
2783
|
-
explorerUrl: explorerUrlOrEmpty(status.chainId, status.txHash),
|
|
2784
|
-
accepted: option,
|
|
2785
|
-
paymentHeader,
|
|
2786
|
-
merchantTo: status.merchantAddress ?? option.payTo,
|
|
2787
|
-
payer: this.x402Wallet,
|
|
2788
|
-
chainId: status.chainId || chainIdFromNetwork(option.network)
|
|
2789
|
-
});
|
|
2790
|
-
}
|
|
2791
|
-
buildX402Receipt(input) {
|
|
2792
|
-
const fundingExplorerUrl = input.explorerUrl || explorerUrlOrEmpty(input.chainId, input.txHash);
|
|
2793
|
-
return {
|
|
2794
|
-
success: true,
|
|
2795
|
-
paymentId: input.paymentId,
|
|
2796
|
-
txHash: input.txHash,
|
|
2797
|
-
token: input.token,
|
|
2798
|
-
amount: input.amount,
|
|
2799
|
-
to: input.to,
|
|
2800
|
-
resourceUrl: input.resourceUrl,
|
|
2801
|
-
explorerUrl: input.explorerUrl,
|
|
2802
|
-
accepted: input.accepted,
|
|
2803
|
-
paymentHeader: input.paymentHeader,
|
|
2804
|
-
merchantTo: input.merchantTo ?? input.accepted.payTo,
|
|
2805
|
-
payer: input.payer,
|
|
2806
|
-
chainId: input.chainId,
|
|
2807
|
-
haven: {
|
|
2808
|
-
paymentId: input.paymentId,
|
|
2809
|
-
fundingTxHash: input.txHash,
|
|
2810
|
-
fundingExplorerUrl
|
|
2811
|
-
},
|
|
2812
|
-
merchant: {
|
|
2813
|
-
payTo: input.merchantTo ?? input.accepted.payTo
|
|
2814
|
-
},
|
|
2815
|
-
x402: {
|
|
2816
|
-
amount: x402AuthorizationAmount(input.accepted),
|
|
2817
|
-
token: input.token,
|
|
2818
|
-
network: input.accepted.network,
|
|
2819
|
-
asset: input.accepted.asset,
|
|
2820
|
-
resource: input.accepted.resource ?? input.resourceUrl
|
|
2821
|
-
}
|
|
2822
|
-
};
|
|
2823
|
-
}
|
|
2824
|
-
async createStandardX402Header(paymentRequired, option) {
|
|
2825
|
-
if (!this.delegateKey) {
|
|
2826
|
-
throw new HavenSigningError("delegateKey is required to sign x402 payment headers.");
|
|
2827
|
-
}
|
|
2828
|
-
const account = accounts.privateKeyToAccount(this.delegateKey);
|
|
2829
|
-
const requirements = toStandardPaymentRequirements(paymentRequired, option);
|
|
2830
|
-
const header = await schemes.exact.evm.createPaymentHeader(
|
|
2831
|
-
account,
|
|
2832
|
-
paymentRequired.x402Version,
|
|
2833
|
-
requirements
|
|
2834
|
-
);
|
|
2835
|
-
if (paymentRequired.x402Version < 2) return header;
|
|
2836
|
-
const payment = decodeBase64Json(header);
|
|
2837
|
-
return encodeBase64Json({
|
|
2838
|
-
x402Version: paymentRequired.x402Version,
|
|
2839
|
-
accepted: option,
|
|
2840
|
-
payload: payment.payload
|
|
2841
|
-
});
|
|
2842
|
-
}
|
|
2843
|
-
cacheX402Receipt(idempotencyKey, paymentHeader, receipt) {
|
|
2844
|
-
const expiresAt = getPaymentHeaderValidBefore(paymentHeader);
|
|
2845
|
-
if (expiresAt > Date.now()) {
|
|
2846
|
-
this.x402ReceiptCache.set(idempotencyKey, { expiresAt, receipt });
|
|
2847
|
-
}
|
|
2848
|
-
}
|
|
2849
|
-
async recordMerchantRetryRejected(input) {
|
|
2850
|
-
try {
|
|
2851
|
-
await this.post("/machine-payments/reconciliation-events", {
|
|
2852
|
-
paymentId: input.paymentId,
|
|
2853
|
-
rail: input.rail,
|
|
2854
|
-
eventType: "merchant_retry_rejected_after_payment",
|
|
2855
|
-
txHash: input.txHash,
|
|
2856
|
-
reason: `Merchant returned HTTP ${input.merchant.merchant_status} after Haven payment confirmation`,
|
|
2857
|
-
details: {
|
|
2858
|
-
resource_url: input.resourceUrl,
|
|
2859
|
-
retry_status: input.merchant.merchant_status,
|
|
2860
|
-
retry_body: input.merchant.merchant_body.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,
|
|
2861
|
-
...input.details
|
|
2862
|
-
}
|
|
2863
|
-
});
|
|
2864
|
-
} catch {
|
|
2865
|
-
}
|
|
2866
|
-
}
|
|
2867
|
-
async reportMachinePaymentEvidence(input) {
|
|
2868
|
-
try {
|
|
2869
|
-
await this.post("/machine-payments/evidence", {
|
|
2870
|
-
paymentId: input.paymentId,
|
|
2871
|
-
rail: input.rail,
|
|
2872
|
-
txHash: input.txHash,
|
|
2873
|
-
resourceUrl: input.resourceUrl,
|
|
2874
|
-
merchantStatus: input.merchantStatus,
|
|
2875
|
-
challengePayload: input.challengePayload,
|
|
2876
|
-
selectedPayment: input.selectedPayment,
|
|
2877
|
-
paymentProofHeaderName: input.paymentProofHeaderName,
|
|
2878
|
-
paymentProofHeader: input.paymentProofHeader,
|
|
2879
|
-
protocolReceiptHeaderName: input.protocolReceiptHeaderName,
|
|
2880
|
-
protocolReceiptHeader: input.protocolReceiptHeader,
|
|
2881
|
-
protocolReceiptPayload: input.protocolReceiptHeader ? parseProtocolReceiptHeader(input.protocolReceiptHeader) : void 0
|
|
2882
|
-
});
|
|
2883
|
-
} catch {
|
|
2884
|
-
}
|
|
3601
|
+
handshakeRequired: raw.mcp_transport.handshake_required,
|
|
3602
|
+
source: raw.mcp_transport.source
|
|
3603
|
+
}
|
|
3604
|
+
} : {}
|
|
3605
|
+
};
|
|
2885
3606
|
}
|
|
2886
3607
|
/**
|
|
2887
3608
|
* Wait for a funding tx to be mined with ≥1 confirmation before the
|
|
@@ -2892,264 +3613,9 @@ var HavenClient = class {
|
|
|
2892
3613
|
* backend has already confirmed on-chain submission and callers accept the
|
|
2893
3614
|
* small propagation window as a trade-off for not configuring an RPC URL.
|
|
2894
3615
|
*/
|
|
2895
|
-
async waitForFundingTx(txHash, chainId, timeoutMs = 3e4) {
|
|
2896
|
-
if (!txHash || !chainId) return;
|
|
2897
|
-
const rpcUrl = this.chainRpcs[chainId];
|
|
2898
|
-
if (!rpcUrl) return;
|
|
2899
|
-
const provider = createJsonRpcProvider(rpcUrl);
|
|
2900
|
-
const onChainReceipt = await provider.waitForTransaction(txHash, 1, timeoutMs);
|
|
2901
|
-
if (!onChainReceipt || onChainReceipt.status !== 1) {
|
|
2902
|
-
throw new HavenApiError(
|
|
2903
|
-
"Funding tx did not confirm on-chain within the timeout window.",
|
|
2904
|
-
500,
|
|
2905
|
-
{ txHash, chainId }
|
|
2906
|
-
);
|
|
2907
|
-
}
|
|
2908
|
-
}
|
|
2909
|
-
/**
|
|
2910
|
-
* Can the delegate EOA still fund an authorization for `amountAtomic`?
|
|
2911
|
-
*
|
|
2912
|
-
* #1521: the only question that separates a legitimate resume (funding
|
|
2913
|
-
* confirmed, merchant never paid — the delegate still holds the money) from
|
|
2914
|
-
* a replayed settled payment (funding confirmed, merchant paid, delegate
|
|
2915
|
-
* spent). The intent's own `status: 'confirmed'` is identical in both.
|
|
2916
|
-
*
|
|
2917
|
-
* The balance is asked of the CHAIN rather than of Haven's bookkeeping on
|
|
2918
|
-
* purpose: the merchant-settlement evidence record is written by this SDK
|
|
2919
|
-
* *after* the merchant call, so a client that dies between the two leaves
|
|
2920
|
-
* the backend believing the merchant was never paid — the exact case the
|
|
2921
|
-
* discriminator has to get right. The chain cannot be behind in that way.
|
|
2922
|
-
*
|
|
2923
|
-
* Returns `null` — never a guess — when `chainRpcs` has no entry for the
|
|
2924
|
-
* chain or the read fails. Callers must treat that as "unverifiable", not
|
|
2925
|
-
* as "funded".
|
|
2926
|
-
*/
|
|
2927
|
-
async delegateCanFund(chainId, tokenAddress, amountAtomic, timeoutMs = 1e4) {
|
|
2928
|
-
if (!chainId || !this.delegateAddress) return null;
|
|
2929
|
-
const rpcUrl = this.chainRpcs[chainId];
|
|
2930
|
-
if (!rpcUrl) return null;
|
|
2931
|
-
try {
|
|
2932
|
-
const provider = createJsonRpcProvider(rpcUrl);
|
|
2933
|
-
const token = createErc20Contract(
|
|
2934
|
-
tokenAddress,
|
|
2935
|
-
["function balanceOf(address) view returns (uint256)"],
|
|
2936
|
-
provider
|
|
2937
|
-
);
|
|
2938
|
-
const balance = await Promise.race([
|
|
2939
|
-
token.balanceOf(this.delegateAddress),
|
|
2940
|
-
new Promise((resolve) => setTimeout(() => resolve(null), timeoutMs).unref?.())
|
|
2941
|
-
]);
|
|
2942
|
-
if (balance === null) return null;
|
|
2943
|
-
return balance >= BigInt(amountAtomic);
|
|
2944
|
-
} catch {
|
|
2945
|
-
return null;
|
|
2946
|
-
}
|
|
2947
|
-
}
|
|
2948
3616
|
throwIfNonSignableAuthorizationState(label, raw) {
|
|
2949
3617
|
if (raw.status === "pending_signature") return;
|
|
2950
|
-
|
|
2951
|
-
}
|
|
2952
|
-
throwPaymentStateError(label, raw) {
|
|
2953
|
-
const statusCode = PAYMENT_STATE_STATUS_CODES[raw.status] ?? 502;
|
|
2954
|
-
const state = this.paymentStateFromRaw(label, raw);
|
|
2955
|
-
if (state) {
|
|
2956
|
-
throw new HavenPaymentStateError(state.message, statusCode, state, raw);
|
|
2957
|
-
}
|
|
2958
|
-
if (raw.status === "pending_approval") {
|
|
2959
|
-
throw new HavenApiError(
|
|
2960
|
-
`${label} exceeds the on-chain allowance and was queued for owner approval (payment_id: ${raw.payment_id}).`,
|
|
2961
|
-
statusCode,
|
|
2962
|
-
raw
|
|
2963
|
-
);
|
|
2964
|
-
}
|
|
2965
|
-
if (raw.status === "expired") {
|
|
2966
|
-
throw new HavenApiError(
|
|
2967
|
-
`${label} expired before it could be completed (payment_id: ${raw.payment_id}).`,
|
|
2968
|
-
statusCode,
|
|
2969
|
-
raw
|
|
2970
|
-
);
|
|
2971
|
-
}
|
|
2972
|
-
const paymentId = raw.payment_id ? ` (payment_id: ${raw.payment_id})` : "";
|
|
2973
|
-
const message = raw.error ?? `${label} ${raw.status}${paymentId}`;
|
|
2974
|
-
throw new HavenApiError(message, statusCode, raw);
|
|
2975
|
-
}
|
|
2976
|
-
paymentStateFromRaw(label, raw) {
|
|
2977
|
-
if (!raw.payment_id || !raw.status) return null;
|
|
2978
|
-
const phase = raw.phase ?? phaseForStatus(raw.status);
|
|
2979
|
-
const nextAction = raw.next_action ?? nextActionForStatus(raw.status);
|
|
2980
|
-
if (!phase || !nextAction) return null;
|
|
2981
|
-
const amount = raw.amount ?? raw.requested ?? "";
|
|
2982
|
-
const token = raw.token ?? "";
|
|
2983
|
-
const message = raw.message ?? raw.error ?? messageForState(label, raw.status, raw.payment_id, nextAction);
|
|
2984
|
-
return {
|
|
2985
|
-
paymentId: raw.payment_id,
|
|
2986
|
-
kind: raw.kind === "payment_intent" ? "payment_intent" : "approval_request",
|
|
2987
|
-
rail: raw.rail ?? "direct",
|
|
2988
|
-
status: raw.status === "pending" ? "pending_approval" : raw.status,
|
|
2989
|
-
phase,
|
|
2990
|
-
nextAction,
|
|
2991
|
-
amount,
|
|
2992
|
-
token,
|
|
2993
|
-
resourceUrl: raw.resource_url ?? null,
|
|
2994
|
-
merchantAddress: raw.merchant_address ?? raw.merchant_to ?? null,
|
|
2995
|
-
txHash: raw.tx_hash ?? null,
|
|
2996
|
-
expiresAt: raw.expires_at ?? "",
|
|
2997
|
-
chainId: raw.chain_id ?? 0,
|
|
2998
|
-
message,
|
|
2999
|
-
amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? raw.mpp?.amount_atomic ?? null,
|
|
3000
|
-
asset: raw.asset ?? raw.x402?.asset ?? raw.mpp?.asset ?? null,
|
|
3001
|
-
network: raw.network ?? raw.x402?.network ?? raw.mpp?.network ?? null,
|
|
3002
|
-
description: raw.description ?? raw.x402?.description ?? raw.mpp?.description ?? null,
|
|
3003
|
-
idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? raw.mpp?.idempotency_key ?? null,
|
|
3004
|
-
x402: raw.x402 ? {
|
|
3005
|
-
amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,
|
|
3006
|
-
asset: raw.x402.asset ?? raw.asset ?? null,
|
|
3007
|
-
network: raw.x402.network ?? raw.network ?? null,
|
|
3008
|
-
resourceUrl: raw.x402.resource_url ?? raw.resource_url ?? null,
|
|
3009
|
-
merchantAddress: raw.x402.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,
|
|
3010
|
-
description: raw.x402.description ?? raw.description ?? null,
|
|
3011
|
-
idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null
|
|
3012
|
-
} : void 0,
|
|
3013
|
-
mpp: raw.mpp ? {
|
|
3014
|
-
amountAtomic: raw.mpp.amount_atomic ?? raw.amount_atomic ?? null,
|
|
3015
|
-
asset: raw.mpp.asset ?? raw.asset ?? null,
|
|
3016
|
-
network: raw.mpp.network ?? raw.network ?? null,
|
|
3017
|
-
resourceUrl: raw.mpp.resource_url ?? raw.resource_url ?? null,
|
|
3018
|
-
merchantAddress: raw.mpp.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,
|
|
3019
|
-
description: raw.mpp.description ?? raw.description ?? null,
|
|
3020
|
-
idempotencyKey: raw.mpp.idempotency_key ?? raw.idempotency_key ?? null,
|
|
3021
|
-
challengeId: raw.mpp.challenge_id ?? raw.challenge_id ?? null
|
|
3022
|
-
} : void 0
|
|
3023
|
-
};
|
|
3024
|
-
}
|
|
3025
|
-
x402PayerAddress() {
|
|
3026
|
-
return this.delegateAddress ?? this.x402Wallet;
|
|
3027
|
-
}
|
|
3028
|
-
snapshotX402Request(url, init) {
|
|
3029
|
-
return {
|
|
3030
|
-
url,
|
|
3031
|
-
method: init?.method ?? "GET",
|
|
3032
|
-
headers: Array.from(new Headers(init?.headers).entries()),
|
|
3033
|
-
body: this.snapshotRequestBody(init?.body)
|
|
3034
|
-
};
|
|
3035
|
-
}
|
|
3036
|
-
snapshotRequestBody(body) {
|
|
3037
|
-
if (body == null) return void 0;
|
|
3038
|
-
if (typeof body === "string") return body;
|
|
3039
|
-
if (body instanceof URLSearchParams) return body.toString();
|
|
3040
|
-
throw new HavenApiError(
|
|
3041
|
-
"Quote helpers can only capture resumable request bodies that are strings or URLSearchParams. For streams, blobs, or binary bodies, preserve the original request yourself and call the matching resume method with fresh init.",
|
|
3042
|
-
400
|
|
3043
|
-
);
|
|
3044
|
-
}
|
|
3045
|
-
requestInitFromSnapshot(request) {
|
|
3046
|
-
return {
|
|
3047
|
-
method: request.method,
|
|
3048
|
-
headers: request.headers,
|
|
3049
|
-
body: request.body
|
|
3050
|
-
};
|
|
3051
|
-
}
|
|
3052
|
-
withX402Wallet(init, wallet = this.x402PayerAddress()) {
|
|
3053
|
-
if (!wallet) return init;
|
|
3054
|
-
const headers = new Headers(init?.headers);
|
|
3055
|
-
if (!headers.has("x402-wallet")) {
|
|
3056
|
-
headers.set("x402-wallet", wallet);
|
|
3057
|
-
}
|
|
3058
|
-
return {
|
|
3059
|
-
...init,
|
|
3060
|
-
headers
|
|
3061
|
-
};
|
|
3062
|
-
}
|
|
3063
|
-
buildX402Quote(paymentRequired, request, idempotencyKey, mcpTransport) {
|
|
3064
|
-
const option = selectStandardPaymentOption(paymentRequired.accepts);
|
|
3065
|
-
if (!option) {
|
|
3066
|
-
throw new HavenApiError(
|
|
3067
|
-
"No compatible payment option found in x402 requirements. Haven supports standard x402 exact payments on Base USDC.",
|
|
3068
|
-
400
|
|
3069
|
-
);
|
|
3070
|
-
}
|
|
3071
|
-
const token = resolveTokenFromAddress(option.asset, option.network);
|
|
3072
|
-
return {
|
|
3073
|
-
rail: "x402",
|
|
3074
|
-
idempotencyKey: idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option),
|
|
3075
|
-
paymentRequired,
|
|
3076
|
-
accepted: option,
|
|
3077
|
-
request,
|
|
3078
|
-
...mcpTransport ? { mcpTransport } : {},
|
|
3079
|
-
resourceUrl: paymentRequired.resource.url,
|
|
3080
|
-
description: paymentRequired.resource.description ?? option.description ?? null,
|
|
3081
|
-
mimeType: paymentRequired.resource.mimeType ?? option.mimeType ?? null,
|
|
3082
|
-
amountAtomic: x402AuthorizationAmount(option),
|
|
3083
|
-
amount: decimalFromUsdcAtomic(x402AuthorizationAmount(option)),
|
|
3084
|
-
token: token?.symbol ?? "USDC",
|
|
3085
|
-
// #1351: null when the asset is unrecognised on this network — the
|
|
3086
|
-
// `token` fallback above is a LABEL, not evidence of 6 decimals, and a
|
|
3087
|
-
// human-denominated cap must fail closed rather than convert against a
|
|
3088
|
-
// guess. Same resolution as `token`, so the two never disagree.
|
|
3089
|
-
decimals: token?.decimals ?? null,
|
|
3090
|
-
asset: option.asset,
|
|
3091
|
-
network: option.network,
|
|
3092
|
-
chainId: chainIdOrNull(option.network),
|
|
3093
|
-
merchantAddress: option.payTo,
|
|
3094
|
-
maxTimeoutSeconds: option.maxTimeoutSeconds
|
|
3095
|
-
};
|
|
3096
|
-
}
|
|
3097
|
-
async detectX402McpTransport(url, paymentRequired, response) {
|
|
3098
|
-
if (isMcpUrl(url)) {
|
|
3099
|
-
return { handshakeRequired: true, source: "path" };
|
|
3100
|
-
}
|
|
3101
|
-
if (paymentRequired.extensions?.bazaar != null) {
|
|
3102
|
-
return { handshakeRequired: true, source: "bazaar" };
|
|
3103
|
-
}
|
|
3104
|
-
if (await responseHasBazaarExtension(response)) {
|
|
3105
|
-
return { handshakeRequired: true, source: "bazaar" };
|
|
3106
|
-
}
|
|
3107
|
-
return void 0;
|
|
3108
|
-
}
|
|
3109
|
-
buildX402ResumeState(input) {
|
|
3110
|
-
const token = resolveTokenFromAddress(input.accepted.asset, input.accepted.network);
|
|
3111
|
-
return {
|
|
3112
|
-
rail: "x402",
|
|
3113
|
-
paymentId: input.paymentId,
|
|
3114
|
-
idempotencyKey: input.idempotencyKey,
|
|
3115
|
-
paymentRequired: input.paymentRequired,
|
|
3116
|
-
accepted: input.accepted,
|
|
3117
|
-
url: input.request?.url ?? input.paymentRequired.resource.url,
|
|
3118
|
-
request: input.request,
|
|
3119
|
-
resourceUrl: input.paymentRequired.resource.url,
|
|
3120
|
-
description: input.paymentRequired.resource.description ?? input.accepted.description ?? null,
|
|
3121
|
-
amountAtomic: x402AuthorizationAmount(input.accepted),
|
|
3122
|
-
amount: decimalFromUsdcAtomic(x402AuthorizationAmount(input.accepted)),
|
|
3123
|
-
token: token?.symbol ?? "USDC",
|
|
3124
|
-
asset: input.accepted.asset,
|
|
3125
|
-
network: input.accepted.network,
|
|
3126
|
-
chainId: chainIdOrNull(input.accepted.network),
|
|
3127
|
-
merchantAddress: input.accepted.payTo
|
|
3128
|
-
};
|
|
3129
|
-
}
|
|
3130
|
-
// #1328: attachResumeState's 'mpp' branch (buildMppQuote / buildMppResumeState
|
|
3131
|
-
// / attachMppResumeState) is retired along with the rest of the MPP-demo
|
|
3132
|
-
// client surface — every remaining caller passes rail: 'x402' only, so this
|
|
3133
|
-
// is now a direct alias for attachX402ResumeState rather than a dispatcher.
|
|
3134
|
-
attachResumeState(err, input) {
|
|
3135
|
-
this.attachX402ResumeState(
|
|
3136
|
-
err,
|
|
3137
|
-
input.paymentRequired,
|
|
3138
|
-
input.accepted,
|
|
3139
|
-
input.idempotencyKey,
|
|
3140
|
-
input.request
|
|
3141
|
-
);
|
|
3142
|
-
}
|
|
3143
|
-
attachX402ResumeState(err, paymentRequired, accepted, idempotencyKey, request) {
|
|
3144
|
-
if (!(err instanceof HavenPaymentStateError)) return;
|
|
3145
|
-
if (err.state.rail !== "x402") return;
|
|
3146
|
-
err.resumeState = this.buildX402ResumeState({
|
|
3147
|
-
paymentId: err.state.paymentId,
|
|
3148
|
-
paymentRequired,
|
|
3149
|
-
accepted,
|
|
3150
|
-
idempotencyKey,
|
|
3151
|
-
request
|
|
3152
|
-
});
|
|
3618
|
+
throwPaymentStateError(label, raw);
|
|
3153
3619
|
}
|
|
3154
3620
|
// ── Tool Execution (for agent frameworks) ────────────────────────
|
|
3155
3621
|
/**
|
|
@@ -3181,19 +3647,19 @@ var HavenClient = class {
|
|
|
3181
3647
|
error: result.errorMessage
|
|
3182
3648
|
};
|
|
3183
3649
|
} catch (err) {
|
|
3184
|
-
return
|
|
3650
|
+
return toolError(err);
|
|
3185
3651
|
}
|
|
3186
3652
|
}
|
|
3187
3653
|
if (toolName === "authorize_x402_payment") {
|
|
3188
3654
|
const { url, payTo, amount, asset, network, description, idempotencyKey } = input;
|
|
3189
3655
|
try {
|
|
3190
3656
|
const receipt = await this.authorizeX402(
|
|
3191
|
-
|
|
3657
|
+
toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),
|
|
3192
3658
|
{ idempotencyKey }
|
|
3193
3659
|
);
|
|
3194
|
-
return
|
|
3660
|
+
return x402ToolReceipt(receipt);
|
|
3195
3661
|
} catch (err) {
|
|
3196
|
-
return
|
|
3662
|
+
return toolError(err);
|
|
3197
3663
|
}
|
|
3198
3664
|
}
|
|
3199
3665
|
if (toolName === "resume_x402_payment") {
|
|
@@ -3201,12 +3667,12 @@ var HavenClient = class {
|
|
|
3201
3667
|
try {
|
|
3202
3668
|
const receipt = await this.resumeAuthorizedX402({
|
|
3203
3669
|
paymentId: payment_id,
|
|
3204
|
-
paymentRequired:
|
|
3670
|
+
paymentRequired: toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),
|
|
3205
3671
|
idempotencyKey
|
|
3206
3672
|
});
|
|
3207
|
-
return
|
|
3673
|
+
return x402ToolReceipt(receipt);
|
|
3208
3674
|
} catch (err) {
|
|
3209
|
-
return
|
|
3675
|
+
return toolError(err);
|
|
3210
3676
|
}
|
|
3211
3677
|
}
|
|
3212
3678
|
if (toolName === "get_payment_status") {
|
|
@@ -3241,302 +3707,17 @@ var HavenClient = class {
|
|
|
3241
3707
|
}
|
|
3242
3708
|
throw new Error(`Unknown tool: ${toolName}`);
|
|
3243
3709
|
}
|
|
3244
|
-
toolX402PaymentRequired(input) {
|
|
3245
|
-
return {
|
|
3246
|
-
x402Version: 2,
|
|
3247
|
-
resource: { url: input.url, description: input.description },
|
|
3248
|
-
accepts: [
|
|
3249
|
-
{
|
|
3250
|
-
scheme: "exact",
|
|
3251
|
-
network: input.network,
|
|
3252
|
-
amount: input.amount,
|
|
3253
|
-
asset: input.asset,
|
|
3254
|
-
payTo: input.payTo,
|
|
3255
|
-
maxTimeoutSeconds: 30
|
|
3256
|
-
}
|
|
3257
|
-
]
|
|
3258
|
-
};
|
|
3259
|
-
}
|
|
3260
|
-
x402ToolReceipt(receipt) {
|
|
3261
|
-
return {
|
|
3262
|
-
success: true,
|
|
3263
|
-
payment_id: receipt.paymentId,
|
|
3264
|
-
tx_hash: receipt.txHash,
|
|
3265
|
-
token: receipt.token,
|
|
3266
|
-
amount: receipt.amount,
|
|
3267
|
-
to: receipt.to,
|
|
3268
|
-
resource_url: receipt.resourceUrl,
|
|
3269
|
-
explorer_url: receipt.explorerUrl,
|
|
3270
|
-
payment_header: receipt.paymentHeader,
|
|
3271
|
-
merchant_to: receipt.merchantTo,
|
|
3272
|
-
payer: receipt.payer,
|
|
3273
|
-
chain_id: receipt.chainId,
|
|
3274
|
-
haven: receipt.haven,
|
|
3275
|
-
merchant: receipt.merchant,
|
|
3276
|
-
x402: receipt.x402
|
|
3277
|
-
};
|
|
3278
|
-
}
|
|
3279
|
-
toolError(err) {
|
|
3280
|
-
if (err instanceof HavenPaymentStateError) {
|
|
3281
|
-
return {
|
|
3282
|
-
success: false,
|
|
3283
|
-
payment_id: err.state.paymentId,
|
|
3284
|
-
kind: err.state.kind,
|
|
3285
|
-
rail: err.state.rail,
|
|
3286
|
-
status: err.state.status,
|
|
3287
|
-
phase: err.state.phase,
|
|
3288
|
-
next_action: err.state.nextAction,
|
|
3289
|
-
tx_hash: err.state.txHash,
|
|
3290
|
-
token: err.state.token,
|
|
3291
|
-
amount: err.state.amount,
|
|
3292
|
-
resource_url: err.state.resourceUrl,
|
|
3293
|
-
merchant_address: err.state.merchantAddress,
|
|
3294
|
-
amount_atomic: err.state.amountAtomic,
|
|
3295
|
-
asset: err.state.asset,
|
|
3296
|
-
network: err.state.network,
|
|
3297
|
-
description: err.state.description,
|
|
3298
|
-
idempotency_key: err.state.idempotencyKey,
|
|
3299
|
-
x402: err.state.x402 ? {
|
|
3300
|
-
amount_atomic: err.state.x402.amountAtomic,
|
|
3301
|
-
asset: err.state.x402.asset,
|
|
3302
|
-
network: err.state.x402.network,
|
|
3303
|
-
resource_url: err.state.x402.resourceUrl,
|
|
3304
|
-
merchant_address: err.state.x402.merchantAddress,
|
|
3305
|
-
description: err.state.x402.description,
|
|
3306
|
-
idempotency_key: err.state.x402.idempotencyKey
|
|
3307
|
-
} : void 0,
|
|
3308
|
-
mpp: err.state.mpp ? {
|
|
3309
|
-
amount_atomic: err.state.mpp.amountAtomic,
|
|
3310
|
-
asset: err.state.mpp.asset,
|
|
3311
|
-
network: err.state.mpp.network,
|
|
3312
|
-
resource_url: err.state.mpp.resourceUrl,
|
|
3313
|
-
merchant_address: err.state.mpp.merchantAddress,
|
|
3314
|
-
description: err.state.mpp.description,
|
|
3315
|
-
idempotency_key: err.state.mpp.idempotencyKey,
|
|
3316
|
-
challenge_id: err.state.mpp.challengeId
|
|
3317
|
-
} : void 0,
|
|
3318
|
-
resume_state: err.resumeState,
|
|
3319
|
-
expires_at: err.state.expiresAt,
|
|
3320
|
-
chain_id: err.state.chainId,
|
|
3321
|
-
message: err.state.message,
|
|
3322
|
-
error: err.message
|
|
3323
|
-
};
|
|
3324
|
-
}
|
|
3325
|
-
if (err instanceof HavenApiError) {
|
|
3326
|
-
return {
|
|
3327
|
-
success: false,
|
|
3328
|
-
status_code: err.statusCode,
|
|
3329
|
-
error: err.message,
|
|
3330
|
-
body: err.body
|
|
3331
|
-
};
|
|
3332
|
-
}
|
|
3333
|
-
return {
|
|
3334
|
-
success: false,
|
|
3335
|
-
error: err instanceof Error ? err.message : String(err)
|
|
3336
|
-
};
|
|
3337
|
-
}
|
|
3338
3710
|
// ── HTTP Helpers ─────────────────────────────────────────────────
|
|
3339
3711
|
async post(path, body) {
|
|
3340
|
-
return this.
|
|
3712
|
+
return this.havenApi.post(path, body);
|
|
3341
3713
|
}
|
|
3342
3714
|
async get(path) {
|
|
3343
|
-
return this.
|
|
3344
|
-
}
|
|
3345
|
-
/**
|
|
3346
|
-
* #1300: every MERCHANT-facing fetch goes through here. Haven API calls
|
|
3347
|
-
* have always been bounded (request() below); the merchant probes/retries
|
|
3348
|
-
* called globalThis.fetch bare, so a slow-loris merchant could hold a tool
|
|
3349
|
-
* call open forever. A caller-supplied signal still applies (combined via
|
|
3350
|
-
* AbortSignal.any); a timeout abort surfaces as a clear HavenApiError 504
|
|
3351
|
-
* naming the URL rather than a bare AbortError.
|
|
3352
|
-
*/
|
|
3353
|
-
async merchantFetch(url, init = {}, timeoutMs = this.merchantTimeout) {
|
|
3354
|
-
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
3355
|
-
const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal;
|
|
3356
|
-
try {
|
|
3357
|
-
return await globalThis.fetch(url, { ...init, signal });
|
|
3358
|
-
} catch (err) {
|
|
3359
|
-
if (timeoutSignal.aborted) {
|
|
3360
|
-
throw new MerchantTimeoutError(`Merchant request timed out after ${timeoutMs}ms: ${url}`);
|
|
3361
|
-
}
|
|
3362
|
-
throw err;
|
|
3363
|
-
}
|
|
3364
|
-
}
|
|
3365
|
-
async request(method, path, body) {
|
|
3366
|
-
const url = `${this.baseUrl}${path}`;
|
|
3367
|
-
const controller = new AbortController();
|
|
3368
|
-
const timeout = setTimeout(() => controller.abort(), this.requestTimeout);
|
|
3369
|
-
try {
|
|
3370
|
-
const contextHeaders = this.requestContext.getStore()?.headers ?? {};
|
|
3371
|
-
const res = await fetch(url, {
|
|
3372
|
-
method,
|
|
3373
|
-
headers: {
|
|
3374
|
-
"Content-Type": "application/json",
|
|
3375
|
-
"Authorization": `Bearer ${this.apiKey}`,
|
|
3376
|
-
...this.defaultHeaders,
|
|
3377
|
-
...contextHeaders
|
|
3378
|
-
},
|
|
3379
|
-
body: body ? JSON.stringify(body) : void 0,
|
|
3380
|
-
signal: controller.signal
|
|
3381
|
-
});
|
|
3382
|
-
const data = await res.json();
|
|
3383
|
-
if (!res.ok) {
|
|
3384
|
-
const record = data;
|
|
3385
|
-
const errorText = typeof record.error === "string" ? record.error : void 0;
|
|
3386
|
-
const rawDetails = record.details ?? record.detail;
|
|
3387
|
-
const detailsText = typeof rawDetails === "string" ? rawDetails : rawDetails != null ? JSON.stringify(rawDetails) : void 0;
|
|
3388
|
-
const message = errorText && detailsText ? `${errorText}: ${detailsText}` : errorText ?? detailsText ?? `API request failed`;
|
|
3389
|
-
throw new HavenApiError(message, res.status, data);
|
|
3390
|
-
}
|
|
3391
|
-
return data;
|
|
3392
|
-
} catch (err) {
|
|
3393
|
-
if (err instanceof HavenApiError) throw err;
|
|
3394
|
-
if (err instanceof Error && err.name === "AbortError") {
|
|
3395
|
-
throw new HavenApiError(`Request to ${path} timed out`, 408);
|
|
3396
|
-
}
|
|
3397
|
-
throw new HavenApiError(
|
|
3398
|
-
`Request to ${path} failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
3399
|
-
0
|
|
3400
|
-
);
|
|
3401
|
-
} finally {
|
|
3402
|
-
clearTimeout(timeout);
|
|
3403
|
-
}
|
|
3404
|
-
}
|
|
3405
|
-
// ── Mapping Helpers ──────────────────────────────────────────────
|
|
3406
|
-
mapPaymentResult(raw) {
|
|
3407
|
-
return {
|
|
3408
|
-
paymentId: raw.payment_id,
|
|
3409
|
-
status: raw.status,
|
|
3410
|
-
token: raw.token,
|
|
3411
|
-
amount: raw.amount,
|
|
3412
|
-
to: raw.to,
|
|
3413
|
-
txHash: raw.tx_hash,
|
|
3414
|
-
errorMessage: raw.error_message,
|
|
3415
|
-
explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl(raw.chain_id, raw.tx_hash) : null),
|
|
3416
|
-
fee: raw.fee ? {
|
|
3417
|
-
amount: raw.fee.amount,
|
|
3418
|
-
token: raw.fee.token,
|
|
3419
|
-
basisPoints: raw.fee.basis_points,
|
|
3420
|
-
applied: raw.fee.applied
|
|
3421
|
-
} : null,
|
|
3422
|
-
createdAt: raw.created_at,
|
|
3423
|
-
signedAt: raw.signed_at,
|
|
3424
|
-
submittedAt: raw.submitted_at,
|
|
3425
|
-
confirmedAt: raw.confirmed_at,
|
|
3426
|
-
expiresAt: raw.expires_at
|
|
3427
|
-
};
|
|
3428
|
-
}
|
|
3429
|
-
mapPaymentStatusResult(raw) {
|
|
3430
|
-
return {
|
|
3431
|
-
paymentId: raw.payment_id,
|
|
3432
|
-
kind: raw.kind,
|
|
3433
|
-
rail: raw.rail,
|
|
3434
|
-
status: raw.status,
|
|
3435
|
-
phase: raw.phase,
|
|
3436
|
-
nextAction: raw.next_action,
|
|
3437
|
-
amount: raw.amount,
|
|
3438
|
-
token: raw.token,
|
|
3439
|
-
resourceUrl: raw.resource_url,
|
|
3440
|
-
merchantAddress: raw.merchant_address,
|
|
3441
|
-
payerAddress: raw.payer_address ?? null,
|
|
3442
|
-
txHash: raw.tx_hash,
|
|
3443
|
-
expiresAt: raw.expires_at,
|
|
3444
|
-
chainId: raw.chain_id,
|
|
3445
|
-
message: raw.message,
|
|
3446
|
-
fee: raw.fee ? {
|
|
3447
|
-
amount: raw.fee.amount,
|
|
3448
|
-
token: raw.fee.token,
|
|
3449
|
-
basisPoints: raw.fee.basis_points,
|
|
3450
|
-
applied: raw.fee.applied
|
|
3451
|
-
} : null,
|
|
3452
|
-
amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? null,
|
|
3453
|
-
asset: raw.asset ?? raw.x402?.asset ?? null,
|
|
3454
|
-
network: raw.network ?? raw.x402?.network ?? null,
|
|
3455
|
-
description: raw.description ?? raw.x402?.description ?? null,
|
|
3456
|
-
idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? null,
|
|
3457
|
-
x402: raw.x402 ? {
|
|
3458
|
-
amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,
|
|
3459
|
-
asset: raw.x402.asset ?? raw.asset ?? null,
|
|
3460
|
-
network: raw.x402.network ?? raw.network ?? null,
|
|
3461
|
-
resourceUrl: raw.x402.resource_url ?? raw.resource_url,
|
|
3462
|
-
merchantAddress: raw.x402.merchant_address ?? raw.merchant_address,
|
|
3463
|
-
description: raw.x402.description ?? raw.description ?? null,
|
|
3464
|
-
idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null
|
|
3465
|
-
} : void 0
|
|
3466
|
-
};
|
|
3467
|
-
}
|
|
3468
|
-
mapPaymentReceipt(raw) {
|
|
3469
|
-
const receipt = {
|
|
3470
|
-
id: raw.id,
|
|
3471
|
-
paymentId: raw.payment_id,
|
|
3472
|
-
rail: raw.rail,
|
|
3473
|
-
proofStatus: raw.proof_status,
|
|
3474
|
-
txHash: raw.tx_hash,
|
|
3475
|
-
chainId: raw.chain_id,
|
|
3476
|
-
resourceUrl: raw.resource_url,
|
|
3477
|
-
merchantAddress: raw.merchant_address,
|
|
3478
|
-
payerAddress: raw.payer_address,
|
|
3479
|
-
settlementAddress: raw.settlement_address,
|
|
3480
|
-
tokenSymbol: raw.token_symbol,
|
|
3481
|
-
tokenAddress: raw.token_address,
|
|
3482
|
-
amountRaw: raw.amount_raw,
|
|
3483
|
-
amount: raw.amount_human,
|
|
3484
|
-
challengeId: raw.challenge_id,
|
|
3485
|
-
idempotencyKey: raw.idempotency_key,
|
|
3486
|
-
challengePayload: raw.challenge_payload,
|
|
3487
|
-
selectedPayment: raw.selected_payment,
|
|
3488
|
-
paymentProofHeaderName: raw.payment_proof_header_name,
|
|
3489
|
-
protocolReceiptHeaderName: raw.protocol_receipt_header_name,
|
|
3490
|
-
protocolReceiptPayload: raw.protocol_receipt_payload,
|
|
3491
|
-
merchantStatus: raw.merchant_status,
|
|
3492
|
-
confirmedAt: raw.confirmed_at,
|
|
3493
|
-
createdAt: raw.created_at,
|
|
3494
|
-
updatedAt: raw.updated_at
|
|
3495
|
-
};
|
|
3496
|
-
if ("payment_intent_id" in raw) {
|
|
3497
|
-
receipt.paymentIntentId = raw.payment_intent_id ?? null;
|
|
3498
|
-
}
|
|
3499
|
-
if ("approval_request_id" in raw) {
|
|
3500
|
-
receipt.approvalRequestId = raw.approval_request_id ?? null;
|
|
3501
|
-
}
|
|
3502
|
-
return receipt;
|
|
3715
|
+
return this.havenApi.get(path);
|
|
3503
3716
|
}
|
|
3504
3717
|
};
|
|
3505
3718
|
function sleep(ms) {
|
|
3506
3719
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
3507
3720
|
}
|
|
3508
|
-
function getPaymentHeaderValidBefore(paymentHeader) {
|
|
3509
|
-
try {
|
|
3510
|
-
const payment = decodeBase64Json(
|
|
3511
|
-
paymentHeader
|
|
3512
|
-
);
|
|
3513
|
-
const payload = payment.payload;
|
|
3514
|
-
const validBeforeSeconds = Number(payload.authorization?.validBefore);
|
|
3515
|
-
if (Number.isFinite(validBeforeSeconds)) return validBeforeSeconds * 1e3;
|
|
3516
|
-
} catch {
|
|
3517
|
-
}
|
|
3518
|
-
return 0;
|
|
3519
|
-
}
|
|
3520
|
-
function parseProtocolReceiptHeader(value) {
|
|
3521
|
-
try {
|
|
3522
|
-
return decodeBase64Json(value);
|
|
3523
|
-
} catch {
|
|
3524
|
-
try {
|
|
3525
|
-
return JSON.parse(value);
|
|
3526
|
-
} catch {
|
|
3527
|
-
return void 0;
|
|
3528
|
-
}
|
|
3529
|
-
}
|
|
3530
|
-
}
|
|
3531
|
-
async function captureMerchantResponse(response) {
|
|
3532
|
-
const merchant_body = await response.text().catch(() => "");
|
|
3533
|
-
return {
|
|
3534
|
-
merchant_status: response.status,
|
|
3535
|
-
merchant_status_text: response.statusText,
|
|
3536
|
-
merchant_headers: Object.fromEntries(response.headers.entries()),
|
|
3537
|
-
merchant_body
|
|
3538
|
-
};
|
|
3539
|
-
}
|
|
3540
3721
|
|
|
3541
3722
|
// src/tool-descriptions.ts
|
|
3542
3723
|
function composeDescription(d) {
|
|
@@ -3618,8 +3799,8 @@ var toolDescriptions = {
|
|
|
3618
3799
|
sweep_delegate: {
|
|
3619
3800
|
summary: "Sweep stranded USDC and/or ETH from the delegate wallet back to the originating Safe.",
|
|
3620
3801
|
selectionGuidance: "Use this when the user instructs you to recover stranded funds on the delegate wallet, or when a payment status returns nextAction=sweep_stranded_funds. Do NOT use for normal payments \u2014 use haven_pay_x402. Do NOT use to read balances only \u2014 use haven_get_allowances.",
|
|
3621
|
-
behavior:
|
|
3622
|
-
nextActionGuidance:
|
|
3802
|
+
behavior: `Reads the delegate EOA's on-chain USDC and ETH balances. For each non-zero balance, signs and submits a transfer from the delegate EOA to the originating Safe (hardcoded destination). The delegate key signs locally \u2014 Haven never sees it and the backend never constructs signed transactions (CASP/MiCA Red Line #2). Returns tx hashes and recovered amounts. Returns an empty transfers list when nothing is stranded. Each transfer carries confirmation: "confirmed" (a receipt was seen \u2014 the funds are in the Safe) or "unconfirmed" (broadcast but not confirmed within 90 seconds \u2014 still in the mempool, may still land). The top-level unconfirmed flag is true when any transfer is unconfirmed.`,
|
|
3803
|
+
nextActionGuidance: 'If transfers is non-empty, confirm the amounts with the user. Report a transfer as recovered ONLY when its confirmation is "confirmed". For an "unconfirmed" transfer, tell the user it was submitted but not yet confirmed, give them its txHash and explorerUrl to check, and do not re-run the sweep immediately \u2014 a re-run after it lands will simply find nothing stranded.'
|
|
3623
3804
|
},
|
|
3624
3805
|
send: {
|
|
3625
3806
|
summary: "Send ETH or USDC directly from the agent's Haven wallet to a recipient address.",
|
|
@@ -4148,6 +4329,7 @@ exports.AgentPaymentRail = AgentPaymentRail;
|
|
|
4148
4329
|
exports.AgentPaymentRailDescriptions = AgentPaymentRailDescriptions;
|
|
4149
4330
|
exports.AgentPaymentRailSchema = AgentPaymentRailSchema;
|
|
4150
4331
|
exports.AgentPaymentWarningCode = AgentPaymentWarningCode;
|
|
4332
|
+
exports.DEFAULT_CONFIRMATION_TIMEOUT_MS = DEFAULT_CONFIRMATION_TIMEOUT_MS;
|
|
4151
4333
|
exports.DISCOVERY_MAX_BYTES = DISCOVERY_MAX_BYTES;
|
|
4152
4334
|
exports.ERC7710_ASSET_TRANSFER_METHOD = ERC7710_ASSET_TRANSFER_METHOD;
|
|
4153
4335
|
exports.HAVEN_MINIMUM_NODE_VERSION = HAVEN_MINIMUM_NODE_VERSION;
|