-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathsettlement-header.js
More file actions
76 lines (65 loc) · 1.71 KB
/
Copy pathsettlement-header.js
File metadata and controls
76 lines (65 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { decodePaymentResponseHeader } from '@x402/fetch'
const SETTLEMENT_HEADER_CANDIDATES = [
'PAYMENT-RESPONSE',
'X-PAYMENT-RESPONSE',
'payment-response',
'x-payment-response',
'X402-PAYMENT-RESPONSE',
'x402-payment-response',
]
function summarizeError(err) {
return (err?.message || 'unknown error').substring(0, 180)
}
function safeJsonParse(value) {
try {
return JSON.parse(value)
} catch {
return null
}
}
function safeBase64JsonParse(value) {
try {
const decoded = Buffer.from(value, 'base64').toString('utf8')
return safeJsonParse(decoded)
} catch {
return null
}
}
export function parseSettlementHeader(
response,
{ decoder = decodePaymentResponseHeader, warn = console.warn } = {}
) {
if (!response?.headers?.get) return null
const candidates = SETTLEMENT_HEADER_CANDIDATES.map((name) => response.headers.get(name)).filter(
Boolean
)
if (candidates.length === 0) return null
let lastError = null
for (const encoded of candidates) {
const jsonDirect = safeJsonParse(encoded)
if (jsonDirect) return jsonDirect
try {
const decoded = decoder(encoded)
if (decoded) return decoded
} catch (err) {
lastError = err
const fallbackJson = safeBase64JsonParse(encoded)
if (fallbackJson) return fallbackJson
}
}
warn(
` unable to decode payment response header, using unverified settlement mode: ${summarizeError(lastError)}`
)
return { unverified: true, _unverified: true }
}
export function extractTxHash(settle) {
if (!settle || typeof settle !== 'object') return null
return (
settle.transaction ||
settle.txHash ||
settle.transactionHash ||
settle.tx_id ||
settle.txId ||
null
)
}