-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcurrent-fees.php
More file actions
265 lines (217 loc) · 7.73 KB
/
Copy pathcurrent-fees.php
File metadata and controls
265 lines (217 loc) · 7.73 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<?php
/**
* BTCBench PHP Current Fees Example
* https://www.btcbench.com/
*
* Fetches current Bitcoin fee estimates from the public BTCBench API
* and displays them with approximate USD transaction cost.
*
* Source : https://www.btcbench.com
* API : https://www.btcbench.com/api-docs.html
* GitHub : https://github.com/btcbench-com/btcbench-api-examples
* Please keep this credit if you use or share this code.
*/
declare(strict_types=1);
// ─────────────────────────────────────────────
// Config
// ─────────────────────────────────────────────
const API_URL = 'https://www.btcbench.com/api/v1/fees.json';
const DEFAULT_TX_VBYTES = 140;
// ─────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────
/**
* Convert a sat/vB fee rate to an approximate USD cost
* based on a default transaction size.
*/
function fee_to_usd(mixed $fee_rate_sat_per_vb, mixed $btc_usd_price): string
{
$fee = filter_var($fee_rate_sat_per_vb, FILTER_VALIDATE_FLOAT);
$price = filter_var($btc_usd_price, FILTER_VALIDATE_FLOAT);
if ($fee === false || $price === false) {
return '~$—';
}
$sats = $fee * DEFAULT_TX_VBYTES;
$usd = ($sats / 100_000_000) * $price;
return '~$' . number_format($usd, 2);
}
/**
* Extract and parse the timestamp from the API response.
* Tries multiple known field names.
*/
function parse_date(array $data): ?DateTimeImmutable
{
$raw = $data['datetime']
?? $data['btc_price_fetched_at']
?? $data['updated_at']
?? $data['timestamp']
?? null;
if ($raw === null) {
return null;
}
// Unix timestamp (integer or float)
if (is_numeric($raw)) {
$dt = DateTimeImmutable::createFromFormat(
'U',
(string)(int)$raw
);
return $dt !== false ? $dt->setTimezone(new DateTimeZone('UTC')) : null;
}
// String timestamp — normalise to ISO 8601
$raw_str = trim((string)$raw);
if (!str_contains($raw_str, 'T')) {
$raw_str = str_replace(' ', 'T', $raw_str);
if (!str_ends_with($raw_str, 'Z')) {
$raw_str .= 'Z';
}
}
try {
return new DateTimeImmutable($raw_str, new DateTimeZone('UTC'));
} catch (Exception) {
return null;
}
}
/**
* Format a DateTimeImmutable object as a readable UTC string.
*/
function format_utc_date(?DateTimeImmutable $date): string
{
if ($date === null) {
return 'Latest BTCBench snapshot';
}
return $date->format('d M Y H:i') . ' UTC';
}
/**
* Return a human-readable 'Updated X min ago' string.
*/
function minutes_ago(?DateTimeImmutable $date): string
{
if ($date === null) {
return 'Updated recently';
}
$diff_seconds = (new DateTimeImmutable('now', new DateTimeZone('UTC')))
->getTimestamp() - $date->getTimestamp();
$diff_min = max(0, (int)round($diff_seconds / 60));
if ($diff_min < 1) return 'Updated just now';
if ($diff_min === 1) return 'Updated 1 min ago';
if ($diff_min < 60) return "Updated {$diff_min} min ago";
$diff_hours = (int)round($diff_min / 60);
if ($diff_hours === 1) return 'Updated 1 hour ago';
return "Updated {$diff_hours} hours ago";
}
// ─────────────────────────────────────────────
// Fetch
// ─────────────────────────────────────────────
/**
* Fetch fee data from the BTCBench public API.
* Returns parsed array or throws on failure.
*
* @throws RuntimeException
*/
function fetch_fees(): array
{
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => "User-Agent: BTCBench-PHP-Example/1.0\r\n",
'timeout' => 10,
'ignore_errors' => true,
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
],
]);
$raw = @file_get_contents(API_URL, false, $context);
if ($raw === false) {
throw new RuntimeException('Request failed — could not reach BTCBench API.');
}
// Check HTTP status from response headers
$status_line = $http_response_header[0] ?? '';
preg_match('/HTTP\/\S+\s+(\d+)/', $status_line, $matches);
$status_code = (int)($matches[1] ?? 0);
if ($status_code !== 200) {
throw new RuntimeException("HTTP {$status_code}");
}
$data = json_decode($raw, associative: true);
if (!is_array($data)) {
throw new RuntimeException('Failed to decode BTCBench API JSON response.');
}
return $data;
}
// ─────────────────────────────────────────────
// Render
// ─────────────────────────────────────────────
/**
* Validate and display the fee data in the terminal.
*
* @throws InvalidArgumentException
*/
function render(array $data): void
{
if (empty($data['fees'])) {
throw new InvalidArgumentException('Invalid BTCBench API response.');
}
$fees = $data['fees'];
$fastest = $fees['fastest'] ?? 'N/A';
$normal = $fees['halfHour'] ?? 'N/A';
$economy = $fees['economy'] ?? 'N/A';
$btc_price_usd = $data['btc_price_usd'] ?? null;
$date = parse_date($data);
$div = str_repeat('=', 44);
$line = str_repeat('-', 44);
echo PHP_EOL;
echo $div . PHP_EOL;
echo ' BTCBench — Current Bitcoin Fee Estimates' . PHP_EOL;
echo $div . PHP_EOL;
echo sprintf(
" %-12s %8s %12s\n",
'Tier', 'sat/vB', 'USD ~140 vB'
);
echo $line . PHP_EOL;
echo sprintf(
" %-12s %8s %12s\n",
'Fastest',
(string)$fastest,
fee_to_usd($fastest, $btc_price_usd)
);
echo sprintf(
" %-12s %8s %12s\n",
'Normal',
(string)$normal,
fee_to_usd($normal, $btc_price_usd)
);
echo sprintf(
" %-12s %8s %12s\n",
'Economy',
(string)$economy,
fee_to_usd($economy, $btc_price_usd)
);
echo $line . PHP_EOL;
echo ' ' . minutes_ago($date) . PHP_EOL;
echo ' ' . format_utc_date($date) . PHP_EOL;
echo $div . PHP_EOL;
echo ' Powered by BTCBench · https://www.btcbench.com' . PHP_EOL;
echo ' USD estimate assumes 140 vbyte transaction.' . PHP_EOL;
echo ' Always verify fees in your own wallet.' . PHP_EOL;
echo $div . PHP_EOL;
echo PHP_EOL;
}
// ─────────────────────────────────────────────
// Main
// ─────────────────────────────────────────────
function main(): void
{
echo PHP_EOL . ' Fetching BTCBench fee data…' . PHP_EOL;
try {
$data = fetch_fees();
render($data);
} catch (Throwable $error) {
echo PHP_EOL;
echo ' [ERROR] Could not load BTCBench fee data: ' . $error->getMessage() . PHP_EOL;
echo ' Please check the BTCBench API or status page.' . PHP_EOL;
echo ' https://www.btcbench.com' . PHP_EOL;
echo PHP_EOL;
}
}
main();