@haven_ai/sdk 0.1.27-alpha.0 → 0.1.28-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 +1865 -1704
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +30 -160
- package/dist/index.d.ts +30 -160
- package/dist/index.js +1865 -1704
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
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
|
|
|
@@ -394,24 +394,6 @@ function verifySignature(hash, signature, expectedAddress) {
|
|
|
394
394
|
return false;
|
|
395
395
|
}
|
|
396
396
|
}
|
|
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
397
|
|
|
416
398
|
// src/base64.ts
|
|
417
399
|
function normalizeBase64(value) {
|
|
@@ -958,61 +940,173 @@ function stableStringify2(value) {
|
|
|
958
940
|
const object = value;
|
|
959
941
|
return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableStringify2(object[key])}`).join(",")}}`;
|
|
960
942
|
}
|
|
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
943
|
var DEFAULT_BASE_URL = "http://localhost:3001";
|
|
973
|
-
var
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
944
|
+
var DEFAULT_REQUEST_TIMEOUT = 3e4;
|
|
945
|
+
var HavenApiTransport = class {
|
|
946
|
+
apiKey;
|
|
947
|
+
baseUrl;
|
|
948
|
+
requestTimeout;
|
|
949
|
+
defaultHeaders;
|
|
950
|
+
requestContext = new async_hooks.AsyncLocalStorage();
|
|
951
|
+
constructor(config) {
|
|
952
|
+
this.apiKey = config.apiKey;
|
|
953
|
+
this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
954
|
+
this.requestTimeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
|
|
955
|
+
this.defaultHeaders = { ...config.defaultHeaders ?? {} };
|
|
956
|
+
}
|
|
957
|
+
/** Run `fn` with extra headers scoped to its asynchronous Haven API work. */
|
|
958
|
+
withRequestContext(headers, fn) {
|
|
959
|
+
return this.requestContext.run({ headers: { ...headers } }, fn);
|
|
960
|
+
}
|
|
961
|
+
async post(path, body) {
|
|
962
|
+
return this.request("POST", path, body);
|
|
963
|
+
}
|
|
964
|
+
async get(path) {
|
|
965
|
+
return this.request("GET", path);
|
|
966
|
+
}
|
|
967
|
+
async request(method, path, body) {
|
|
968
|
+
const url = `${this.baseUrl}${path}`;
|
|
969
|
+
const controller = new AbortController();
|
|
970
|
+
const timeout = setTimeout(() => controller.abort(), this.requestTimeout);
|
|
971
|
+
try {
|
|
972
|
+
const contextHeaders = this.requestContext.getStore()?.headers ?? {};
|
|
973
|
+
const res = await fetch(url, {
|
|
974
|
+
method,
|
|
975
|
+
headers: {
|
|
976
|
+
"Content-Type": "application/json",
|
|
977
|
+
"Authorization": `Bearer ${this.apiKey}`,
|
|
978
|
+
...this.defaultHeaders,
|
|
979
|
+
...contextHeaders
|
|
980
|
+
},
|
|
981
|
+
body: body ? JSON.stringify(body) : void 0,
|
|
982
|
+
signal: controller.signal
|
|
983
|
+
});
|
|
984
|
+
const data = await res.json();
|
|
985
|
+
if (!res.ok) {
|
|
986
|
+
const record = data;
|
|
987
|
+
const errorText = typeof record.error === "string" ? record.error : void 0;
|
|
988
|
+
const rawDetails = record.details ?? record.detail;
|
|
989
|
+
const detailsText = typeof rawDetails === "string" ? rawDetails : rawDetails != null ? JSON.stringify(rawDetails) : void 0;
|
|
990
|
+
const message = errorText && detailsText ? `${errorText}: ${detailsText}` : errorText ?? detailsText ?? "API request failed";
|
|
991
|
+
throw new HavenApiError(message, res.status, data);
|
|
992
|
+
}
|
|
993
|
+
return data;
|
|
994
|
+
} catch (err) {
|
|
995
|
+
if (err instanceof HavenApiError) throw err;
|
|
996
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
997
|
+
throw new HavenApiError(`Request to ${path} timed out`, 408);
|
|
998
|
+
}
|
|
999
|
+
throw new HavenApiError(
|
|
1000
|
+
`Request to ${path} failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
1001
|
+
0
|
|
1002
|
+
);
|
|
1003
|
+
} finally {
|
|
1004
|
+
clearTimeout(timeout);
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
980
1007
|
};
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
1008
|
+
|
|
1009
|
+
// src/payment-mappers.ts
|
|
1010
|
+
function mapPaymentResult(raw, buildExplorerUrl2) {
|
|
1011
|
+
return {
|
|
1012
|
+
paymentId: raw.payment_id,
|
|
1013
|
+
status: raw.status,
|
|
1014
|
+
token: raw.token,
|
|
1015
|
+
amount: raw.amount,
|
|
1016
|
+
to: raw.to,
|
|
1017
|
+
txHash: raw.tx_hash,
|
|
1018
|
+
errorMessage: raw.error_message,
|
|
1019
|
+
explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl2(raw.chain_id, raw.tx_hash) : null),
|
|
1020
|
+
fee: raw.fee ? {
|
|
1021
|
+
amount: raw.fee.amount,
|
|
1022
|
+
token: raw.fee.token,
|
|
1023
|
+
basisPoints: raw.fee.basis_points,
|
|
1024
|
+
applied: raw.fee.applied
|
|
1025
|
+
} : null,
|
|
1026
|
+
createdAt: raw.created_at,
|
|
1027
|
+
signedAt: raw.signed_at,
|
|
1028
|
+
submittedAt: raw.submitted_at,
|
|
1029
|
+
confirmedAt: raw.confirmed_at,
|
|
1030
|
+
expiresAt: raw.expires_at
|
|
1031
|
+
};
|
|
987
1032
|
}
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
1033
|
+
function mapPaymentStatusResult(raw) {
|
|
1034
|
+
return {
|
|
1035
|
+
paymentId: raw.payment_id,
|
|
1036
|
+
kind: raw.kind,
|
|
1037
|
+
rail: raw.rail,
|
|
1038
|
+
status: raw.status,
|
|
1039
|
+
phase: raw.phase,
|
|
1040
|
+
nextAction: raw.next_action,
|
|
1041
|
+
amount: raw.amount,
|
|
1042
|
+
token: raw.token,
|
|
1043
|
+
resourceUrl: raw.resource_url,
|
|
1044
|
+
merchantAddress: raw.merchant_address,
|
|
1045
|
+
payerAddress: raw.payer_address ?? null,
|
|
1046
|
+
txHash: raw.tx_hash,
|
|
1047
|
+
expiresAt: raw.expires_at,
|
|
1048
|
+
chainId: raw.chain_id,
|
|
1049
|
+
message: raw.message,
|
|
1050
|
+
fee: raw.fee ? {
|
|
1051
|
+
amount: raw.fee.amount,
|
|
1052
|
+
token: raw.fee.token,
|
|
1053
|
+
basisPoints: raw.fee.basis_points,
|
|
1054
|
+
applied: raw.fee.applied
|
|
1055
|
+
} : null,
|
|
1056
|
+
amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? null,
|
|
1057
|
+
asset: raw.asset ?? raw.x402?.asset ?? null,
|
|
1058
|
+
network: raw.network ?? raw.x402?.network ?? null,
|
|
1059
|
+
description: raw.description ?? raw.x402?.description ?? null,
|
|
1060
|
+
idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? null,
|
|
1061
|
+
x402: raw.x402 ? {
|
|
1062
|
+
amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,
|
|
1063
|
+
asset: raw.x402.asset ?? raw.asset ?? null,
|
|
1064
|
+
network: raw.x402.network ?? raw.network ?? null,
|
|
1065
|
+
resourceUrl: raw.x402.resource_url ?? raw.resource_url,
|
|
1066
|
+
merchantAddress: raw.x402.merchant_address ?? raw.merchant_address,
|
|
1067
|
+
description: raw.x402.description ?? raw.description ?? null,
|
|
1068
|
+
idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null
|
|
1069
|
+
} : void 0
|
|
1070
|
+
};
|
|
999
1071
|
}
|
|
1000
|
-
function
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1072
|
+
function mapPaymentReceipt(raw) {
|
|
1073
|
+
const receipt = {
|
|
1074
|
+
id: raw.id,
|
|
1075
|
+
paymentId: raw.payment_id,
|
|
1076
|
+
rail: raw.rail,
|
|
1077
|
+
proofStatus: raw.proof_status,
|
|
1078
|
+
txHash: raw.tx_hash,
|
|
1079
|
+
chainId: raw.chain_id,
|
|
1080
|
+
resourceUrl: raw.resource_url,
|
|
1081
|
+
merchantAddress: raw.merchant_address,
|
|
1082
|
+
payerAddress: raw.payer_address,
|
|
1083
|
+
settlementAddress: raw.settlement_address,
|
|
1084
|
+
tokenSymbol: raw.token_symbol,
|
|
1085
|
+
tokenAddress: raw.token_address,
|
|
1086
|
+
amountRaw: raw.amount_raw,
|
|
1087
|
+
amount: raw.amount_human,
|
|
1088
|
+
challengeId: raw.challenge_id,
|
|
1089
|
+
idempotencyKey: raw.idempotency_key,
|
|
1090
|
+
challengePayload: raw.challenge_payload,
|
|
1091
|
+
selectedPayment: raw.selected_payment,
|
|
1092
|
+
paymentProofHeaderName: raw.payment_proof_header_name,
|
|
1093
|
+
protocolReceiptHeaderName: raw.protocol_receipt_header_name,
|
|
1094
|
+
protocolReceiptPayload: raw.protocol_receipt_payload,
|
|
1095
|
+
merchantStatus: raw.merchant_status,
|
|
1096
|
+
confirmedAt: raw.confirmed_at,
|
|
1097
|
+
createdAt: raw.created_at,
|
|
1098
|
+
updatedAt: raw.updated_at
|
|
1099
|
+
};
|
|
1100
|
+
if ("payment_intent_id" in raw) {
|
|
1101
|
+
receipt.paymentIntentId = raw.payment_intent_id ?? null;
|
|
1005
1102
|
}
|
|
1103
|
+
if ("approval_request_id" in raw) {
|
|
1104
|
+
receipt.approvalRequestId = raw.approval_request_id ?? null;
|
|
1105
|
+
}
|
|
1106
|
+
return receipt;
|
|
1006
1107
|
}
|
|
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;
|
|
1108
|
+
|
|
1109
|
+
// src/payment-state.ts
|
|
1016
1110
|
var PAYMENT_STATE_STATUS_CODES = {
|
|
1017
1111
|
pending: 202,
|
|
1018
1112
|
pending_approval: 202,
|
|
@@ -1025,15 +1119,8 @@ var PAYMENT_STATE_STATUS_CODES = {
|
|
|
1025
1119
|
failed: 502,
|
|
1026
1120
|
rejected: 409
|
|
1027
1121
|
};
|
|
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;
|
|
1122
|
+
function paymentStateStatusCode(status, fallback = 502) {
|
|
1123
|
+
return PAYMENT_STATE_STATUS_CODES[status] ?? fallback;
|
|
1037
1124
|
}
|
|
1038
1125
|
function phaseForStatus(status) {
|
|
1039
1126
|
if (status === "pending_signature") return AgentPaymentPhase.AgentSignatureRequired;
|
|
@@ -1076,69 +1163,1484 @@ function messageForState(label, status, paymentId, nextAction) {
|
|
|
1076
1163
|
}
|
|
1077
1164
|
return `${label} is ${status}; next_action=${nextAction} (payment_id: ${paymentId}).`;
|
|
1078
1165
|
}
|
|
1079
|
-
function
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
const
|
|
1085
|
-
const
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1166
|
+
function paymentStateFromRaw(label, raw) {
|
|
1167
|
+
if (!raw.payment_id || !raw.status) return null;
|
|
1168
|
+
const phase = raw.phase ?? phaseForStatus(raw.status);
|
|
1169
|
+
const nextAction = raw.next_action ?? nextActionForStatus(raw.status);
|
|
1170
|
+
if (!phase || !nextAction) return null;
|
|
1171
|
+
const amount = raw.amount ?? raw.requested ?? "";
|
|
1172
|
+
const token = raw.token ?? "";
|
|
1173
|
+
const message = raw.message ?? raw.error ?? messageForState(label, raw.status, raw.payment_id, nextAction);
|
|
1174
|
+
return {
|
|
1175
|
+
paymentId: raw.payment_id,
|
|
1176
|
+
kind: raw.kind === "payment_intent" ? "payment_intent" : "approval_request",
|
|
1177
|
+
rail: raw.rail ?? "direct",
|
|
1178
|
+
status: raw.status === "pending" ? "pending_approval" : raw.status,
|
|
1179
|
+
phase,
|
|
1180
|
+
nextAction,
|
|
1181
|
+
amount,
|
|
1182
|
+
token,
|
|
1183
|
+
resourceUrl: raw.resource_url ?? null,
|
|
1184
|
+
merchantAddress: raw.merchant_address ?? raw.merchant_to ?? null,
|
|
1185
|
+
txHash: raw.tx_hash ?? null,
|
|
1186
|
+
expiresAt: raw.expires_at ?? "",
|
|
1187
|
+
chainId: raw.chain_id ?? 0,
|
|
1188
|
+
message,
|
|
1189
|
+
amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? raw.mpp?.amount_atomic ?? null,
|
|
1190
|
+
asset: raw.asset ?? raw.x402?.asset ?? raw.mpp?.asset ?? null,
|
|
1191
|
+
network: raw.network ?? raw.x402?.network ?? raw.mpp?.network ?? null,
|
|
1192
|
+
description: raw.description ?? raw.x402?.description ?? raw.mpp?.description ?? null,
|
|
1193
|
+
idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? raw.mpp?.idempotency_key ?? null,
|
|
1194
|
+
x402: raw.x402 ? {
|
|
1195
|
+
amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,
|
|
1196
|
+
asset: raw.x402.asset ?? raw.asset ?? null,
|
|
1197
|
+
network: raw.x402.network ?? raw.network ?? null,
|
|
1198
|
+
resourceUrl: raw.x402.resource_url ?? raw.resource_url ?? null,
|
|
1199
|
+
merchantAddress: raw.x402.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,
|
|
1200
|
+
description: raw.x402.description ?? raw.description ?? null,
|
|
1201
|
+
idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null
|
|
1202
|
+
} : void 0,
|
|
1203
|
+
mpp: raw.mpp ? {
|
|
1204
|
+
amountAtomic: raw.mpp.amount_atomic ?? raw.amount_atomic ?? null,
|
|
1205
|
+
asset: raw.mpp.asset ?? raw.asset ?? null,
|
|
1206
|
+
network: raw.mpp.network ?? raw.network ?? null,
|
|
1207
|
+
resourceUrl: raw.mpp.resource_url ?? raw.resource_url ?? null,
|
|
1208
|
+
merchantAddress: raw.mpp.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,
|
|
1209
|
+
description: raw.mpp.description ?? raw.description ?? null,
|
|
1210
|
+
idempotencyKey: raw.mpp.idempotency_key ?? raw.idempotency_key ?? null,
|
|
1211
|
+
challengeId: raw.mpp.challenge_id ?? raw.challenge_id ?? null
|
|
1212
|
+
} : void 0
|
|
1213
|
+
};
|
|
1100
1214
|
}
|
|
1101
|
-
function
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1215
|
+
function throwPaymentStateError(label, raw) {
|
|
1216
|
+
const statusCode = paymentStateStatusCode(raw.status);
|
|
1217
|
+
const state = paymentStateFromRaw(label, raw);
|
|
1218
|
+
if (state) {
|
|
1219
|
+
throw new HavenPaymentStateError(state.message, statusCode, state, raw);
|
|
1106
1220
|
}
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1221
|
+
if (raw.status === "pending_approval") {
|
|
1222
|
+
throw new HavenApiError(
|
|
1223
|
+
`${label} exceeds the on-chain allowance and was queued for owner approval (payment_id: ${raw.payment_id}).`,
|
|
1224
|
+
statusCode,
|
|
1225
|
+
raw
|
|
1226
|
+
);
|
|
1227
|
+
}
|
|
1228
|
+
if (raw.status === "expired") {
|
|
1229
|
+
throw new HavenApiError(
|
|
1230
|
+
`${label} expired before it could be completed (payment_id: ${raw.payment_id}).`,
|
|
1231
|
+
statusCode,
|
|
1232
|
+
raw
|
|
1233
|
+
);
|
|
1114
1234
|
}
|
|
1235
|
+
const paymentId = raw.payment_id ? ` (payment_id: ${raw.payment_id})` : "";
|
|
1236
|
+
const message = raw.error ?? `${label} ${raw.status}${paymentId}`;
|
|
1237
|
+
throw new HavenApiError(message, statusCode, raw);
|
|
1115
1238
|
}
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1239
|
+
|
|
1240
|
+
// src/mcp-merchant-transport.ts
|
|
1241
|
+
var DEFAULT_MERCHANT_TIMEOUT = 3e5;
|
|
1242
|
+
var MCP_NOTIFICATION_TIMEOUT = 1e4;
|
|
1243
|
+
var MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
1244
|
+
var MCP_ACCEPT = "application/json, text/event-stream";
|
|
1245
|
+
var MCP_CLIENT_INFO = { name: "haven-sdk", version: "1" };
|
|
1246
|
+
var McpMerchantTransport = class {
|
|
1247
|
+
merchantTimeout;
|
|
1248
|
+
fetchImpl;
|
|
1249
|
+
requestId = 0;
|
|
1250
|
+
constructor(options = {}) {
|
|
1251
|
+
this.merchantTimeout = options.merchantTimeout ?? DEFAULT_MERCHANT_TIMEOUT;
|
|
1252
|
+
this.fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
1253
|
+
}
|
|
1254
|
+
/** Fetch a merchant with a settlement-sized timeout and caller cancellation. */
|
|
1255
|
+
async fetch(url, init = {}, timeoutMs = this.merchantTimeout) {
|
|
1256
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
1257
|
+
const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal;
|
|
1121
1258
|
try {
|
|
1122
|
-
|
|
1259
|
+
return await this.fetchImpl(url, { ...init, signal });
|
|
1260
|
+
} catch (err) {
|
|
1261
|
+
if (timeoutSignal.aborted) {
|
|
1262
|
+
throw new MerchantTimeoutError(`Merchant request timed out after ${timeoutMs}ms: ${url}`);
|
|
1263
|
+
}
|
|
1264
|
+
throw err;
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Establish an MCP Streamable-HTTP session. Any handshake failure degrades
|
|
1269
|
+
* to `undefined`, allowing the caller to fall back to plain x402.
|
|
1270
|
+
*/
|
|
1271
|
+
async initialize(url, init, wallet) {
|
|
1272
|
+
try {
|
|
1273
|
+
const headers = new Headers(init?.headers);
|
|
1274
|
+
headers.set("Content-Type", "application/json");
|
|
1275
|
+
headers.set("Accept", MCP_ACCEPT);
|
|
1276
|
+
if (wallet && !headers.has("x402-wallet")) headers.set("x402-wallet", wallet);
|
|
1277
|
+
const response = await this.fetch(url, {
|
|
1278
|
+
method: "POST",
|
|
1279
|
+
headers,
|
|
1280
|
+
body: JSON.stringify({
|
|
1281
|
+
jsonrpc: "2.0",
|
|
1282
|
+
id: ++this.requestId,
|
|
1283
|
+
method: "initialize",
|
|
1284
|
+
params: {
|
|
1285
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
1286
|
+
capabilities: {},
|
|
1287
|
+
clientInfo: MCP_CLIENT_INFO
|
|
1288
|
+
}
|
|
1289
|
+
})
|
|
1290
|
+
});
|
|
1291
|
+
if (!response.ok) return void 0;
|
|
1292
|
+
const sessionId = response.headers.get("mcp-session-id");
|
|
1293
|
+
if (!sessionId) return void 0;
|
|
1294
|
+
const message = await this.readMessage(response);
|
|
1295
|
+
if (message && "error" in message) return void 0;
|
|
1296
|
+
await this.notifyInitialized(url, init, sessionId, wallet);
|
|
1297
|
+
return sessionId;
|
|
1123
1298
|
} catch {
|
|
1299
|
+
return void 0;
|
|
1124
1300
|
}
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1301
|
+
}
|
|
1302
|
+
/** Add the MCP session and response-content negotiation headers. */
|
|
1303
|
+
withSessionHeaders(init, sessionId) {
|
|
1304
|
+
const headers = new Headers(init?.headers);
|
|
1305
|
+
headers.set("mcp-session-id", sessionId);
|
|
1306
|
+
headers.set("Accept", MCP_ACCEPT);
|
|
1307
|
+
return { ...init, headers };
|
|
1308
|
+
}
|
|
1309
|
+
/** Read one JSON-RPC message from a JSON or SSE response without consuming it. */
|
|
1310
|
+
async readMessage(response) {
|
|
1311
|
+
let text;
|
|
1312
|
+
try {
|
|
1313
|
+
text = await response.clone().text();
|
|
1314
|
+
} catch {
|
|
1315
|
+
return void 0;
|
|
1131
1316
|
}
|
|
1132
|
-
if (
|
|
1133
|
-
|
|
1317
|
+
if ((response.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
1318
|
+
return selectJsonRpcResult(parseSseJsonRpcMessages(text));
|
|
1319
|
+
}
|
|
1320
|
+
try {
|
|
1321
|
+
return JSON.parse(text);
|
|
1322
|
+
} catch {
|
|
1323
|
+
return void 0;
|
|
1134
1324
|
}
|
|
1135
1325
|
}
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1326
|
+
/**
|
|
1327
|
+
* Collapse an MCP SSE response to the JSON-RPC result. Non-SSE and
|
|
1328
|
+
* unparseable responses pass through with their original body untouched.
|
|
1329
|
+
*/
|
|
1330
|
+
async surfaceResult(response) {
|
|
1331
|
+
if (!(response.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
1332
|
+
return response;
|
|
1333
|
+
}
|
|
1334
|
+
let text;
|
|
1335
|
+
try {
|
|
1336
|
+
text = await response.clone().text();
|
|
1337
|
+
} catch {
|
|
1338
|
+
return response;
|
|
1339
|
+
}
|
|
1340
|
+
const message = selectJsonRpcResult(parseSseJsonRpcMessages(text));
|
|
1341
|
+
if (!message) return response;
|
|
1342
|
+
const body = "result" in message ? message.result : message;
|
|
1343
|
+
const headers = new Headers(response.headers);
|
|
1344
|
+
headers.set("content-type", "application/json");
|
|
1345
|
+
headers.delete("content-length");
|
|
1346
|
+
headers.delete("mcp-session-id");
|
|
1347
|
+
return new Response(JSON.stringify(body), {
|
|
1348
|
+
status: response.status,
|
|
1349
|
+
statusText: response.statusText,
|
|
1350
|
+
headers
|
|
1351
|
+
});
|
|
1352
|
+
}
|
|
1353
|
+
/** Detect MCP transport from the URL or Coinbase Bazaar extension. */
|
|
1354
|
+
async detect(url, paymentRequired, response) {
|
|
1355
|
+
if (isMcpUrl(url)) return { handshakeRequired: true, source: "path" };
|
|
1356
|
+
if (paymentRequired.extensions?.bazaar != null) {
|
|
1357
|
+
return { handshakeRequired: true, source: "bazaar" };
|
|
1358
|
+
}
|
|
1359
|
+
if (await responseHasBazaarExtension(response)) {
|
|
1360
|
+
return { handshakeRequired: true, source: "bazaar" };
|
|
1361
|
+
}
|
|
1362
|
+
return void 0;
|
|
1363
|
+
}
|
|
1364
|
+
/** Identify the conventional Streamable-HTTP MCP path without probing it. */
|
|
1365
|
+
isMcpUrl(url) {
|
|
1366
|
+
return isMcpUrl(url);
|
|
1367
|
+
}
|
|
1368
|
+
/** Detect Bazaar metadata without consuming the merchant response. */
|
|
1369
|
+
hasBazaarExtension(response) {
|
|
1370
|
+
return responseHasBazaarExtension(response);
|
|
1371
|
+
}
|
|
1372
|
+
/** Deliver an already-signed x402 header without changing the caller body. */
|
|
1373
|
+
async deliverPayment(url, init, paymentHeader) {
|
|
1374
|
+
const headers = new Headers(init?.headers);
|
|
1375
|
+
headers.set("X-PAYMENT", paymentHeader);
|
|
1376
|
+
return this.fetch(url, { ...init, headers });
|
|
1377
|
+
}
|
|
1378
|
+
async notifyInitialized(url, init, sessionId, wallet) {
|
|
1379
|
+
try {
|
|
1380
|
+
const headers = new Headers(init?.headers);
|
|
1381
|
+
headers.set("Content-Type", "application/json");
|
|
1382
|
+
headers.set("Accept", MCP_ACCEPT);
|
|
1383
|
+
headers.set("mcp-session-id", sessionId);
|
|
1384
|
+
if (wallet && !headers.has("x402-wallet")) headers.set("x402-wallet", wallet);
|
|
1385
|
+
await this.fetch(
|
|
1386
|
+
url,
|
|
1387
|
+
{
|
|
1388
|
+
method: "POST",
|
|
1389
|
+
headers,
|
|
1390
|
+
body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
|
|
1391
|
+
},
|
|
1392
|
+
MCP_NOTIFICATION_TIMEOUT
|
|
1393
|
+
);
|
|
1394
|
+
} catch {
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
};
|
|
1398
|
+
async function captureMerchantResponse(response) {
|
|
1399
|
+
const merchant_body = await response.text().catch(() => "");
|
|
1400
|
+
return {
|
|
1401
|
+
merchant_status: response.status,
|
|
1402
|
+
merchant_status_text: response.statusText,
|
|
1403
|
+
merchant_headers: Object.fromEntries(response.headers.entries()),
|
|
1404
|
+
merchant_body
|
|
1405
|
+
};
|
|
1406
|
+
}
|
|
1407
|
+
function isMcpUrl(url) {
|
|
1408
|
+
try {
|
|
1409
|
+
return new URL(url).pathname.replace(/\/+$/, "").endsWith("/mcp");
|
|
1410
|
+
} catch {
|
|
1411
|
+
return /\/mcp(?:[/?#]|$)/.test(url);
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
async function responseHasBazaarExtension(response) {
|
|
1415
|
+
try {
|
|
1416
|
+
const body = await response.clone().json();
|
|
1417
|
+
return body?.extensions?.bazaar != null;
|
|
1418
|
+
} catch {
|
|
1419
|
+
return false;
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
function parseSseJsonRpcMessages(text) {
|
|
1423
|
+
const messages = [];
|
|
1424
|
+
let dataLines = [];
|
|
1425
|
+
const flush = () => {
|
|
1426
|
+
if (dataLines.length === 0) return;
|
|
1427
|
+
try {
|
|
1428
|
+
messages.push(JSON.parse(dataLines.join("\n")));
|
|
1429
|
+
} catch {
|
|
1430
|
+
}
|
|
1431
|
+
dataLines = [];
|
|
1432
|
+
};
|
|
1433
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1434
|
+
if (line === "") {
|
|
1435
|
+
flush();
|
|
1436
|
+
continue;
|
|
1437
|
+
}
|
|
1438
|
+
if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
1439
|
+
}
|
|
1440
|
+
flush();
|
|
1441
|
+
return messages;
|
|
1442
|
+
}
|
|
1443
|
+
function selectJsonRpcResult(messages) {
|
|
1444
|
+
return messages.find((message) => "result" in message || "error" in message) ?? messages.at(-1);
|
|
1445
|
+
}
|
|
1446
|
+
var RECEIPT_VERSION = "haven-receipt-1";
|
|
1447
|
+
function defaultRecover(hash, signature) {
|
|
1448
|
+
return ethers.ethers.recoverAddress(hash, signature);
|
|
1449
|
+
}
|
|
1450
|
+
function verifyPaymentReceipt(receipt, recover = defaultRecover) {
|
|
1451
|
+
const { delegate, signHash: signHash2, signature } = receipt.authorization;
|
|
1452
|
+
if (!signature) return { verified: false, reason: "missing_signature" };
|
|
1453
|
+
let recovered;
|
|
1454
|
+
try {
|
|
1455
|
+
recovered = recover(signHash2, signature);
|
|
1456
|
+
} catch {
|
|
1457
|
+
return { verified: false, reason: "bad_signature" };
|
|
1458
|
+
}
|
|
1459
|
+
if (recovered.toLowerCase() !== delegate.toLowerCase()) {
|
|
1460
|
+
return { verified: false, reason: "signer_mismatch", recoveredSigner: recovered };
|
|
1461
|
+
}
|
|
1462
|
+
return { verified: true, recoveredSigner: recovered };
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
// src/account-reads.ts
|
|
1466
|
+
function safeBigInt(value) {
|
|
1467
|
+
try {
|
|
1468
|
+
return BigInt(value);
|
|
1469
|
+
} catch {
|
|
1470
|
+
return 0n;
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
function formatAtomicAmount(atomic, decimals) {
|
|
1474
|
+
if (atomic < 0n) return "0.0";
|
|
1475
|
+
const value = atomic.toString().padStart(decimals + 1, "0");
|
|
1476
|
+
const whole = value.slice(0, value.length - decimals) || "0";
|
|
1477
|
+
const fraction = value.slice(value.length - decimals).replace(/0+$/, "") || "0";
|
|
1478
|
+
return `${whole}.${fraction}`;
|
|
1479
|
+
}
|
|
1480
|
+
function deriveReadiness(status, allowances) {
|
|
1481
|
+
if (status !== "active") return "revoked";
|
|
1482
|
+
return allowances.some((allowance) => safeBigInt(allowance.remainingAtomic) > 0n) ? "ready" : "needs_approval";
|
|
1483
|
+
}
|
|
1484
|
+
var AccountReads = class {
|
|
1485
|
+
transport;
|
|
1486
|
+
getPaymentStatus;
|
|
1487
|
+
agentInFlight = null;
|
|
1488
|
+
constructor(options) {
|
|
1489
|
+
this.transport = options.transport;
|
|
1490
|
+
this.getPaymentStatus = options.getPaymentStatus;
|
|
1491
|
+
}
|
|
1492
|
+
async getAgent() {
|
|
1493
|
+
if (this.agentInFlight) return this.agentInFlight;
|
|
1494
|
+
const request = this.fetchAgent();
|
|
1495
|
+
this.agentInFlight = request;
|
|
1496
|
+
request.finally(() => {
|
|
1497
|
+
this.agentInFlight = null;
|
|
1498
|
+
}).catch(() => {
|
|
1499
|
+
});
|
|
1500
|
+
return request;
|
|
1501
|
+
}
|
|
1502
|
+
async getAgentSummary() {
|
|
1503
|
+
const [agent, allowanceSummary] = await Promise.all([this.getAgent(), this.getAllowances()]);
|
|
1504
|
+
const allowances = allowanceSummary.allowances.map((allowance) => {
|
|
1505
|
+
const token = resolveTokenFromAddress(allowance.tokenAddress);
|
|
1506
|
+
const remainingDisplay = token ? `${formatAtomicAmount(safeBigInt(allowance.onchain.remaining), token.decimals)} ${allowance.tokenSymbol}` : `${allowance.onchain.remaining} ${allowance.tokenSymbol} (atomic; unknown decimals)`;
|
|
1507
|
+
return {
|
|
1508
|
+
tokenSymbol: allowance.tokenSymbol,
|
|
1509
|
+
remainingAtomic: allowance.onchain.remaining,
|
|
1510
|
+
remainingDisplay,
|
|
1511
|
+
configuredAmount: allowance.configuredAmount,
|
|
1512
|
+
resetPeriodMin: allowance.resetPeriodMin,
|
|
1513
|
+
isResetPending: allowance.onchain.isResetPending
|
|
1514
|
+
};
|
|
1515
|
+
});
|
|
1516
|
+
const readiness = deriveReadiness(agent.status, allowances);
|
|
1517
|
+
return { ...agent, readiness, spend_authority_readiness: readiness, allowances };
|
|
1518
|
+
}
|
|
1519
|
+
async getAllowances() {
|
|
1520
|
+
const raw = await this.transport.get("/machine-payments/allowances");
|
|
1521
|
+
return {
|
|
1522
|
+
agentId: raw.agent_id,
|
|
1523
|
+
safeAddress: raw.safe_address,
|
|
1524
|
+
delegateAddress: raw.delegate_address,
|
|
1525
|
+
chainId: raw.chain_id,
|
|
1526
|
+
allowances: raw.allowances.map((allowance) => ({
|
|
1527
|
+
id: allowance.id,
|
|
1528
|
+
tokenAddress: allowance.token_address,
|
|
1529
|
+
tokenSymbol: allowance.token_symbol,
|
|
1530
|
+
configuredAmount: allowance.configured_amount,
|
|
1531
|
+
resetPeriodMin: allowance.reset_period_min,
|
|
1532
|
+
onchain: {
|
|
1533
|
+
amount: allowance.onchain.amount,
|
|
1534
|
+
spent: allowance.onchain.spent,
|
|
1535
|
+
remaining: allowance.onchain.remaining,
|
|
1536
|
+
effectiveSpent: allowance.onchain.effective_spent,
|
|
1537
|
+
resetTimeMin: allowance.onchain.reset_time_min,
|
|
1538
|
+
lastResetMin: allowance.onchain.last_reset_min,
|
|
1539
|
+
nonce: allowance.onchain.nonce,
|
|
1540
|
+
isResetPending: allowance.onchain.is_reset_pending,
|
|
1541
|
+
remainingIsFromChain: allowance.onchain.remaining_is_from_chain
|
|
1542
|
+
}
|
|
1543
|
+
}))
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
async getPostPurchaseAllowanceSummary(paymentId) {
|
|
1547
|
+
const unavailable = (detail, payment2 = null) => ({
|
|
1548
|
+
payment: payment2,
|
|
1549
|
+
allowance: null,
|
|
1550
|
+
warnings: [{
|
|
1551
|
+
code: AgentPaymentWarningCode.AllowanceCheckUnavailable,
|
|
1552
|
+
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.`
|
|
1553
|
+
}]
|
|
1554
|
+
});
|
|
1555
|
+
const [statusResult, agentResult, allowanceResult] = await Promise.allSettled([
|
|
1556
|
+
this.getPaymentStatus(paymentId),
|
|
1557
|
+
this.getAgent(),
|
|
1558
|
+
this.getAllowances()
|
|
1559
|
+
]);
|
|
1560
|
+
if (statusResult.status === "rejected") {
|
|
1561
|
+
return unavailable(statusResult.reason instanceof Error ? statusResult.reason.message : String(statusResult.reason));
|
|
1562
|
+
}
|
|
1563
|
+
const payment = statusResult.value;
|
|
1564
|
+
if (agentResult.status === "rejected") {
|
|
1565
|
+
return unavailable(agentResult.reason instanceof Error ? agentResult.reason.message : String(agentResult.reason), payment);
|
|
1566
|
+
}
|
|
1567
|
+
if (allowanceResult.status === "rejected") {
|
|
1568
|
+
return unavailable(allowanceResult.reason instanceof Error ? allowanceResult.reason.message : String(allowanceResult.reason), payment);
|
|
1569
|
+
}
|
|
1570
|
+
try {
|
|
1571
|
+
const tokenAddress = payment.asset ?? payment.x402?.asset ?? null;
|
|
1572
|
+
if (!tokenAddress) return unavailable("the settled payment does not carry a resolvable token address", payment);
|
|
1573
|
+
const match = allowanceResult.value.allowances.find(
|
|
1574
|
+
(allowance) => allowance.tokenAddress.toLowerCase() === tokenAddress.toLowerCase()
|
|
1575
|
+
);
|
|
1576
|
+
if (!match) return unavailable("no allowance/budget row matches the settled token", payment);
|
|
1577
|
+
const token = resolveTokenFromAddress(match.tokenAddress);
|
|
1578
|
+
const remainingDisplay = token ? `${formatAtomicAmount(safeBigInt(match.onchain.remaining), token.decimals)} ${match.tokenSymbol}` : void 0;
|
|
1579
|
+
const rail = agentResult.value.executionRail;
|
|
1580
|
+
return {
|
|
1581
|
+
payment,
|
|
1582
|
+
allowance: {
|
|
1583
|
+
rail,
|
|
1584
|
+
remaining_atomic: match.onchain.remaining,
|
|
1585
|
+
...remainingDisplay ? { remaining_display: remainingDisplay } : {},
|
|
1586
|
+
token_symbol: match.tokenSymbol,
|
|
1587
|
+
token_address: match.tokenAddress,
|
|
1588
|
+
reset_period: match.resetPeriodMin,
|
|
1589
|
+
source: rail === "delegation" ? "active_delegations" : "allowance_module"
|
|
1590
|
+
},
|
|
1591
|
+
warnings: []
|
|
1592
|
+
};
|
|
1593
|
+
} catch (error) {
|
|
1594
|
+
return unavailable(error instanceof Error ? error.message : String(error));
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
async listReceipts(options = {}) {
|
|
1598
|
+
const query = options.limit ? `?limit=${encodeURIComponent(String(options.limit))}` : "";
|
|
1599
|
+
const raw = await this.transport.get(`/machine-payments/receipts${query}`);
|
|
1600
|
+
return raw.receipts.map(mapPaymentReceipt);
|
|
1601
|
+
}
|
|
1602
|
+
async getReceipt(paymentId) {
|
|
1603
|
+
const { receipt } = await this.transport.get(`/payments/${paymentId}/receipt`);
|
|
1604
|
+
return { receipt, verification: verifyPaymentReceipt(receipt) };
|
|
1605
|
+
}
|
|
1606
|
+
async fetchAgent() {
|
|
1607
|
+
const raw = await this.transport.get("/machine-payments/agent");
|
|
1608
|
+
return {
|
|
1609
|
+
id: raw.id,
|
|
1610
|
+
name: raw.name,
|
|
1611
|
+
status: raw.status,
|
|
1612
|
+
safeAddress: raw.safe_address,
|
|
1613
|
+
delegateAddress: raw.delegate_address,
|
|
1614
|
+
chainId: raw.chain_id,
|
|
1615
|
+
executionRail: raw.execution_rail === "delegation" ? "delegation" : "legacy"
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
};
|
|
1619
|
+
function createJsonRpcProvider(url) {
|
|
1620
|
+
return new ethers.ethers.JsonRpcProvider(url);
|
|
1621
|
+
}
|
|
1622
|
+
function createWallet(privateKey, provider) {
|
|
1623
|
+
return new ethers.ethers.Wallet(privateKey, provider);
|
|
1624
|
+
}
|
|
1625
|
+
function createErc20Contract(address, abi, runner) {
|
|
1626
|
+
return new ethers.ethers.Contract(address, abi, runner);
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
// src/delegate-sweep.ts
|
|
1630
|
+
var DelegateSweepApi = class {
|
|
1631
|
+
constructor(options) {
|
|
1632
|
+
this.options = options;
|
|
1633
|
+
}
|
|
1634
|
+
options;
|
|
1635
|
+
async sweepDelegate() {
|
|
1636
|
+
if (!this.options.delegateKey) throw new HavenSigningError("delegateKey is required for sweepDelegate.");
|
|
1637
|
+
const agent = await this.options.getAgent();
|
|
1638
|
+
if (!agent.delegateAddress) throw new HavenApiError("Agent has no delegate address.", 422);
|
|
1639
|
+
const rpcUrl = this.options.chainRpcs[agent.chainId];
|
|
1640
|
+
if (!rpcUrl) throw new HavenApiError(`chainRpcs[${agent.chainId}] must be configured to sweep the delegate wallet.`, 422);
|
|
1641
|
+
const provider = createJsonRpcProvider(rpcUrl);
|
|
1642
|
+
const wallet = createWallet(this.options.delegateKey, provider);
|
|
1643
|
+
const transfers = [];
|
|
1644
|
+
if (isSweepableChain(agent.chainId)) {
|
|
1645
|
+
const contract = createErc20Contract(sweepUsdcAddress(agent.chainId), ["function balanceOf(address) view returns (uint256)", "function transfer(address to, uint256 amount) returns (bool)"], wallet);
|
|
1646
|
+
const balance2 = await contract.balanceOf(agent.delegateAddress);
|
|
1647
|
+
if (balance2 > 0n) {
|
|
1648
|
+
const tx = await contract.transfer(agent.safeAddress, balance2);
|
|
1649
|
+
const receipt = await tx.wait(1);
|
|
1650
|
+
const txHash = receipt?.hash ?? tx.hash;
|
|
1651
|
+
transfers.push({ asset: "USDC", amount: format(balance2, 6), amountAtomic: balance2.toString(), txHash, explorerUrl: this.options.buildExplorerUrl(agent.chainId, txHash) });
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
const balance = await provider.getBalance(agent.delegateAddress);
|
|
1655
|
+
if (balance > 0n) {
|
|
1656
|
+
const fee = await provider.getFeeData();
|
|
1657
|
+
const send = balance - (fee.maxFeePerGas ?? fee.gasPrice ?? 1000000n) * 21000n * 2n;
|
|
1658
|
+
if (send > 0n) {
|
|
1659
|
+
const tx = await wallet.sendTransaction({ to: agent.safeAddress, value: send });
|
|
1660
|
+
const receipt = await tx.wait(1);
|
|
1661
|
+
const txHash = receipt?.hash ?? tx.hash;
|
|
1662
|
+
transfers.push({ asset: "ETH", amount: format(send, 18), amountAtomic: send.toString(), txHash, explorerUrl: this.options.buildExplorerUrl(agent.chainId, txHash) });
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
return { fromAddress: agent.delegateAddress, toAddress: agent.safeAddress, chainId: agent.chainId, transfers };
|
|
1666
|
+
}
|
|
1667
|
+
prepareSweep() {
|
|
1668
|
+
return this.options.transport.post("/machine-payments/sweep/prepare", {});
|
|
1669
|
+
}
|
|
1670
|
+
submitSweep(authorization, signature) {
|
|
1671
|
+
return this.options.transport.post("/machine-payments/sweep/submit", { authorization, signature });
|
|
1672
|
+
}
|
|
1673
|
+
};
|
|
1674
|
+
function format(value, decimals) {
|
|
1675
|
+
const raw = value.toString().padStart(decimals + 1, "0");
|
|
1676
|
+
return `${raw.slice(0, -decimals) || "0"}.${raw.slice(-decimals).replace(/0+$/, "") || "0"}`;
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
// src/x402-protocol.ts
|
|
1680
|
+
var CHAIN_EXPLORER_TX = {
|
|
1681
|
+
100: "https://gnosisscan.io/tx",
|
|
1682
|
+
8453: "https://basescan.org/tx"
|
|
1683
|
+
};
|
|
1684
|
+
function buildExplorerUrl(chainId, txHash) {
|
|
1685
|
+
const base = CHAIN_EXPLORER_TX[chainId ?? 8453] ?? CHAIN_EXPLORER_TX[8453];
|
|
1686
|
+
return `${base}/${txHash}`;
|
|
1687
|
+
}
|
|
1688
|
+
function explorerUrlOrEmpty(chainId, txHash) {
|
|
1689
|
+
return txHash ? buildExplorerUrl(chainId, txHash) : "";
|
|
1690
|
+
}
|
|
1691
|
+
function chainIdFromNetwork(network) {
|
|
1692
|
+
if (network === "base") return 8453;
|
|
1693
|
+
if (network === "base-sepolia") return 84532;
|
|
1694
|
+
if (!network?.startsWith("eip155:")) return void 0;
|
|
1695
|
+
const chainId = Number(network.slice("eip155:".length));
|
|
1696
|
+
return Number.isFinite(chainId) ? chainId : void 0;
|
|
1697
|
+
}
|
|
1698
|
+
function chainIdOrNull(network) {
|
|
1699
|
+
return chainIdFromNetwork(network) ?? null;
|
|
1700
|
+
}
|
|
1701
|
+
function sameAddress3(a, b) {
|
|
1702
|
+
return Boolean(a && b && a.toLowerCase() === b.toLowerCase());
|
|
1703
|
+
}
|
|
1704
|
+
function decimalFromUsdcAtomic(value) {
|
|
1705
|
+
const amount = BigInt(value);
|
|
1706
|
+
const whole = amount / 1000000n;
|
|
1707
|
+
const fraction = (amount % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
|
|
1708
|
+
return fraction ? `${whole}.${fraction}` : whole.toString();
|
|
1709
|
+
}
|
|
1710
|
+
function normalizeDecimal(value) {
|
|
1711
|
+
if (!value.includes(".")) return value.replace(/^0+(?=\d)/, "") || "0";
|
|
1712
|
+
const [whole, fraction = ""] = value.split(".");
|
|
1713
|
+
const normalizedWhole = whole.replace(/^0+(?=\d)/, "") || "0";
|
|
1714
|
+
const normalizedFraction = fraction.replace(/0+$/, "");
|
|
1715
|
+
return normalizedFraction ? `${normalizedWhole}.${normalizedFraction}` : normalizedWhole;
|
|
1716
|
+
}
|
|
1717
|
+
function x402PayerAddress(delegateAddress, x402Wallet) {
|
|
1718
|
+
return delegateAddress ?? x402Wallet;
|
|
1719
|
+
}
|
|
1720
|
+
function withX402Wallet(init, wallet) {
|
|
1721
|
+
if (!wallet) return init;
|
|
1722
|
+
const headers = new Headers(init?.headers);
|
|
1723
|
+
if (!headers.has("x402-wallet")) {
|
|
1724
|
+
headers.set("x402-wallet", wallet);
|
|
1725
|
+
}
|
|
1726
|
+
return {
|
|
1727
|
+
...init,
|
|
1728
|
+
headers
|
|
1729
|
+
};
|
|
1730
|
+
}
|
|
1731
|
+
function snapshotRequestBody(body) {
|
|
1732
|
+
if (body == null) return void 0;
|
|
1733
|
+
if (typeof body === "string") return body;
|
|
1734
|
+
if (body instanceof URLSearchParams) return body.toString();
|
|
1735
|
+
throw new HavenApiError(
|
|
1736
|
+
"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.",
|
|
1737
|
+
400
|
|
1738
|
+
);
|
|
1739
|
+
}
|
|
1740
|
+
function snapshotX402Request(url, init) {
|
|
1741
|
+
return {
|
|
1742
|
+
url,
|
|
1743
|
+
method: init?.method ?? "GET",
|
|
1744
|
+
headers: Array.from(new Headers(init?.headers).entries()),
|
|
1745
|
+
body: snapshotRequestBody(init?.body)
|
|
1746
|
+
};
|
|
1747
|
+
}
|
|
1748
|
+
function requestInitFromSnapshot(request) {
|
|
1749
|
+
return {
|
|
1750
|
+
method: request.method,
|
|
1751
|
+
headers: request.headers,
|
|
1752
|
+
body: request.body
|
|
1753
|
+
};
|
|
1754
|
+
}
|
|
1755
|
+
function buildX402Quote(paymentRequired, request, idempotencyKey, mcpTransport) {
|
|
1756
|
+
const option = selectStandardPaymentOption(paymentRequired.accepts);
|
|
1757
|
+
if (!option) {
|
|
1758
|
+
throw new HavenApiError(
|
|
1759
|
+
"No compatible payment option found in x402 requirements. Haven supports standard x402 exact payments on Base USDC.",
|
|
1760
|
+
400
|
|
1761
|
+
);
|
|
1762
|
+
}
|
|
1763
|
+
const token = resolveTokenFromAddress(option.asset, option.network);
|
|
1764
|
+
return {
|
|
1765
|
+
rail: "x402",
|
|
1766
|
+
idempotencyKey: idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option),
|
|
1767
|
+
paymentRequired,
|
|
1768
|
+
accepted: option,
|
|
1769
|
+
request,
|
|
1770
|
+
...mcpTransport ? { mcpTransport } : {},
|
|
1771
|
+
resourceUrl: paymentRequired.resource.url,
|
|
1772
|
+
description: paymentRequired.resource.description ?? option.description ?? null,
|
|
1773
|
+
mimeType: paymentRequired.resource.mimeType ?? option.mimeType ?? null,
|
|
1774
|
+
amountAtomic: x402AuthorizationAmount(option),
|
|
1775
|
+
amount: decimalFromUsdcAtomic(x402AuthorizationAmount(option)),
|
|
1776
|
+
token: token?.symbol ?? "USDC",
|
|
1777
|
+
// #1351: null when the asset is unrecognised on this network — the
|
|
1778
|
+
// `token` fallback above is a LABEL, not evidence of 6 decimals, and a
|
|
1779
|
+
// human-denominated cap must fail closed rather than convert against a
|
|
1780
|
+
// guess. Same resolution as `token`, so the two never disagree.
|
|
1781
|
+
decimals: token?.decimals ?? null,
|
|
1782
|
+
asset: option.asset,
|
|
1783
|
+
network: option.network,
|
|
1784
|
+
chainId: chainIdOrNull(option.network),
|
|
1785
|
+
merchantAddress: option.payTo,
|
|
1786
|
+
maxTimeoutSeconds: option.maxTimeoutSeconds
|
|
1787
|
+
};
|
|
1788
|
+
}
|
|
1789
|
+
function buildX402Receipt(input) {
|
|
1790
|
+
const fundingExplorerUrl = input.explorerUrl || explorerUrlOrEmpty(input.chainId, input.txHash);
|
|
1791
|
+
return {
|
|
1792
|
+
success: true,
|
|
1793
|
+
paymentId: input.paymentId,
|
|
1794
|
+
txHash: input.txHash,
|
|
1795
|
+
token: input.token,
|
|
1796
|
+
amount: input.amount,
|
|
1797
|
+
to: input.to,
|
|
1798
|
+
resourceUrl: input.resourceUrl,
|
|
1799
|
+
explorerUrl: input.explorerUrl,
|
|
1800
|
+
accepted: input.accepted,
|
|
1801
|
+
paymentHeader: input.paymentHeader,
|
|
1802
|
+
merchantTo: input.merchantTo ?? input.accepted.payTo,
|
|
1803
|
+
payer: input.payer,
|
|
1804
|
+
chainId: input.chainId,
|
|
1805
|
+
haven: {
|
|
1806
|
+
paymentId: input.paymentId,
|
|
1807
|
+
fundingTxHash: input.txHash,
|
|
1808
|
+
fundingExplorerUrl
|
|
1809
|
+
},
|
|
1810
|
+
merchant: {
|
|
1811
|
+
payTo: input.merchantTo ?? input.accepted.payTo
|
|
1812
|
+
},
|
|
1813
|
+
x402: {
|
|
1814
|
+
amount: x402AuthorizationAmount(input.accepted),
|
|
1815
|
+
token: input.token,
|
|
1816
|
+
network: input.accepted.network,
|
|
1817
|
+
asset: input.accepted.asset,
|
|
1818
|
+
resource: input.accepted.resource ?? input.resourceUrl
|
|
1819
|
+
}
|
|
1820
|
+
};
|
|
1821
|
+
}
|
|
1822
|
+
function buildX402ResumeState(input) {
|
|
1823
|
+
const token = resolveTokenFromAddress(input.accepted.asset, input.accepted.network);
|
|
1824
|
+
return {
|
|
1825
|
+
rail: "x402",
|
|
1826
|
+
paymentId: input.paymentId,
|
|
1827
|
+
idempotencyKey: input.idempotencyKey,
|
|
1828
|
+
paymentRequired: input.paymentRequired,
|
|
1829
|
+
accepted: input.accepted,
|
|
1830
|
+
url: input.request?.url ?? input.paymentRequired.resource.url,
|
|
1831
|
+
request: input.request,
|
|
1832
|
+
resourceUrl: input.paymentRequired.resource.url,
|
|
1833
|
+
description: input.paymentRequired.resource.description ?? input.accepted.description ?? null,
|
|
1834
|
+
amountAtomic: x402AuthorizationAmount(input.accepted),
|
|
1835
|
+
amount: decimalFromUsdcAtomic(x402AuthorizationAmount(input.accepted)),
|
|
1836
|
+
token: token?.symbol ?? "USDC",
|
|
1837
|
+
asset: input.accepted.asset,
|
|
1838
|
+
network: input.accepted.network,
|
|
1839
|
+
chainId: chainIdOrNull(input.accepted.network),
|
|
1840
|
+
merchantAddress: input.accepted.payTo
|
|
1841
|
+
};
|
|
1842
|
+
}
|
|
1843
|
+
function attachX402ResumeState(err, paymentRequired, accepted, idempotencyKey, request) {
|
|
1844
|
+
if (!(err instanceof HavenPaymentStateError)) return;
|
|
1845
|
+
if (err.state.rail !== "x402") return;
|
|
1846
|
+
err.resumeState = buildX402ResumeState({
|
|
1847
|
+
paymentId: err.state.paymentId,
|
|
1848
|
+
paymentRequired,
|
|
1849
|
+
accepted,
|
|
1850
|
+
idempotencyKey,
|
|
1851
|
+
request
|
|
1852
|
+
});
|
|
1853
|
+
}
|
|
1854
|
+
function attachResumeState(err, input) {
|
|
1855
|
+
attachX402ResumeState(
|
|
1856
|
+
err,
|
|
1857
|
+
input.paymentRequired,
|
|
1858
|
+
input.accepted,
|
|
1859
|
+
input.idempotencyKey,
|
|
1860
|
+
input.request
|
|
1861
|
+
);
|
|
1862
|
+
}
|
|
1863
|
+
function assertCanResumeX402(status, paymentRequired, option) {
|
|
1864
|
+
if (status.rail !== "x402") {
|
|
1865
|
+
throw new HavenPaymentStateError(
|
|
1866
|
+
`Payment ${status.paymentId} is ${status.rail}, not x402.`,
|
|
1867
|
+
409,
|
|
1868
|
+
status
|
|
1869
|
+
);
|
|
1870
|
+
}
|
|
1871
|
+
if (status.nextAction !== AgentPaymentNextAction.RetryOriginalX402Request) {
|
|
1872
|
+
throw new HavenPaymentStateError(status.message, paymentStateStatusCode(status.status, 409), status);
|
|
1873
|
+
}
|
|
1874
|
+
if (!status.txHash) {
|
|
1875
|
+
throw new HavenApiError(
|
|
1876
|
+
`x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,
|
|
1877
|
+
502,
|
|
1878
|
+
status,
|
|
1879
|
+
status.paymentId
|
|
1880
|
+
);
|
|
1881
|
+
}
|
|
1882
|
+
if (status.resourceUrl && status.resourceUrl !== paymentRequired.resource.url) {
|
|
1883
|
+
throw new HavenApiError(
|
|
1884
|
+
"x402 resume request does not match the approved resource URL.",
|
|
1885
|
+
409,
|
|
1886
|
+
{ status, paymentRequired },
|
|
1887
|
+
status.paymentId
|
|
1888
|
+
);
|
|
1889
|
+
}
|
|
1890
|
+
if (status.merchantAddress && !sameAddress3(status.merchantAddress, option.payTo)) {
|
|
1891
|
+
throw new HavenApiError(
|
|
1892
|
+
"x402 resume request does not match the approved merchant.",
|
|
1893
|
+
409,
|
|
1894
|
+
{ status, selectedPayment: option },
|
|
1895
|
+
status.paymentId
|
|
1896
|
+
);
|
|
1897
|
+
}
|
|
1898
|
+
const optionChainId = chainIdFromNetwork(option.network);
|
|
1899
|
+
if (status.chainId && optionChainId && status.chainId !== optionChainId) {
|
|
1900
|
+
throw new HavenApiError(
|
|
1901
|
+
"x402 resume request does not match the approved network.",
|
|
1902
|
+
409,
|
|
1903
|
+
{ status, selectedPayment: option },
|
|
1904
|
+
status.paymentId
|
|
1905
|
+
);
|
|
1906
|
+
}
|
|
1907
|
+
if (status.token && status.token !== "USDC") {
|
|
1908
|
+
throw new HavenApiError(
|
|
1909
|
+
"x402 resume request does not match the approved token.",
|
|
1910
|
+
409,
|
|
1911
|
+
{ status, selectedPayment: option },
|
|
1912
|
+
status.paymentId
|
|
1913
|
+
);
|
|
1914
|
+
}
|
|
1915
|
+
const approvedAmount = status.amount ? normalizeDecimal(status.amount) : "";
|
|
1916
|
+
const requestedAmount = normalizeDecimal(decimalFromUsdcAtomic(x402AuthorizationAmount(option)));
|
|
1917
|
+
if (approvedAmount && approvedAmount !== requestedAmount) {
|
|
1918
|
+
throw new HavenApiError(
|
|
1919
|
+
"x402 resume request does not match the approved amount.",
|
|
1920
|
+
409,
|
|
1921
|
+
{ status, selectedPayment: option },
|
|
1922
|
+
status.paymentId
|
|
1923
|
+
);
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
var X402FundingLeg = class {
|
|
1927
|
+
delegateKey;
|
|
1928
|
+
delegateAddress;
|
|
1929
|
+
x402Wallet;
|
|
1930
|
+
chainRpcs;
|
|
1931
|
+
post;
|
|
1932
|
+
signForData;
|
|
1933
|
+
assertSignableAuthorizationState;
|
|
1934
|
+
/**
|
|
1935
|
+
* Receipts keyed by idempotency key, held only as long as the underlying
|
|
1936
|
+
* EIP-3009 authorization is valid. The cache belongs to this module rather
|
|
1937
|
+
* than to the facade because its expiry is read out of the authorization
|
|
1938
|
+
* header itself — a 3009 artifact.
|
|
1939
|
+
*/
|
|
1940
|
+
receiptCache = /* @__PURE__ */ new Map();
|
|
1941
|
+
constructor(options) {
|
|
1942
|
+
this.delegateKey = options.delegateKey;
|
|
1943
|
+
this.delegateAddress = options.delegateAddress;
|
|
1944
|
+
this.x402Wallet = options.x402Wallet;
|
|
1945
|
+
this.chainRpcs = options.chainRpcs;
|
|
1946
|
+
this.post = options.post;
|
|
1947
|
+
this.signForData = options.signForData;
|
|
1948
|
+
this.assertSignableAuthorizationState = options.assertSignableAuthorizationState;
|
|
1949
|
+
}
|
|
1950
|
+
// ── Receipt cache ────────────────────────────────────────────────
|
|
1951
|
+
/** A still-valid cached receipt for this key, or undefined. */
|
|
1952
|
+
cachedReceipt(idempotencyKey) {
|
|
1953
|
+
const cached = this.receiptCache.get(idempotencyKey);
|
|
1954
|
+
if (cached && cached.expiresAt > Date.now()) return cached.receipt;
|
|
1955
|
+
return void 0;
|
|
1956
|
+
}
|
|
1957
|
+
cacheReceipt(idempotencyKey, paymentHeader, receipt) {
|
|
1958
|
+
const expiresAt = getPaymentHeaderValidBefore(paymentHeader);
|
|
1959
|
+
if (expiresAt > Date.now()) {
|
|
1960
|
+
this.receiptCache.set(idempotencyKey, { expiresAt, receipt });
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
// ── Authorization ────────────────────────────────────────────────
|
|
1964
|
+
async authorize(paymentRequired, option, idempotencyKey) {
|
|
1965
|
+
const raw = await this.post("/x402", {
|
|
1966
|
+
url: paymentRequired.resource.url,
|
|
1967
|
+
payTo: this.delegateAddress,
|
|
1968
|
+
merchantPayTo: option.payTo,
|
|
1969
|
+
amount: x402AuthorizationAmount(option),
|
|
1970
|
+
asset: option.asset,
|
|
1971
|
+
network: option.network,
|
|
1972
|
+
description: paymentRequired.resource.description,
|
|
1973
|
+
idempotencyKey,
|
|
1974
|
+
// #1360: same explicit funding-leg declaration as createX402Intent —
|
|
1975
|
+
// this local-key path derives payTo from the key (never stale), but the
|
|
1976
|
+
// declaration keeps both writers of the 3009 shape loud-by-default.
|
|
1977
|
+
settlementScheme: "eip3009"
|
|
1978
|
+
});
|
|
1979
|
+
const state = paymentStateFromRaw("x402 payment", raw);
|
|
1980
|
+
const executedReplay = raw.success && raw.tx_hash ? "idempotency-collision" : state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request ? "approval-resume" : null;
|
|
1981
|
+
if (executedReplay) {
|
|
1982
|
+
const canFund = await this.delegateCanFund(
|
|
1983
|
+
raw.chain_id ?? state?.chainId ?? chainIdFromNetwork(option.network),
|
|
1984
|
+
option.asset,
|
|
1985
|
+
x402AuthorizationAmount(option)
|
|
1986
|
+
);
|
|
1987
|
+
const refuse = executedReplay === "idempotency-collision" ? canFund !== true : canFund === false;
|
|
1988
|
+
if (refuse) {
|
|
1989
|
+
const settledReceipt = state && executedReplay === "approval-resume" ? this.receiptFromStatus(paymentRequired, option, void 0, state) : this.receiptFromAuthorization(paymentRequired, option, void 0, raw);
|
|
1990
|
+
throw new X402AlreadySettledError(
|
|
1991
|
+
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`.",
|
|
1992
|
+
settledReceipt,
|
|
1993
|
+
canFund === false ? "settled" : "unverifiable"
|
|
1994
|
+
);
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
const paymentHeader = await this.createPaymentHeader(paymentRequired, option);
|
|
1998
|
+
if (raw.success && raw.tx_hash) {
|
|
1999
|
+
const receipt2 = this.receiptFromAuthorization(paymentRequired, option, paymentHeader, raw);
|
|
2000
|
+
this.cacheReceipt(idempotencyKey, paymentHeader, receipt2);
|
|
2001
|
+
return receipt2;
|
|
2002
|
+
}
|
|
2003
|
+
if (state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request) {
|
|
2004
|
+
const receipt2 = this.receiptFromStatus(paymentRequired, option, paymentHeader, state);
|
|
2005
|
+
this.cacheReceipt(idempotencyKey, paymentHeader, receipt2);
|
|
2006
|
+
return receipt2;
|
|
2007
|
+
}
|
|
2008
|
+
this.assertSignableAuthorizationState("x402 payment", raw);
|
|
2009
|
+
if (!raw.sign_data?.hash) {
|
|
2010
|
+
throw new HavenApiError("No sign_hash returned from x402/authorize", 500, raw);
|
|
2011
|
+
}
|
|
2012
|
+
const sig = await this.signForData(raw.sign_data);
|
|
2013
|
+
const execResult = await this.post(
|
|
2014
|
+
`/payments/${raw.payment_id}/sign`,
|
|
2015
|
+
{ signature: sig }
|
|
2016
|
+
);
|
|
2017
|
+
if (execResult.status !== "confirmed") {
|
|
2018
|
+
throwPaymentStateError("x402 payment", execResult);
|
|
2019
|
+
}
|
|
2020
|
+
await this.waitForFundingTx(
|
|
2021
|
+
execResult.tx_hash,
|
|
2022
|
+
execResult.chain_id ?? chainIdFromNetwork(option.network)
|
|
2023
|
+
);
|
|
2024
|
+
const receipt = this.receiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult);
|
|
2025
|
+
this.cacheReceipt(idempotencyKey, paymentHeader, receipt);
|
|
2026
|
+
return receipt;
|
|
2027
|
+
}
|
|
2028
|
+
// ── Header minting ───────────────────────────────────────────────
|
|
2029
|
+
async createPaymentHeader(paymentRequired, option) {
|
|
2030
|
+
if (!this.delegateKey) {
|
|
2031
|
+
throw new HavenSigningError("delegateKey is required to sign x402 payment headers.");
|
|
2032
|
+
}
|
|
2033
|
+
const account = accounts.privateKeyToAccount(this.delegateKey);
|
|
2034
|
+
const requirements = toStandardPaymentRequirements(paymentRequired, option);
|
|
2035
|
+
const header = await schemes.exact.evm.createPaymentHeader(
|
|
2036
|
+
account,
|
|
2037
|
+
paymentRequired.x402Version,
|
|
2038
|
+
requirements
|
|
2039
|
+
);
|
|
2040
|
+
if (paymentRequired.x402Version < 2) return header;
|
|
2041
|
+
const payment = decodeBase64Json(header);
|
|
2042
|
+
return encodeBase64Json({
|
|
2043
|
+
x402Version: paymentRequired.x402Version,
|
|
2044
|
+
accepted: option,
|
|
2045
|
+
payload: payment.payload
|
|
2046
|
+
});
|
|
2047
|
+
}
|
|
2048
|
+
// ── Receipt mapping ──────────────────────────────────────────────
|
|
2049
|
+
receiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult) {
|
|
2050
|
+
const txHash = execResult?.tx_hash ?? raw.tx_hash ?? "";
|
|
2051
|
+
const chainId = execResult?.chain_id ?? raw.chain_id ?? chainIdFromNetwork(option.network);
|
|
2052
|
+
const token = execResult?.token ?? raw.token ?? "USDC";
|
|
2053
|
+
const amount = execResult?.amount ?? raw.amount ?? decimalFromUsdcAtomic(x402AuthorizationAmount(option));
|
|
2054
|
+
const to = execResult?.to ?? raw.to ?? this.delegateAddress ?? "";
|
|
2055
|
+
const explorerUrl = execResult?.explorer_url ?? raw.explorer_url ?? explorerUrlOrEmpty(chainId, txHash);
|
|
2056
|
+
const merchantTo = execResult?.merchant_to ?? raw.merchant_to ?? option.payTo;
|
|
2057
|
+
const payer = raw.payer ?? raw.safe_address ?? raw.sign_data?.components.safe;
|
|
2058
|
+
return buildX402Receipt({
|
|
2059
|
+
paymentId: raw.payment_id,
|
|
2060
|
+
txHash,
|
|
2061
|
+
token,
|
|
2062
|
+
amount,
|
|
2063
|
+
to,
|
|
2064
|
+
resourceUrl: paymentRequired.resource.url,
|
|
2065
|
+
explorerUrl,
|
|
2066
|
+
accepted: option,
|
|
2067
|
+
paymentHeader,
|
|
2068
|
+
merchantTo,
|
|
2069
|
+
payer,
|
|
2070
|
+
chainId
|
|
2071
|
+
});
|
|
2072
|
+
}
|
|
2073
|
+
receiptFromStatus(paymentRequired, option, paymentHeader, status) {
|
|
2074
|
+
if (!status.txHash) {
|
|
2075
|
+
throw new HavenApiError(
|
|
2076
|
+
`x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,
|
|
2077
|
+
502,
|
|
2078
|
+
status,
|
|
2079
|
+
status.paymentId
|
|
2080
|
+
);
|
|
2081
|
+
}
|
|
2082
|
+
return buildX402Receipt({
|
|
2083
|
+
paymentId: status.paymentId,
|
|
2084
|
+
txHash: status.txHash,
|
|
2085
|
+
token: status.token || "USDC",
|
|
2086
|
+
amount: status.amount || decimalFromUsdcAtomic(x402AuthorizationAmount(option)),
|
|
2087
|
+
to: this.delegateAddress ?? "",
|
|
2088
|
+
resourceUrl: paymentRequired.resource.url,
|
|
2089
|
+
explorerUrl: explorerUrlOrEmpty(status.chainId, status.txHash),
|
|
2090
|
+
accepted: option,
|
|
2091
|
+
paymentHeader,
|
|
2092
|
+
merchantTo: status.merchantAddress ?? option.payTo,
|
|
2093
|
+
payer: this.x402Wallet,
|
|
2094
|
+
chainId: status.chainId || chainIdFromNetwork(option.network)
|
|
2095
|
+
});
|
|
2096
|
+
}
|
|
2097
|
+
// ── On-chain reads ───────────────────────────────────────────────
|
|
2098
|
+
/**
|
|
2099
|
+
* Wait for a funding tx to be mined with ≥1 confirmation before the
|
|
2100
|
+
* merchant retry, eliminating the race where the merchant's
|
|
2101
|
+
* `balanceOf(delegate)` runs before the funding block propagates.
|
|
2102
|
+
*
|
|
2103
|
+
* Skipped when `chainRpcs` does not include the chain; in that case Haven's
|
|
2104
|
+
* backend has already confirmed on-chain submission and callers accept the
|
|
2105
|
+
* small propagation window as a trade-off for not configuring an RPC URL.
|
|
2106
|
+
*/
|
|
2107
|
+
async waitForFundingTx(txHash, chainId, timeoutMs = 3e4) {
|
|
2108
|
+
if (!txHash || !chainId) return;
|
|
2109
|
+
const rpcUrl = this.chainRpcs[chainId];
|
|
2110
|
+
if (!rpcUrl) return;
|
|
2111
|
+
const provider = createJsonRpcProvider(rpcUrl);
|
|
2112
|
+
const onChainReceipt = await provider.waitForTransaction(txHash, 1, timeoutMs);
|
|
2113
|
+
if (!onChainReceipt || onChainReceipt.status !== 1) {
|
|
2114
|
+
throw new HavenApiError(
|
|
2115
|
+
"Funding tx did not confirm on-chain within the timeout window.",
|
|
2116
|
+
500,
|
|
2117
|
+
{ txHash, chainId }
|
|
2118
|
+
);
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
/**
|
|
2122
|
+
* Can the delegate EOA still fund an authorization for `amountAtomic`?
|
|
2123
|
+
*
|
|
2124
|
+
* #1521: the only question that separates a legitimate resume (funding
|
|
2125
|
+
* confirmed, merchant never paid — the delegate still holds the money) from
|
|
2126
|
+
* a replayed settled payment (funding confirmed, merchant paid, delegate
|
|
2127
|
+
* spent). The intent's own `status: 'confirmed'` is identical in both.
|
|
2128
|
+
*
|
|
2129
|
+
* The balance is asked of the CHAIN rather than of Haven's bookkeeping on
|
|
2130
|
+
* purpose: the merchant-settlement evidence record is written by this SDK
|
|
2131
|
+
* *after* the merchant call, so a client that dies between the two leaves
|
|
2132
|
+
* the backend believing the merchant was never paid — the exact case the
|
|
2133
|
+
* discriminator has to get right. The chain cannot be behind in that way.
|
|
2134
|
+
*
|
|
2135
|
+
* Returns `null` — never a guess — when `chainRpcs` has no entry for the
|
|
2136
|
+
* chain or the read fails. Callers must treat that as "unverifiable", not
|
|
2137
|
+
* as "funded".
|
|
2138
|
+
*/
|
|
2139
|
+
async delegateCanFund(chainId, tokenAddress, amountAtomic, timeoutMs = 1e4) {
|
|
2140
|
+
if (!chainId || !this.delegateAddress) return null;
|
|
2141
|
+
const rpcUrl = this.chainRpcs[chainId];
|
|
2142
|
+
if (!rpcUrl) return null;
|
|
2143
|
+
try {
|
|
2144
|
+
const provider = createJsonRpcProvider(rpcUrl);
|
|
2145
|
+
const token = createErc20Contract(
|
|
2146
|
+
tokenAddress,
|
|
2147
|
+
["function balanceOf(address) view returns (uint256)"],
|
|
2148
|
+
provider
|
|
2149
|
+
);
|
|
2150
|
+
const balance = await Promise.race([
|
|
2151
|
+
token.balanceOf(this.delegateAddress),
|
|
2152
|
+
new Promise((resolve) => setTimeout(() => resolve(null), timeoutMs).unref?.())
|
|
2153
|
+
]);
|
|
2154
|
+
if (balance === null) return null;
|
|
2155
|
+
return balance >= BigInt(amountAtomic);
|
|
2156
|
+
} catch {
|
|
2157
|
+
return null;
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
};
|
|
2161
|
+
function getPaymentHeaderValidBefore(paymentHeader) {
|
|
2162
|
+
try {
|
|
2163
|
+
const payment = decodeBase64Json(
|
|
2164
|
+
paymentHeader
|
|
2165
|
+
);
|
|
2166
|
+
const payload = payment.payload;
|
|
2167
|
+
const validBeforeSeconds = Number(payload.authorization?.validBefore);
|
|
2168
|
+
if (Number.isFinite(validBeforeSeconds)) return validBeforeSeconds * 1e3;
|
|
2169
|
+
} catch {
|
|
2170
|
+
}
|
|
2171
|
+
return 0;
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
// src/x402-erc7710.ts
|
|
2175
|
+
var X402Erc7710 = class {
|
|
2176
|
+
delegateKey;
|
|
2177
|
+
post;
|
|
2178
|
+
signForData;
|
|
2179
|
+
getAgent;
|
|
2180
|
+
constructor(options) {
|
|
2181
|
+
this.delegateKey = options.delegateKey;
|
|
2182
|
+
this.post = options.post;
|
|
2183
|
+
this.signForData = options.signForData;
|
|
2184
|
+
this.getAgent = options.getAgent;
|
|
2185
|
+
}
|
|
2186
|
+
/**
|
|
2187
|
+
* Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).
|
|
2188
|
+
*
|
|
2189
|
+
* The whole point of this path is what it does NOT do. There is no funding
|
|
2190
|
+
* leg: the merchant redeems a delegation chain and pulls from the treasury
|
|
2191
|
+
* directly, so the delegate EOA never holds the money, no sweep can strand
|
|
2192
|
+
* it, and the #713 reconciliation class does not apply. It is also why this
|
|
2193
|
+
* method is SMALLER than the 3009 path — the backend assembles the merchant
|
|
2194
|
+
* `X-PAYMENT` header in `assembleSettlementPayload`, so the SDK builds no
|
|
2195
|
+
* header locally.
|
|
2196
|
+
*
|
|
2197
|
+
* authorize (payTo = the MERCHANT) → sign the child → settle → header
|
|
2198
|
+
*
|
|
2199
|
+
* The caller then retries the merchant with that header. **Nothing has
|
|
2200
|
+
* settled when this returns** — that is why it does not return an
|
|
2201
|
+
* `X402Receipt`.
|
|
2202
|
+
*
|
|
2203
|
+
* Requires a delegation-rail account. The backend enforces that
|
|
2204
|
+
* (`validateGenericSchemeRail`), and so does this method, before building a
|
|
2205
|
+
* request the backend would only reject: an error a client can explain is
|
|
2206
|
+
* worth more than a 400 it has to decode.
|
|
2207
|
+
*
|
|
2208
|
+
* **MCP callers must pass `options.resourceUrl`.** An in-band MCP 402
|
|
2209
|
+
* challenge frequently carries no `resource` object at all, so
|
|
2210
|
+
* `paymentRequired.resource?.url` is undefined and the backend answers
|
|
2211
|
+
* "Valid url is required". The QA scenario this path was ported from falls
|
|
2212
|
+
* back to the request URL for exactly that reason — the SDK cannot, because
|
|
2213
|
+
* it never saw the request. Pass it.
|
|
2214
|
+
*/
|
|
2215
|
+
async settle(paymentRequired, options = {}) {
|
|
2216
|
+
if (!this.delegateKey) {
|
|
2217
|
+
throw new HavenSigningError(
|
|
2218
|
+
"delegateKey is required for x402 payments. Pass it in the HavenClient config."
|
|
2219
|
+
);
|
|
2220
|
+
}
|
|
2221
|
+
const prepared = await this.prepare(paymentRequired, options);
|
|
2222
|
+
const signature = await this.signForData(prepared.signData);
|
|
2223
|
+
const paymentHeader = await this.submit(prepared.paymentId, signature);
|
|
2224
|
+
return { ...prepared.settlement, paymentHeader };
|
|
2225
|
+
}
|
|
2226
|
+
/**
|
|
2227
|
+
* The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build
|
|
2228
|
+
* the request, and return the child to be signed — without signing it.
|
|
2229
|
+
*
|
|
2230
|
+
* Split out because the hosted topology cannot use `settleX402Erc7710()`:
|
|
2231
|
+
* that method signs in-process with `delegateKey`, and hosted Haven does not
|
|
2232
|
+
* have one and must not. The hosted MCP server drives these two halves with
|
|
2233
|
+
* the LOCAL signer in between, so the key stays where it belongs and the
|
|
2234
|
+
* request shaping stays in one place rather than being reimplemented.
|
|
2235
|
+
*/
|
|
2236
|
+
async prepare(paymentRequired, options = {}) {
|
|
2237
|
+
const delegationRail = options.delegationRail ?? (await this.getAgent()).executionRail === "delegation";
|
|
2238
|
+
if (!delegationRail) {
|
|
2239
|
+
throw new HavenApiError(
|
|
2240
|
+
"erc7710 settlement requires a delegation-rail account; this one is not on it. Use authorizeX402() for the standard EIP-3009 path.",
|
|
2241
|
+
400
|
|
2242
|
+
);
|
|
2243
|
+
}
|
|
2244
|
+
const selection = selectX402SettlementScheme(paymentRequired.accepts, { delegationRail });
|
|
2245
|
+
if (!selection || selection.scheme !== "erc7710") {
|
|
2246
|
+
throw new HavenApiError(
|
|
2247
|
+
"This merchant does not advertise an erc7710 settlement option (no accepts[] entry carries extra.assetTransferMethod: 'erc7710'). Use authorizeX402() for the standard EIP-3009 path.",
|
|
2248
|
+
400
|
|
2249
|
+
);
|
|
2250
|
+
}
|
|
2251
|
+
const option = selection.option;
|
|
2252
|
+
const merchantPayTo = option.payTo;
|
|
2253
|
+
const amountAtomic = x402AuthorizationAmount(option);
|
|
2254
|
+
const raw = await this.post("/x402", {
|
|
2255
|
+
url: options.resourceUrl ?? paymentRequired.resource?.url,
|
|
2256
|
+
// payTo = the MERCHANT is what selects direct settlement server-side.
|
|
2257
|
+
// The explicit settlementScheme must AGREE with that shape (#1360) —
|
|
2258
|
+
// disagreement is a 400 by design, so that a stale delegate address
|
|
2259
|
+
// becomes a loud mismatch instead of a silent reroute to the 3009 leg.
|
|
2260
|
+
payTo: merchantPayTo,
|
|
2261
|
+
settlementScheme: "erc7710",
|
|
2262
|
+
amount: amountAtomic,
|
|
2263
|
+
asset: option.asset,
|
|
2264
|
+
network: option.network,
|
|
2265
|
+
// The v2 header echoes the accepted entry field-for-field, so the quoted
|
|
2266
|
+
// timeout must round-trip or the merchant rejects the echo (#1064).
|
|
2267
|
+
maxTimeoutSeconds: option.maxTimeoutSeconds,
|
|
2268
|
+
// #1058: forward the advertised facilitators verbatim — the child becomes
|
|
2269
|
+
// redeemable ONLY by them. `null` here means the merchant advertised none
|
|
2270
|
+
// (or an empty array, which the backend 400s on), so the field is OMITTED
|
|
2271
|
+
// rather than sent empty. See x402FacilitatorAddresses.
|
|
2272
|
+
...selection.facilitatorAddresses ? { facilitatorAddresses: selection.facilitatorAddresses } : {},
|
|
2273
|
+
// #1307/#1547: persisted so the settle leg can rehydrate the merchant
|
|
2274
|
+
// call by payment_id on this scheme too, not only on the 3009 bridge.
|
|
2275
|
+
...options.mcpCallContext ? { mcpCallContext: options.mcpCallContext } : {}
|
|
2276
|
+
});
|
|
2277
|
+
if (!raw.payment_id) {
|
|
2278
|
+
throw new HavenApiError("No payment_id returned from x402/authorize", 500, raw);
|
|
2279
|
+
}
|
|
2280
|
+
const signData = raw.sign_data;
|
|
2281
|
+
if (signData?.signature_scheme !== "eip712_delegation" || !signData.typed_data) {
|
|
2282
|
+
throw new HavenApiError(
|
|
2283
|
+
`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.`,
|
|
2284
|
+
500,
|
|
2285
|
+
raw
|
|
2286
|
+
);
|
|
2287
|
+
}
|
|
2288
|
+
return {
|
|
2289
|
+
paymentId: raw.payment_id,
|
|
2290
|
+
signData,
|
|
2291
|
+
settlement: {
|
|
2292
|
+
paymentId: raw.payment_id,
|
|
2293
|
+
merchantPayTo,
|
|
2294
|
+
amountAtomic,
|
|
2295
|
+
asset: option.asset,
|
|
2296
|
+
network: option.network,
|
|
2297
|
+
facilitatorAddresses: selection.facilitatorAddresses
|
|
2298
|
+
}
|
|
2299
|
+
};
|
|
2300
|
+
}
|
|
2301
|
+
/**
|
|
2302
|
+
* The SETTLE half (#1456): exchange the signed child for the merchant header.
|
|
2303
|
+
*
|
|
2304
|
+
* The SDK builds no header on this path — the backend assembles the MetaMask
|
|
2305
|
+
* erc7710 payload in `assembleSettlementPayload`. Whoever produced the
|
|
2306
|
+
* signature (an in-process delegate key, or the local edge signer over the
|
|
2307
|
+
* hosted boundary) is irrelevant here.
|
|
2308
|
+
*/
|
|
2309
|
+
async submit(paymentId, signature) {
|
|
2310
|
+
const settled = await this.post(
|
|
2311
|
+
`/x402/${paymentId}/settle`,
|
|
2312
|
+
{ signature }
|
|
2313
|
+
);
|
|
2314
|
+
if (!settled.payment_header) {
|
|
2315
|
+
throw new HavenApiError(
|
|
2316
|
+
"x402 settle returned no payment_header \u2014 the merchant cannot be retried.",
|
|
2317
|
+
500,
|
|
2318
|
+
settled
|
|
2319
|
+
);
|
|
2320
|
+
}
|
|
2321
|
+
return settled.payment_header;
|
|
2322
|
+
}
|
|
2323
|
+
};
|
|
2324
|
+
|
|
2325
|
+
// src/tool-adapter.ts
|
|
2326
|
+
function toolX402PaymentRequired(input) {
|
|
2327
|
+
return {
|
|
2328
|
+
x402Version: 2,
|
|
2329
|
+
resource: { url: input.url, description: input.description },
|
|
2330
|
+
accepts: [
|
|
2331
|
+
{
|
|
2332
|
+
scheme: "exact",
|
|
2333
|
+
network: input.network,
|
|
2334
|
+
amount: input.amount,
|
|
2335
|
+
asset: input.asset,
|
|
2336
|
+
payTo: input.payTo,
|
|
2337
|
+
maxTimeoutSeconds: 30
|
|
2338
|
+
}
|
|
2339
|
+
]
|
|
2340
|
+
};
|
|
2341
|
+
}
|
|
2342
|
+
function x402ToolReceipt(receipt) {
|
|
2343
|
+
return {
|
|
2344
|
+
success: true,
|
|
2345
|
+
payment_id: receipt.paymentId,
|
|
2346
|
+
tx_hash: receipt.txHash,
|
|
2347
|
+
token: receipt.token,
|
|
2348
|
+
amount: receipt.amount,
|
|
2349
|
+
to: receipt.to,
|
|
2350
|
+
resource_url: receipt.resourceUrl,
|
|
2351
|
+
explorer_url: receipt.explorerUrl,
|
|
2352
|
+
payment_header: receipt.paymentHeader,
|
|
2353
|
+
merchant_to: receipt.merchantTo,
|
|
2354
|
+
payer: receipt.payer,
|
|
2355
|
+
chain_id: receipt.chainId,
|
|
2356
|
+
haven: receipt.haven,
|
|
2357
|
+
merchant: receipt.merchant,
|
|
2358
|
+
x402: receipt.x402
|
|
2359
|
+
};
|
|
2360
|
+
}
|
|
2361
|
+
function toolError(err) {
|
|
2362
|
+
if (err instanceof HavenPaymentStateError) {
|
|
2363
|
+
return {
|
|
2364
|
+
success: false,
|
|
2365
|
+
payment_id: err.state.paymentId,
|
|
2366
|
+
kind: err.state.kind,
|
|
2367
|
+
rail: err.state.rail,
|
|
2368
|
+
status: err.state.status,
|
|
2369
|
+
phase: err.state.phase,
|
|
2370
|
+
next_action: err.state.nextAction,
|
|
2371
|
+
tx_hash: err.state.txHash,
|
|
2372
|
+
token: err.state.token,
|
|
2373
|
+
amount: err.state.amount,
|
|
2374
|
+
resource_url: err.state.resourceUrl,
|
|
2375
|
+
merchant_address: err.state.merchantAddress,
|
|
2376
|
+
amount_atomic: err.state.amountAtomic,
|
|
2377
|
+
asset: err.state.asset,
|
|
2378
|
+
network: err.state.network,
|
|
2379
|
+
description: err.state.description,
|
|
2380
|
+
idempotency_key: err.state.idempotencyKey,
|
|
2381
|
+
x402: err.state.x402 ? {
|
|
2382
|
+
amount_atomic: err.state.x402.amountAtomic,
|
|
2383
|
+
asset: err.state.x402.asset,
|
|
2384
|
+
network: err.state.x402.network,
|
|
2385
|
+
resource_url: err.state.x402.resourceUrl,
|
|
2386
|
+
merchant_address: err.state.x402.merchantAddress,
|
|
2387
|
+
description: err.state.x402.description,
|
|
2388
|
+
idempotency_key: err.state.x402.idempotencyKey
|
|
2389
|
+
} : void 0,
|
|
2390
|
+
mpp: err.state.mpp ? {
|
|
2391
|
+
amount_atomic: err.state.mpp.amountAtomic,
|
|
2392
|
+
asset: err.state.mpp.asset,
|
|
2393
|
+
network: err.state.mpp.network,
|
|
2394
|
+
resource_url: err.state.mpp.resourceUrl,
|
|
2395
|
+
merchant_address: err.state.mpp.merchantAddress,
|
|
2396
|
+
description: err.state.mpp.description,
|
|
2397
|
+
idempotency_key: err.state.mpp.idempotencyKey,
|
|
2398
|
+
challenge_id: err.state.mpp.challengeId
|
|
2399
|
+
} : void 0,
|
|
2400
|
+
resume_state: err.resumeState,
|
|
2401
|
+
expires_at: err.state.expiresAt,
|
|
2402
|
+
chain_id: err.state.chainId,
|
|
2403
|
+
message: err.state.message,
|
|
2404
|
+
error: err.message
|
|
2405
|
+
};
|
|
2406
|
+
}
|
|
2407
|
+
if (err instanceof HavenApiError) {
|
|
2408
|
+
return {
|
|
2409
|
+
success: false,
|
|
2410
|
+
status_code: err.statusCode,
|
|
2411
|
+
error: err.message,
|
|
2412
|
+
body: err.body
|
|
2413
|
+
};
|
|
2414
|
+
}
|
|
2415
|
+
return {
|
|
2416
|
+
success: false,
|
|
2417
|
+
error: err instanceof Error ? err.message : String(err)
|
|
2418
|
+
};
|
|
2419
|
+
}
|
|
2420
|
+
|
|
2421
|
+
// src/merchant-completion.ts
|
|
2422
|
+
var MERCHANT_BODY_SNIPPET_LIMIT = 1e3;
|
|
2423
|
+
var MerchantCompletion = class {
|
|
2424
|
+
post;
|
|
2425
|
+
merchantTransport;
|
|
2426
|
+
getPaymentStatus;
|
|
2427
|
+
getAgent;
|
|
2428
|
+
delegateAddress;
|
|
2429
|
+
x402Wallet;
|
|
2430
|
+
constructor(options) {
|
|
2431
|
+
this.post = options.post;
|
|
2432
|
+
this.merchantTransport = options.merchantTransport;
|
|
2433
|
+
this.getPaymentStatus = options.getPaymentStatus;
|
|
2434
|
+
this.getAgent = options.getAgent;
|
|
2435
|
+
this.delegateAddress = options.delegateAddress;
|
|
2436
|
+
this.x402Wallet = options.x402Wallet;
|
|
2437
|
+
}
|
|
2438
|
+
async retryRequest(url, initialInit, paymentRequired, receipt) {
|
|
2439
|
+
if (!receipt.accepted) {
|
|
2440
|
+
throw new HavenApiError("No accepted x402 option was recorded for payment retry", 500);
|
|
2441
|
+
}
|
|
2442
|
+
if (!receipt.paymentHeader) {
|
|
2443
|
+
throw new HavenApiError("No x402 payment header was returned for payment retry", 500);
|
|
2444
|
+
}
|
|
2445
|
+
const retryResponse = await this.merchantTransport.deliverPayment(
|
|
2446
|
+
url,
|
|
2447
|
+
initialInit,
|
|
2448
|
+
receipt.paymentHeader
|
|
2449
|
+
);
|
|
2450
|
+
if (!retryResponse.ok) {
|
|
2451
|
+
const merchant = await captureMerchantResponse(retryResponse);
|
|
2452
|
+
await this.recordRetryRejected({
|
|
2453
|
+
rail: "x402",
|
|
2454
|
+
paymentId: receipt.paymentId,
|
|
2455
|
+
txHash: receipt.txHash,
|
|
2456
|
+
resourceUrl: receipt.resourceUrl,
|
|
2457
|
+
merchant,
|
|
2458
|
+
details: {
|
|
2459
|
+
merchant_to: receipt.merchantTo,
|
|
2460
|
+
delegate_to: receipt.to
|
|
2461
|
+
}
|
|
2462
|
+
});
|
|
2463
|
+
throw new HavenApiError(
|
|
2464
|
+
"x402 retry failed after Haven funded the delegate wallet; reconciliation may be required.",
|
|
2465
|
+
merchant.merchant_status,
|
|
2466
|
+
{
|
|
2467
|
+
marker: "x402_retry_rejected_after_funding",
|
|
2468
|
+
payment_id: receipt.paymentId,
|
|
2469
|
+
tx_hash: receipt.txHash,
|
|
2470
|
+
resource_url: receipt.resourceUrl,
|
|
2471
|
+
merchant_to: receipt.merchantTo,
|
|
2472
|
+
delegate_to: receipt.to,
|
|
2473
|
+
...merchant
|
|
2474
|
+
}
|
|
2475
|
+
);
|
|
2476
|
+
}
|
|
2477
|
+
const merchantSettlement = parseMerchantSettlement(retryResponse.headers.get("PAYMENT-RESPONSE"));
|
|
2478
|
+
if (receipt.merchant && merchantSettlement.settlementTxHash) {
|
|
2479
|
+
receipt.merchant.settlementTxHash = merchantSettlement.settlementTxHash;
|
|
2480
|
+
receipt.merchant.settlementExplorerUrl = buildExplorerUrl(
|
|
2481
|
+
receipt.chainId,
|
|
2482
|
+
merchantSettlement.settlementTxHash
|
|
2483
|
+
);
|
|
2484
|
+
}
|
|
2485
|
+
await this.reportEvidence({
|
|
2486
|
+
paymentId: receipt.paymentId,
|
|
2487
|
+
rail: "x402",
|
|
2488
|
+
txHash: receipt.txHash,
|
|
2489
|
+
resourceUrl: receipt.resourceUrl,
|
|
2490
|
+
merchantStatus: retryResponse.status,
|
|
2491
|
+
challengePayload: paymentRequired,
|
|
2492
|
+
selectedPayment: receipt.accepted,
|
|
2493
|
+
paymentProofHeaderName: "X-PAYMENT",
|
|
2494
|
+
paymentProofHeader: receipt.paymentHeader,
|
|
2495
|
+
protocolReceiptHeaderName: "PAYMENT-RESPONSE",
|
|
2496
|
+
protocolReceiptHeader: retryResponse.headers.get("PAYMENT-RESPONSE") ?? void 0
|
|
2497
|
+
});
|
|
2498
|
+
await this.reportMerchantReceipt(receipt.paymentId, retryResponse);
|
|
2499
|
+
return retryResponse;
|
|
2500
|
+
}
|
|
2501
|
+
/**
|
|
2502
|
+
* #956: capture the merchant's OWN receipt when the paid response carries
|
|
2503
|
+
* one, and report it to Haven so the reporting feed can attach it next to
|
|
2504
|
+
* the Haven-generated payment evidence (#498). Two supported signals on the
|
|
2505
|
+
* paid response:
|
|
2506
|
+
*
|
|
2507
|
+
* x-receipt-json: base64-encoded JSON receipt document (inline)
|
|
2508
|
+
* x-receipt-url: https URL to the receipt document (reference)
|
|
2509
|
+
*
|
|
2510
|
+
* Strictly best-effort: absence is the normal case, and no failure here may
|
|
2511
|
+
* ever affect the completed payment — the response is already paid for.
|
|
2512
|
+
*/
|
|
2513
|
+
async reportMerchantReceipt(paymentId, response) {
|
|
2514
|
+
try {
|
|
2515
|
+
const inlineB64 = response.headers.get("x-receipt-json");
|
|
2516
|
+
const url = response.headers.get("x-receipt-url");
|
|
2517
|
+
if (!inlineB64 && !url) return;
|
|
2518
|
+
let body = null;
|
|
2519
|
+
if (inlineB64) {
|
|
2520
|
+
if (inlineB64.length > Math.ceil(64 * 1024 * 4 / 3)) return;
|
|
2521
|
+
const decoded = JSON.parse(Buffer.from(inlineB64, "base64").toString("utf8"));
|
|
2522
|
+
if (decoded && typeof decoded === "object") body = { json: decoded };
|
|
2523
|
+
} else if (url && url.startsWith("https://") && url.length <= 2048) {
|
|
2524
|
+
body = { url };
|
|
2525
|
+
}
|
|
2526
|
+
if (!body) return;
|
|
2527
|
+
await this.post(`/machine-payments/${paymentId}/merchant-receipt`, body);
|
|
2528
|
+
} catch {
|
|
2529
|
+
}
|
|
2530
|
+
}
|
|
2531
|
+
async resolveCompletionContext(input) {
|
|
2532
|
+
const status = await this.getPaymentStatus(input.paymentId);
|
|
2533
|
+
if (status.rail !== "x402") {
|
|
2534
|
+
throw new HavenPaymentStateError(
|
|
2535
|
+
`Payment ${status.paymentId} is ${status.rail}, not x402.`,
|
|
2536
|
+
409,
|
|
2537
|
+
status
|
|
2538
|
+
);
|
|
2539
|
+
}
|
|
2540
|
+
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;
|
|
2541
|
+
if (!readyForMerchantCompletion) {
|
|
2542
|
+
throw new HavenPaymentStateError(status.message, paymentStateStatusCode(status.status, 409), status);
|
|
2543
|
+
}
|
|
2544
|
+
if (!input.noFundingLeg && !status.txHash) {
|
|
2545
|
+
throw new HavenApiError(
|
|
2546
|
+
`x402 payment ${status.paymentId} is ready for merchant completion but has no Haven transaction hash.`,
|
|
2547
|
+
502,
|
|
2548
|
+
status,
|
|
2549
|
+
status.paymentId
|
|
2550
|
+
);
|
|
2551
|
+
}
|
|
2552
|
+
const approvedResourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null;
|
|
2553
|
+
if (approvedResourceUrl && approvedResourceUrl !== input.url) {
|
|
2554
|
+
throw new HavenApiError(
|
|
2555
|
+
"x402 merchant completion does not match the approved resource URL.",
|
|
2556
|
+
409,
|
|
2557
|
+
{ status, url: input.url },
|
|
2558
|
+
status.paymentId
|
|
2559
|
+
);
|
|
2560
|
+
}
|
|
2561
|
+
return {
|
|
2562
|
+
paymentId: status.paymentId,
|
|
2563
|
+
txHash: status.txHash,
|
|
2564
|
+
resourceUrl: approvedResourceUrl ?? input.url,
|
|
2565
|
+
merchantAddress: status.merchantAddress ?? status.x402?.merchantAddress ?? null
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
async resolveWalletForMerchantCall() {
|
|
2569
|
+
const localWallet = x402PayerAddress(this.delegateAddress, this.x402Wallet);
|
|
2570
|
+
if (localWallet) return localWallet;
|
|
2571
|
+
try {
|
|
2572
|
+
const agent = await this.getAgent();
|
|
2573
|
+
return agent.delegateAddress ?? void 0;
|
|
2574
|
+
} catch {
|
|
2575
|
+
return void 0;
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
// #1328: authorizeMachinePayment / authorizeMppDemoPayment / resumeAuthorizedMpp
|
|
2579
|
+
// / resumeMppPayment / fetchWithMachinePayment / retryMppRequest (the
|
|
2580
|
+
// MACHINE-PAYMENT-CHALLENGE / mpp_demo client surface) are retired — the
|
|
2581
|
+
// backend's POST /machine-payments/authorize refuses unconditionally now,
|
|
2582
|
+
// and MACHINE-PAYMENT-CHALLENGE was never produced by any other Haven
|
|
2583
|
+
// surface. Use the x402 flow (authorizeX402 / fetch / quoteX402 / payX402Quote)
|
|
2584
|
+
// for agent-to-merchant payments.
|
|
2585
|
+
async recordRetryRejected(input) {
|
|
2586
|
+
try {
|
|
2587
|
+
await this.post("/machine-payments/reconciliation-events", {
|
|
2588
|
+
paymentId: input.paymentId,
|
|
2589
|
+
rail: input.rail,
|
|
2590
|
+
eventType: "merchant_retry_rejected_after_payment",
|
|
2591
|
+
txHash: input.txHash,
|
|
2592
|
+
reason: `Merchant returned HTTP ${input.merchant.merchant_status} after Haven payment confirmation`,
|
|
2593
|
+
details: {
|
|
2594
|
+
resource_url: input.resourceUrl,
|
|
2595
|
+
retry_status: input.merchant.merchant_status,
|
|
2596
|
+
retry_body: input.merchant.merchant_body.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,
|
|
2597
|
+
...input.details
|
|
2598
|
+
}
|
|
2599
|
+
});
|
|
2600
|
+
} catch {
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
async reportEvidence(input) {
|
|
2604
|
+
try {
|
|
2605
|
+
await this.post("/machine-payments/evidence", {
|
|
2606
|
+
paymentId: input.paymentId,
|
|
2607
|
+
rail: input.rail,
|
|
2608
|
+
txHash: input.txHash,
|
|
2609
|
+
resourceUrl: input.resourceUrl,
|
|
2610
|
+
merchantStatus: input.merchantStatus,
|
|
2611
|
+
challengePayload: input.challengePayload,
|
|
2612
|
+
selectedPayment: input.selectedPayment,
|
|
2613
|
+
paymentProofHeaderName: input.paymentProofHeaderName,
|
|
2614
|
+
paymentProofHeader: input.paymentProofHeader,
|
|
2615
|
+
protocolReceiptHeaderName: input.protocolReceiptHeaderName,
|
|
2616
|
+
protocolReceiptHeader: input.protocolReceiptHeader,
|
|
2617
|
+
protocolReceiptPayload: input.protocolReceiptHeader ? parseProtocolReceiptHeader(input.protocolReceiptHeader) : void 0
|
|
2618
|
+
});
|
|
2619
|
+
} catch {
|
|
2620
|
+
}
|
|
2621
|
+
}
|
|
2622
|
+
};
|
|
2623
|
+
function parseMerchantSettlement(header) {
|
|
2624
|
+
if (!header) return {};
|
|
2625
|
+
const parsed = parseProtocolReceiptHeader(header);
|
|
2626
|
+
const tx = typeof parsed?.transaction === "string" ? parsed.transaction : typeof parsed?.txHash === "string" ? parsed.txHash : typeof parsed?.tx_hash === "string" ? parsed.tx_hash : null;
|
|
2627
|
+
return { settlementTxHash: tx };
|
|
2628
|
+
}
|
|
2629
|
+
function parseProtocolReceiptHeader(value) {
|
|
2630
|
+
try {
|
|
2631
|
+
return decodeBase64Json(value);
|
|
2632
|
+
} catch {
|
|
2633
|
+
try {
|
|
2634
|
+
return JSON.parse(value);
|
|
2635
|
+
} catch {
|
|
2636
|
+
return void 0;
|
|
2637
|
+
}
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
// src/client.ts
|
|
2642
|
+
var DEFAULT_CONFIRMATION_TIMEOUT = 9e4;
|
|
2643
|
+
var DEFAULT_POLLING_INTERVAL = 3e3;
|
|
1142
2644
|
function x402TypedDataDigest(typedData) {
|
|
1143
2645
|
if (!typedData || typeof typedData !== "object") return void 0;
|
|
1144
2646
|
try {
|
|
@@ -1169,48 +2671,78 @@ function mapCatalogEntry(entry) {
|
|
|
1169
2671
|
};
|
|
1170
2672
|
}
|
|
1171
2673
|
var HavenClient = class {
|
|
1172
|
-
apiKey;
|
|
1173
2674
|
delegateKey;
|
|
1174
|
-
|
|
2675
|
+
havenApi;
|
|
2676
|
+
accountReads;
|
|
2677
|
+
delegateSweep;
|
|
1175
2678
|
x402Wallet;
|
|
1176
|
-
|
|
1177
|
-
merchantTimeout;
|
|
2679
|
+
merchantTransport;
|
|
1178
2680
|
confirmationTimeout;
|
|
1179
2681
|
pollingInterval;
|
|
1180
2682
|
chainRpcs;
|
|
1181
2683
|
inFlightX402 = /* @__PURE__ */ new Map();
|
|
1182
|
-
x402ReceiptCache = /* @__PURE__ */ new Map();
|
|
1183
2684
|
/**
|
|
1184
|
-
*
|
|
1185
|
-
*
|
|
1186
|
-
* scoping so concurrent requests don't race on shared mutable state.
|
|
2685
|
+
* The EIP-3009 funding-leg lifecycle (#1618). The facade holds a reference
|
|
2686
|
+
* and delegates; it does not reimplement any of it.
|
|
1187
2687
|
*/
|
|
1188
|
-
|
|
2688
|
+
fundingLeg;
|
|
1189
2689
|
/**
|
|
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.
|
|
2690
|
+
* The erc7710 direct-settlement lifecycle (#1619). Separate from the funding
|
|
2691
|
+
* leg on purpose: this scheme has no funding leg to share.
|
|
1194
2692
|
*/
|
|
1195
|
-
|
|
1196
|
-
/**
|
|
1197
|
-
|
|
2693
|
+
erc7710;
|
|
2694
|
+
/**
|
|
2695
|
+
* Merchant delivery and the evidence trail behind it (#1620). Scheme-neutral
|
|
2696
|
+
* on purpose — both settlement schemes finish through the same door.
|
|
2697
|
+
*/
|
|
2698
|
+
merchantCompletion;
|
|
1198
2699
|
/** Delegate address derived from the private key (if provided) */
|
|
1199
2700
|
delegateAddress;
|
|
1200
2701
|
constructor(config) {
|
|
1201
|
-
this.apiKey = config.apiKey;
|
|
1202
2702
|
this.delegateKey = config.delegateKey;
|
|
1203
|
-
this.
|
|
2703
|
+
this.havenApi = new HavenApiTransport(config);
|
|
2704
|
+
this.accountReads = new AccountReads({
|
|
2705
|
+
transport: this.havenApi,
|
|
2706
|
+
getPaymentStatus: (paymentId) => this.getPaymentStatus(paymentId)
|
|
2707
|
+
});
|
|
2708
|
+
this.delegateSweep = new DelegateSweepApi({
|
|
2709
|
+
transport: this.havenApi,
|
|
2710
|
+
delegateKey: config.delegateKey,
|
|
2711
|
+
chainRpcs: config.chainRpcs ?? {},
|
|
2712
|
+
getAgent: () => this.getAgent(),
|
|
2713
|
+
buildExplorerUrl: (chainId, hash) => buildExplorerUrl(chainId, hash)
|
|
2714
|
+
});
|
|
1204
2715
|
this.x402Wallet = config.x402Wallet;
|
|
1205
|
-
this.
|
|
1206
|
-
this.merchantTimeout = config.merchantTimeout ?? DEFAULT_MERCHANT_TIMEOUT;
|
|
2716
|
+
this.merchantTransport = new McpMerchantTransport({ merchantTimeout: config.merchantTimeout });
|
|
1207
2717
|
this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT;
|
|
1208
2718
|
this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL;
|
|
1209
2719
|
this.chainRpcs = config.chainRpcs ?? {};
|
|
1210
|
-
this.defaultHeaders = { ...config.defaultHeaders ?? {} };
|
|
1211
2720
|
if (this.delegateKey) {
|
|
1212
2721
|
this.delegateAddress = addressFromKey(this.delegateKey);
|
|
1213
2722
|
}
|
|
2723
|
+
this.fundingLeg = new X402FundingLeg({
|
|
2724
|
+
delegateKey: this.delegateKey,
|
|
2725
|
+
delegateAddress: this.delegateAddress,
|
|
2726
|
+
x402Wallet: this.x402Wallet,
|
|
2727
|
+
chainRpcs: this.chainRpcs,
|
|
2728
|
+
post: (path, body) => this.post(path, body),
|
|
2729
|
+
signForData: (signData) => this.signForData(signData),
|
|
2730
|
+
assertSignableAuthorizationState: (label, raw) => this.throwIfNonSignableAuthorizationState(label, raw)
|
|
2731
|
+
});
|
|
2732
|
+
this.merchantCompletion = new MerchantCompletion({
|
|
2733
|
+
post: (path, body) => this.post(path, body),
|
|
2734
|
+
merchantTransport: this.merchantTransport,
|
|
2735
|
+
getPaymentStatus: (paymentId) => this.getPaymentStatus(paymentId),
|
|
2736
|
+
getAgent: () => this.getAgent(),
|
|
2737
|
+
delegateAddress: this.delegateAddress,
|
|
2738
|
+
x402Wallet: this.x402Wallet
|
|
2739
|
+
});
|
|
2740
|
+
this.erc7710 = new X402Erc7710({
|
|
2741
|
+
delegateKey: this.delegateKey,
|
|
2742
|
+
post: (path, body) => this.post(path, body),
|
|
2743
|
+
signForData: (signData) => this.signForData(signData),
|
|
2744
|
+
getAgent: () => this.getAgent()
|
|
2745
|
+
});
|
|
1214
2746
|
}
|
|
1215
2747
|
/**
|
|
1216
2748
|
* Run `fn` with extra Haven-API headers scoped to the async work it
|
|
@@ -1228,7 +2760,7 @@ var HavenClient = class {
|
|
|
1228
2760
|
* context.
|
|
1229
2761
|
*/
|
|
1230
2762
|
withRequestContext(headers, fn) {
|
|
1231
|
-
return this.
|
|
2763
|
+
return this.havenApi.withRequestContext(headers, fn);
|
|
1232
2764
|
}
|
|
1233
2765
|
// ── High-Level API ───────────────────────────────────────────────
|
|
1234
2766
|
/**
|
|
@@ -1264,7 +2796,7 @@ var HavenClient = class {
|
|
|
1264
2796
|
...request.idempotencyKey ? { idempotency_key: request.idempotencyKey } : {}
|
|
1265
2797
|
});
|
|
1266
2798
|
if (raw.status === "pending_approval") {
|
|
1267
|
-
|
|
2799
|
+
throwPaymentStateError("Payment", raw);
|
|
1268
2800
|
}
|
|
1269
2801
|
return {
|
|
1270
2802
|
paymentId: raw.payment_id,
|
|
@@ -1327,7 +2859,7 @@ var HavenClient = class {
|
|
|
1327
2859
|
...new TextEncoder().encode(JSON.stringify(paymentRequired)).length <= 65536 ? { paymentRequired } : {}
|
|
1328
2860
|
});
|
|
1329
2861
|
if (raw.status !== "pending_signature") {
|
|
1330
|
-
|
|
2862
|
+
throwPaymentStateError("x402 payment", raw);
|
|
1331
2863
|
}
|
|
1332
2864
|
if (!raw.sign_data?.hash) {
|
|
1333
2865
|
throw new HavenApiError("No sign_hash returned from x402/authorize", 500, raw);
|
|
@@ -1448,7 +2980,7 @@ var HavenClient = class {
|
|
|
1448
2980
|
*/
|
|
1449
2981
|
async getPayment(paymentId) {
|
|
1450
2982
|
const raw = await this.get(`/payments/${paymentId}`);
|
|
1451
|
-
return
|
|
2983
|
+
return mapPaymentResult(raw, buildExplorerUrl);
|
|
1452
2984
|
}
|
|
1453
2985
|
/**
|
|
1454
2986
|
* Get agent-actionable status for a payment intent or approval request.
|
|
@@ -1458,137 +2990,35 @@ var HavenClient = class {
|
|
|
1458
2990
|
*/
|
|
1459
2991
|
async getPaymentStatus(paymentId) {
|
|
1460
2992
|
const raw = await this.get(`/machine-payments/${paymentId}/status`);
|
|
1461
|
-
return
|
|
2993
|
+
return mapPaymentStatusResult(raw);
|
|
1462
2994
|
}
|
|
1463
2995
|
/**
|
|
1464
2996
|
* Get the agent identity tied to this API key.
|
|
1465
2997
|
*/
|
|
1466
2998
|
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
|
-
};
|
|
1492
|
-
}
|
|
1493
|
-
/**
|
|
1494
|
-
* One-shot "am I ready?" bootstrap: identity + live spend authority + a
|
|
1495
|
-
* readiness signal, in a single call. Folds {@link getAgent} and
|
|
1496
|
-
* {@link getAllowances} together and derives a {@link HavenAgentReadiness}
|
|
1497
|
-
* so an agent can answer "who am I and can I pay right now" at session start
|
|
1498
|
-
* without two round trips and manual assembly.
|
|
1499
|
-
*/
|
|
1500
|
-
async getAgentSummary() {
|
|
1501
|
-
const [agent, allowanceSummary] = await Promise.all([
|
|
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 };
|
|
2999
|
+
return this.accountReads.getAgent();
|
|
1519
3000
|
}
|
|
1520
3001
|
/**
|
|
1521
|
-
*
|
|
1522
|
-
*
|
|
1523
|
-
*
|
|
1524
|
-
*
|
|
1525
|
-
*
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
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
|
-
};
|
|
3002
|
+
* One-shot "am I ready?" bootstrap: identity + live spend authority + a
|
|
3003
|
+
* readiness signal, in a single call. Folds {@link getAgent} and
|
|
3004
|
+
* {@link getAllowances} together and derives a {@link HavenAgentReadiness}
|
|
3005
|
+
* so an agent can answer "who am I and can I pay right now" at session start
|
|
3006
|
+
* without two round trips and manual assembly.
|
|
3007
|
+
*/
|
|
3008
|
+
async getAgentSummary() {
|
|
3009
|
+
return this.accountReads.getAgentSummary();
|
|
3010
|
+
}
|
|
3011
|
+
/**
|
|
3012
|
+
* Sweep stranded USDC and ETH from the delegate EOA back to the originating Safe.
|
|
3013
|
+
*
|
|
3014
|
+
* The delegate key held by this client signs and submits the transfer transactions
|
|
3015
|
+
* directly — Haven's backend never handles the key or constructs signed txs
|
|
3016
|
+
* (CASP/MiCA Red Line #2). Funds always go to the Safe linked to this agent.
|
|
3017
|
+
*
|
|
3018
|
+
* Requires `chainRpcs` to be set for the agent's chain in `HavenClientConfig`.
|
|
3019
|
+
*/
|
|
3020
|
+
async sweepDelegate() {
|
|
3021
|
+
return this.delegateSweep.sweepDelegate();
|
|
1592
3022
|
}
|
|
1593
3023
|
/**
|
|
1594
3024
|
* Hosted (keyless) split-signer sweep — step 1 of 2.
|
|
@@ -1599,7 +3029,7 @@ var HavenClient = class {
|
|
|
1599
3029
|
* edge signer's `haven_sign_sweep_delegate`. No key is required on this client.
|
|
1600
3030
|
*/
|
|
1601
3031
|
async prepareSweep() {
|
|
1602
|
-
return this.
|
|
3032
|
+
return this.delegateSweep.prepareSweep();
|
|
1603
3033
|
}
|
|
1604
3034
|
/**
|
|
1605
3035
|
* Hosted (keyless) split-signer sweep — step 2 of 2.
|
|
@@ -1609,40 +3039,13 @@ var HavenClient = class {
|
|
|
1609
3039
|
* the key.
|
|
1610
3040
|
*/
|
|
1611
3041
|
async submitSweep(authorization, signature) {
|
|
1612
|
-
return this.
|
|
1613
|
-
authorization,
|
|
1614
|
-
signature
|
|
1615
|
-
});
|
|
3042
|
+
return this.delegateSweep.submitSweep(authorization, signature);
|
|
1616
3043
|
}
|
|
1617
3044
|
/**
|
|
1618
3045
|
* Get configured and on-chain allowances for the authenticated agent.
|
|
1619
3046
|
*/
|
|
1620
3047
|
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
|
-
};
|
|
3048
|
+
return this.accountReads.getAllowances();
|
|
1646
3049
|
}
|
|
1647
3050
|
/**
|
|
1648
3051
|
* Post-purchase allowance/budget summary for a settled payment (#1310).
|
|
@@ -1673,62 +3076,7 @@ var HavenClient = class {
|
|
|
1673
3076
|
* phrase it as guaranteed-fresh.
|
|
1674
3077
|
*/
|
|
1675
3078
|
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
|
-
}
|
|
3079
|
+
return this.accountReads.getPostPurchaseAllowanceSummary(paymentId);
|
|
1732
3080
|
}
|
|
1733
3081
|
/**
|
|
1734
3082
|
* `haven_get_payment_status` convenience: fetch status and, for a
|
|
@@ -1785,9 +3133,7 @@ var HavenClient = class {
|
|
|
1785
3133
|
* List recent machine-payment receipts/evidence for bookkeeping.
|
|
1786
3134
|
*/
|
|
1787
3135
|
async listReceipts(options = {}) {
|
|
1788
|
-
|
|
1789
|
-
const raw = await this.get(`/machine-payments/receipts${query}`);
|
|
1790
|
-
return raw.receipts.map((receipt) => this.mapPaymentReceipt(receipt));
|
|
3136
|
+
return this.accountReads.listReceipts(options);
|
|
1791
3137
|
}
|
|
1792
3138
|
/**
|
|
1793
3139
|
* Fetch the verifiable receipt bundle for a settled payment and verify it
|
|
@@ -1796,10 +3142,7 @@ var HavenClient = class {
|
|
|
1796
3142
|
* authorisation, so the result is trustworthy even if the backend lied.
|
|
1797
3143
|
*/
|
|
1798
3144
|
async getReceipt(paymentId) {
|
|
1799
|
-
|
|
1800
|
-
`/payments/${paymentId}/receipt`
|
|
1801
|
-
);
|
|
1802
|
-
return { receipt, verification: verifyPaymentReceipt(receipt) };
|
|
3145
|
+
return this.accountReads.getReceipt(paymentId);
|
|
1803
3146
|
}
|
|
1804
3147
|
/**
|
|
1805
3148
|
* Rehydrate the x402 resume-state bundle for a payment id (#1328: the MPP
|
|
@@ -1852,17 +3195,16 @@ var HavenClient = class {
|
|
|
1852
3195
|
);
|
|
1853
3196
|
}
|
|
1854
3197
|
const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option);
|
|
1855
|
-
const cached = this.
|
|
1856
|
-
if (cached
|
|
3198
|
+
const cached = this.fundingLeg.cachedReceipt(idempotencyKey);
|
|
3199
|
+
if (cached) return cached;
|
|
1857
3200
|
const inFlight = this.inFlightX402.get(idempotencyKey);
|
|
1858
3201
|
if (inFlight) return inFlight;
|
|
1859
|
-
const promise = this.
|
|
3202
|
+
const promise = this.fundingLeg.authorize(paymentRequired, option, idempotencyKey);
|
|
1860
3203
|
this.inFlightX402.set(idempotencyKey, promise);
|
|
1861
3204
|
try {
|
|
1862
3205
|
return await promise;
|
|
1863
3206
|
} catch (err) {
|
|
1864
|
-
|
|
1865
|
-
rail: "x402",
|
|
3207
|
+
attachResumeState(err, {
|
|
1866
3208
|
paymentRequired,
|
|
1867
3209
|
accepted: option,
|
|
1868
3210
|
idempotencyKey
|
|
@@ -1877,9 +3219,9 @@ var HavenClient = class {
|
|
|
1877
3219
|
* payment or approval request.
|
|
1878
3220
|
*/
|
|
1879
3221
|
async quoteX402(url, init, options = {}) {
|
|
1880
|
-
const initialInit =
|
|
1881
|
-
const request =
|
|
1882
|
-
const response = await this.
|
|
3222
|
+
const initialInit = withX402Wallet(init, x402PayerAddress(this.delegateAddress, this.x402Wallet));
|
|
3223
|
+
const request = snapshotX402Request(url, initialInit);
|
|
3224
|
+
const response = await this.merchantTransport.fetch(url, initialInit);
|
|
1883
3225
|
if (response.status !== 402) {
|
|
1884
3226
|
throw new X402UnexpectedStatusError(
|
|
1885
3227
|
`Expected an x402 quote response with HTTP 402, got HTTP ${response.status}.`,
|
|
@@ -1890,8 +3232,8 @@ var HavenClient = class {
|
|
|
1890
3232
|
throw new HavenApiError("quoteX402 only supports standard x402 Payment Required responses.", 400);
|
|
1891
3233
|
}
|
|
1892
3234
|
const paymentRequired = await parsePaymentRequiredResponse(response);
|
|
1893
|
-
const mcpTransport = await this.
|
|
1894
|
-
return
|
|
3235
|
+
const mcpTransport = await this.merchantTransport.detect(url, paymentRequired, response);
|
|
3236
|
+
return buildX402Quote(paymentRequired, request, options.idempotencyKey, mcpTransport);
|
|
1895
3237
|
}
|
|
1896
3238
|
/**
|
|
1897
3239
|
* Probe an MCP tool for its x402 quote without creating a payment.
|
|
@@ -1904,8 +3246,8 @@ var HavenClient = class {
|
|
|
1904
3246
|
* callers that need a plain x402 endpoint must use {@link quoteX402}.
|
|
1905
3247
|
*/
|
|
1906
3248
|
async quoteMcpX402(url, init, options = {}) {
|
|
1907
|
-
const wallet = await this.
|
|
1908
|
-
const sessionId = await this.
|
|
3249
|
+
const wallet = await this.merchantCompletion.resolveWalletForMerchantCall();
|
|
3250
|
+
const sessionId = await this.merchantTransport.initialize(url, init, wallet);
|
|
1909
3251
|
if (!sessionId) {
|
|
1910
3252
|
throw new HavenApiError(
|
|
1911
3253
|
"The merchant did not establish an MCP session before the x402 quote. No payment was created.",
|
|
@@ -1913,238 +3255,71 @@ var HavenClient = class {
|
|
|
1913
3255
|
{ mcpSessionNotEstablished: true }
|
|
1914
3256
|
);
|
|
1915
3257
|
}
|
|
1916
|
-
let requestInit =
|
|
1917
|
-
requestInit = this.
|
|
3258
|
+
let requestInit = withX402Wallet(init, wallet);
|
|
3259
|
+
requestInit = this.merchantTransport.withSessionHeaders(requestInit, sessionId);
|
|
1918
3260
|
const quote = await this.quoteX402(url, requestInit, options);
|
|
1919
3261
|
return {
|
|
1920
3262
|
...quote,
|
|
1921
3263
|
mcpTransport: quote.mcpTransport ?? { handshakeRequired: true, source: "path" }
|
|
1922
3264
|
};
|
|
1923
3265
|
}
|
|
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
|
|
3266
|
+
/**
|
|
3267
|
+
* Pay a previously inspected x402 quote and retry the exact captured request.
|
|
3268
|
+
*/
|
|
3269
|
+
async payX402Quote(quote, options = {}) {
|
|
3270
|
+
const idempotencyKey = options.idempotencyKey ?? quote.idempotencyKey;
|
|
3271
|
+
try {
|
|
3272
|
+
const receipt = await this.authorizeX402(quote.paymentRequired, { idempotencyKey });
|
|
3273
|
+
return this.merchantCompletion.retryRequest(
|
|
3274
|
+
quote.request.url,
|
|
3275
|
+
requestInitFromSnapshot(quote.request),
|
|
3276
|
+
quote.paymentRequired,
|
|
3277
|
+
receipt
|
|
2112
3278
|
);
|
|
3279
|
+
} catch (err) {
|
|
3280
|
+
attachResumeState(err, {
|
|
3281
|
+
paymentRequired: quote.paymentRequired,
|
|
3282
|
+
accepted: quote.accepted,
|
|
3283
|
+
idempotencyKey,
|
|
3284
|
+
request: quote.request
|
|
3285
|
+
});
|
|
3286
|
+
throw err;
|
|
2113
3287
|
}
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
3288
|
+
}
|
|
3289
|
+
/**
|
|
3290
|
+
* Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).
|
|
3291
|
+
*
|
|
3292
|
+
* **Nothing has settled when this returns** — that is why it does not return
|
|
3293
|
+
* an `X402Receipt`; the caller still has to retry the merchant with the
|
|
3294
|
+
* header. **MCP callers must pass `options.resourceUrl`**, because an in-band
|
|
3295
|
+
* MCP 402 challenge frequently carries no `resource` object at all.
|
|
3296
|
+
*
|
|
3297
|
+
* Both caveats, and why this scheme has no funding leg, are explained where
|
|
3298
|
+
* the lifecycle lives: `x402-erc7710.ts` (#1619).
|
|
3299
|
+
*/
|
|
3300
|
+
async settleX402Erc7710(paymentRequired, options = {}) {
|
|
3301
|
+
return this.erc7710.settle(paymentRequired, options);
|
|
3302
|
+
}
|
|
3303
|
+
/**
|
|
3304
|
+
* The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build
|
|
3305
|
+
* the request, and return the child to be signed — without signing it.
|
|
3306
|
+
*
|
|
3307
|
+
* Split out because the hosted topology cannot use `settleX402Erc7710()`:
|
|
3308
|
+
* that method signs in-process with `delegateKey`, and hosted Haven does not
|
|
3309
|
+
* have one and must not.
|
|
3310
|
+
*/
|
|
3311
|
+
async prepareX402Erc7710(paymentRequired, options = {}) {
|
|
3312
|
+
return this.erc7710.prepare(paymentRequired, options);
|
|
2126
3313
|
}
|
|
2127
3314
|
/**
|
|
2128
3315
|
* The SETTLE half (#1456): exchange the signed child for the merchant header.
|
|
2129
3316
|
*
|
|
2130
3317
|
* The SDK builds no header on this path — the backend assembles the MetaMask
|
|
2131
|
-
* erc7710 payload
|
|
2132
|
-
*
|
|
2133
|
-
* hosted boundary) is irrelevant here.
|
|
3318
|
+
* erc7710 payload. Whoever produced the signature (an in-process delegate
|
|
3319
|
+
* key, or the local edge signer over the hosted boundary) is irrelevant.
|
|
2134
3320
|
*/
|
|
2135
3321
|
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;
|
|
3322
|
+
return this.erc7710.submit(paymentId, signature);
|
|
2148
3323
|
}
|
|
2149
3324
|
async resumeAuthorizedX402(input) {
|
|
2150
3325
|
if (!this.delegateKey) {
|
|
@@ -2163,11 +3338,11 @@ var HavenClient = class {
|
|
|
2163
3338
|
);
|
|
2164
3339
|
}
|
|
2165
3340
|
const idempotencyKey = input.idempotencyKey ?? buildX402IdempotencyKey(input.paymentRequired, option);
|
|
2166
|
-
const cached = this.
|
|
2167
|
-
if (cached
|
|
3341
|
+
const cached = this.fundingLeg.cachedReceipt(idempotencyKey);
|
|
3342
|
+
if (cached) return cached;
|
|
2168
3343
|
const status = await this.getPaymentStatus(input.paymentId);
|
|
2169
|
-
|
|
2170
|
-
const canFund = await this.delegateCanFund(
|
|
3344
|
+
assertCanResumeX402(status, input.paymentRequired, option);
|
|
3345
|
+
const canFund = await this.fundingLeg.delegateCanFund(
|
|
2171
3346
|
status.chainId ?? chainIdFromNetwork(option.network),
|
|
2172
3347
|
option.asset,
|
|
2173
3348
|
x402AuthorizationAmount(option)
|
|
@@ -2175,20 +3350,20 @@ var HavenClient = class {
|
|
|
2175
3350
|
if (canFund === false) {
|
|
2176
3351
|
throw new X402AlreadySettledError(
|
|
2177
3352
|
`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.
|
|
3353
|
+
this.fundingLeg.receiptFromStatus(input.paymentRequired, option, void 0, status),
|
|
2179
3354
|
"settled"
|
|
2180
3355
|
);
|
|
2181
3356
|
}
|
|
2182
|
-
const paymentHeader = await this.
|
|
2183
|
-
const receipt = this.
|
|
2184
|
-
this.
|
|
3357
|
+
const paymentHeader = await this.fundingLeg.createPaymentHeader(input.paymentRequired, option);
|
|
3358
|
+
const receipt = this.fundingLeg.receiptFromStatus(input.paymentRequired, option, paymentHeader, status);
|
|
3359
|
+
this.fundingLeg.cacheReceipt(idempotencyKey, paymentHeader, receipt);
|
|
2185
3360
|
return receipt;
|
|
2186
3361
|
}
|
|
2187
3362
|
async resumeX402Payment(input) {
|
|
2188
3363
|
const inputInit = "init" in input ? input.init : void 0;
|
|
2189
|
-
const initialInit =
|
|
2190
|
-
inputInit ?? (input.request ?
|
|
2191
|
-
this.
|
|
3364
|
+
const initialInit = withX402Wallet(
|
|
3365
|
+
inputInit ?? (input.request ? requestInitFromSnapshot(input.request) : void 0),
|
|
3366
|
+
x402PayerAddress(this.delegateAddress, this.x402Wallet)
|
|
2192
3367
|
);
|
|
2193
3368
|
let paymentRequired = input.paymentRequired;
|
|
2194
3369
|
const url = input.url ?? input.request?.url;
|
|
@@ -2196,7 +3371,7 @@ var HavenClient = class {
|
|
|
2196
3371
|
if (!url) {
|
|
2197
3372
|
throw new HavenApiError("x402 resume requires the original URL or a captured request snapshot.", 400);
|
|
2198
3373
|
}
|
|
2199
|
-
const response = await this.
|
|
3374
|
+
const response = await this.merchantTransport.fetch(url, initialInit);
|
|
2200
3375
|
if (response.status !== 402) {
|
|
2201
3376
|
throw new HavenApiError("Expected the original x402 request to return HTTP 402 before resuming.", 400);
|
|
2202
3377
|
}
|
|
@@ -2207,7 +3382,7 @@ var HavenClient = class {
|
|
|
2207
3382
|
paymentRequired,
|
|
2208
3383
|
idempotencyKey: input.idempotencyKey
|
|
2209
3384
|
});
|
|
2210
|
-
return this.
|
|
3385
|
+
return this.merchantCompletion.retryRequest(url ?? paymentRequired.resource.url, initialInit, paymentRequired, receipt);
|
|
2211
3386
|
}
|
|
2212
3387
|
/**
|
|
2213
3388
|
* Fetch wrapper that automatically handles HTTP 402 responses.
|
|
@@ -2221,268 +3396,57 @@ var HavenClient = class {
|
|
|
2221
3396
|
* ```
|
|
2222
3397
|
*
|
|
2223
3398
|
* **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)
|
|
3399
|
+
* MCP-shaped — the URL path ends in `/mcp`, or the 402 body carries a
|
|
3400
|
+
* Coinbase Bazaar `extensions.bazaar` block — the SDK runs the MCP
|
|
3401
|
+
* `initialize` handshake, threads the resulting `mcp-session-id`,
|
|
3402
|
+
* `Accept: application/json, text/event-stream`, and `x402-wallet` headers
|
|
3403
|
+
* through every request, and collapses SSE responses to the JSON-RPC
|
|
3404
|
+
* `result`. The caller just passes `(url, { body })` and never sees the
|
|
3405
|
+
* protocol plumbing. A non-MCP server (handshake error / no session id)
|
|
3406
|
+
* falls back to standard x402 behaviour.
|
|
2465
3407
|
*
|
|
2466
|
-
*
|
|
2467
|
-
* ever affect the completed payment — the response is already paid for.
|
|
3408
|
+
* Requires `delegateKey` to be set in the client config.
|
|
2468
3409
|
*/
|
|
2469
|
-
async
|
|
3410
|
+
async fetch(url, init, options = {}) {
|
|
3411
|
+
let mcpSessionId;
|
|
3412
|
+
if (this.merchantTransport.isMcpUrl(url)) {
|
|
3413
|
+
mcpSessionId = await this.merchantTransport.initialize(url, init);
|
|
3414
|
+
}
|
|
3415
|
+
let requestInit = withX402Wallet(init, x402PayerAddress(this.delegateAddress, this.x402Wallet));
|
|
3416
|
+
if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId);
|
|
3417
|
+
const response = await this.merchantTransport.fetch(url, requestInit);
|
|
3418
|
+
if (response.status !== 402) {
|
|
3419
|
+
return mcpSessionId ? this.merchantTransport.surfaceResult(response) : response;
|
|
3420
|
+
}
|
|
3421
|
+
let paymentRequired;
|
|
2470
3422
|
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);
|
|
3423
|
+
paymentRequired = await parsePaymentRequiredResponse(response);
|
|
2484
3424
|
} catch {
|
|
3425
|
+
return response;
|
|
3426
|
+
}
|
|
3427
|
+
if (!mcpSessionId && await this.merchantTransport.hasBazaarExtension(response)) {
|
|
3428
|
+
mcpSessionId = await this.merchantTransport.initialize(url, init);
|
|
3429
|
+
if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId);
|
|
3430
|
+
}
|
|
3431
|
+
const request = snapshotX402Request(url, requestInit);
|
|
3432
|
+
const option = selectStandardPaymentOption(paymentRequired.accepts);
|
|
3433
|
+
const idempotencyKey = options.idempotencyKey ?? (option ? buildX402IdempotencyKey(paymentRequired, option) : void 0);
|
|
3434
|
+
let receipt;
|
|
3435
|
+
try {
|
|
3436
|
+
receipt = await this.authorizeX402(paymentRequired, options);
|
|
3437
|
+
} catch (err) {
|
|
3438
|
+
if (option && idempotencyKey) {
|
|
3439
|
+
attachResumeState(err, {
|
|
3440
|
+
paymentRequired,
|
|
3441
|
+
accepted: option,
|
|
3442
|
+
idempotencyKey,
|
|
3443
|
+
request
|
|
3444
|
+
});
|
|
3445
|
+
}
|
|
3446
|
+
throw err;
|
|
2485
3447
|
}
|
|
3448
|
+
const retryResponse = await this.merchantCompletion.retryRequest(url, requestInit, paymentRequired, receipt);
|
|
3449
|
+
return mcpSessionId ? this.merchantTransport.surfaceResult(retryResponse) : retryResponse;
|
|
2486
3450
|
}
|
|
2487
3451
|
/**
|
|
2488
3452
|
* Deliver an already-signed x402 payment header to the merchant and return
|
|
@@ -2507,7 +3471,7 @@ var HavenClient = class {
|
|
|
2507
3471
|
* and before delivering the X-PAYMENT header, so the merchant's
|
|
2508
3472
|
* balanceOf(delegate) / transferWithAuthorization verification sees the funded
|
|
2509
3473
|
* balance — otherwise it rejects with "Payment verification failed". The
|
|
2510
|
-
* SDK's local path already does this (see
|
|
3474
|
+
* SDK's local path already does this (see `X402FundingLeg.authorize`); the hosted
|
|
2511
3475
|
* split flow regressed when the 5→3 collapse removed the incidental
|
|
2512
3476
|
* inter-call latency that used to mask it.
|
|
2513
3477
|
*
|
|
@@ -2524,28 +3488,25 @@ var HavenClient = class {
|
|
|
2524
3488
|
*/
|
|
2525
3489
|
async ensureFundingConfirmed(paymentId, fundingTxHash) {
|
|
2526
3490
|
const status = await this.getPaymentStatus(paymentId);
|
|
2527
|
-
await this.waitForFundingTx(fundingTxHash ?? status.txHash ?? void 0, status.chainId);
|
|
3491
|
+
await this.fundingLeg.waitForFundingTx(fundingTxHash ?? status.txHash ?? void 0, status.chainId);
|
|
2528
3492
|
}
|
|
2529
3493
|
async completeX402MerchantCall(input) {
|
|
2530
|
-
const evidenceContext = await this.
|
|
3494
|
+
const evidenceContext = await this.merchantCompletion.resolveCompletionContext({
|
|
2531
3495
|
paymentId: input.paymentId,
|
|
2532
3496
|
url: input.url,
|
|
2533
3497
|
noFundingLeg: input.noFundingLeg === true
|
|
2534
3498
|
});
|
|
2535
3499
|
const fundingTxHash = evidenceContext.txHash;
|
|
2536
|
-
const shouldHandshakeMcp = isMcpUrl(input.url) || input.mcpTransport?.handshakeRequired === true;
|
|
2537
|
-
const x402Wallet = shouldHandshakeMcp ? await this.
|
|
3500
|
+
const shouldHandshakeMcp = this.merchantTransport.isMcpUrl(input.url) || input.mcpTransport?.handshakeRequired === true;
|
|
3501
|
+
const x402Wallet = shouldHandshakeMcp ? await this.merchantCompletion.resolveWalletForMerchantCall() : x402PayerAddress(this.delegateAddress, this.x402Wallet);
|
|
2538
3502
|
let mcpSessionId;
|
|
2539
3503
|
if (shouldHandshakeMcp) {
|
|
2540
|
-
mcpSessionId = await this.
|
|
3504
|
+
mcpSessionId = await this.merchantTransport.initialize(input.url, input.init, x402Wallet);
|
|
2541
3505
|
}
|
|
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;
|
|
3506
|
+
let requestInit = withX402Wallet(input.init, x402Wallet) ?? {};
|
|
3507
|
+
if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId);
|
|
3508
|
+
const response = await this.merchantTransport.deliverPayment(input.url, requestInit, input.paymentHeader);
|
|
3509
|
+
const surfaced = mcpSessionId ? await this.merchantTransport.surfaceResult(response) : response;
|
|
2549
3510
|
const protocolReceiptHeader = surfaced.headers.get("PAYMENT-RESPONSE") ?? void 0;
|
|
2550
3511
|
const settlement = parseMerchantSettlement(protocolReceiptHeader ?? null);
|
|
2551
3512
|
const text = await surfaced.text();
|
|
@@ -2557,7 +3518,7 @@ var HavenClient = class {
|
|
|
2557
3518
|
}
|
|
2558
3519
|
if (!surfaced.ok) {
|
|
2559
3520
|
if (!input.noFundingLeg && fundingTxHash) {
|
|
2560
|
-
await this.
|
|
3521
|
+
await this.merchantCompletion.recordRetryRejected({
|
|
2561
3522
|
rail: "x402",
|
|
2562
3523
|
paymentId: evidenceContext.paymentId,
|
|
2563
3524
|
txHash: fundingTxHash,
|
|
@@ -2575,7 +3536,7 @@ var HavenClient = class {
|
|
|
2575
3536
|
}
|
|
2576
3537
|
} else {
|
|
2577
3538
|
if (!input.noFundingLeg && fundingTxHash) {
|
|
2578
|
-
await this.
|
|
3539
|
+
await this.merchantCompletion.reportEvidence({
|
|
2579
3540
|
paymentId: evidenceContext.paymentId,
|
|
2580
3541
|
rail: "x402",
|
|
2581
3542
|
txHash: fundingTxHash,
|
|
@@ -2587,7 +3548,7 @@ var HavenClient = class {
|
|
|
2587
3548
|
protocolReceiptHeader
|
|
2588
3549
|
});
|
|
2589
3550
|
}
|
|
2590
|
-
await this.reportMerchantReceipt(evidenceContext.paymentId, surfaced);
|
|
3551
|
+
await this.merchantCompletion.reportMerchantReceipt(evidenceContext.paymentId, surfaced);
|
|
2591
3552
|
}
|
|
2592
3553
|
return {
|
|
2593
3554
|
status: surfaced.status,
|
|
@@ -2617,271 +3578,11 @@ var HavenClient = class {
|
|
|
2617
3578
|
arguments: raw.arguments ?? {},
|
|
2618
3579
|
...raw.mcp_transport ? {
|
|
2619
3580
|
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
|
-
}
|
|
3581
|
+
handshakeRequired: raw.mcp_transport.handshake_required,
|
|
3582
|
+
source: raw.mcp_transport.source
|
|
3583
|
+
}
|
|
3584
|
+
} : {}
|
|
3585
|
+
};
|
|
2885
3586
|
}
|
|
2886
3587
|
/**
|
|
2887
3588
|
* Wait for a funding tx to be mined with ≥1 confirmation before the
|
|
@@ -2892,264 +3593,9 @@ var HavenClient = class {
|
|
|
2892
3593
|
* backend has already confirmed on-chain submission and callers accept the
|
|
2893
3594
|
* small propagation window as a trade-off for not configuring an RPC URL.
|
|
2894
3595
|
*/
|
|
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
3596
|
throwIfNonSignableAuthorizationState(label, raw) {
|
|
2949
3597
|
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
|
-
});
|
|
3598
|
+
throwPaymentStateError(label, raw);
|
|
3153
3599
|
}
|
|
3154
3600
|
// ── Tool Execution (for agent frameworks) ────────────────────────
|
|
3155
3601
|
/**
|
|
@@ -3181,19 +3627,19 @@ var HavenClient = class {
|
|
|
3181
3627
|
error: result.errorMessage
|
|
3182
3628
|
};
|
|
3183
3629
|
} catch (err) {
|
|
3184
|
-
return
|
|
3630
|
+
return toolError(err);
|
|
3185
3631
|
}
|
|
3186
3632
|
}
|
|
3187
3633
|
if (toolName === "authorize_x402_payment") {
|
|
3188
3634
|
const { url, payTo, amount, asset, network, description, idempotencyKey } = input;
|
|
3189
3635
|
try {
|
|
3190
3636
|
const receipt = await this.authorizeX402(
|
|
3191
|
-
|
|
3637
|
+
toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),
|
|
3192
3638
|
{ idempotencyKey }
|
|
3193
3639
|
);
|
|
3194
|
-
return
|
|
3640
|
+
return x402ToolReceipt(receipt);
|
|
3195
3641
|
} catch (err) {
|
|
3196
|
-
return
|
|
3642
|
+
return toolError(err);
|
|
3197
3643
|
}
|
|
3198
3644
|
}
|
|
3199
3645
|
if (toolName === "resume_x402_payment") {
|
|
@@ -3201,12 +3647,12 @@ var HavenClient = class {
|
|
|
3201
3647
|
try {
|
|
3202
3648
|
const receipt = await this.resumeAuthorizedX402({
|
|
3203
3649
|
paymentId: payment_id,
|
|
3204
|
-
paymentRequired:
|
|
3650
|
+
paymentRequired: toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),
|
|
3205
3651
|
idempotencyKey
|
|
3206
3652
|
});
|
|
3207
|
-
return
|
|
3653
|
+
return x402ToolReceipt(receipt);
|
|
3208
3654
|
} catch (err) {
|
|
3209
|
-
return
|
|
3655
|
+
return toolError(err);
|
|
3210
3656
|
}
|
|
3211
3657
|
}
|
|
3212
3658
|
if (toolName === "get_payment_status") {
|
|
@@ -3241,302 +3687,17 @@ var HavenClient = class {
|
|
|
3241
3687
|
}
|
|
3242
3688
|
throw new Error(`Unknown tool: ${toolName}`);
|
|
3243
3689
|
}
|
|
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
3690
|
// ── HTTP Helpers ─────────────────────────────────────────────────
|
|
3339
3691
|
async post(path, body) {
|
|
3340
|
-
return this.
|
|
3692
|
+
return this.havenApi.post(path, body);
|
|
3341
3693
|
}
|
|
3342
3694
|
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;
|
|
3695
|
+
return this.havenApi.get(path);
|
|
3503
3696
|
}
|
|
3504
3697
|
};
|
|
3505
3698
|
function sleep(ms) {
|
|
3506
3699
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
3507
3700
|
}
|
|
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
3701
|
|
|
3541
3702
|
// src/tool-descriptions.ts
|
|
3542
3703
|
function composeDescription(d) {
|