@k256/sdk 0.2.1 → 0.3.1

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 CHANGED
@@ -979,6 +979,506 @@ var K256WebSocketClient = class {
979
979
  }
980
980
  };
981
981
 
982
+ // src/leader-ws/decoder.ts
983
+ var LeaderMessageTag = {
984
+ Subscribe: 1,
985
+ Subscribed: 2,
986
+ LeaderSchedule: 16,
987
+ GossipSnapshot: 17,
988
+ GossipDiff: 18,
989
+ SlotUpdate: 19,
990
+ RoutingHealth: 20,
991
+ SkipEvent: 21,
992
+ IpChange: 22,
993
+ Heartbeat: 253,
994
+ Ping: 254,
995
+ Error: 255
996
+ };
997
+ function readU64(view, o) {
998
+ const val = Number(view.getBigUint64(o.v, true));
999
+ o.v += 8;
1000
+ return val;
1001
+ }
1002
+ function readU32(view, o) {
1003
+ const val = view.getUint32(o.v, true);
1004
+ o.v += 4;
1005
+ return val;
1006
+ }
1007
+ function readU16(view, o) {
1008
+ const val = view.getUint16(o.v, true);
1009
+ o.v += 2;
1010
+ return val;
1011
+ }
1012
+ function readU8(view, o) {
1013
+ const val = view.getUint8(o.v);
1014
+ o.v += 1;
1015
+ return val;
1016
+ }
1017
+ function readBool(view, o) {
1018
+ return readU8(view, o) !== 0;
1019
+ }
1020
+ function readPubkey(data, o) {
1021
+ const bytes = new Uint8Array(data, o.v, 32);
1022
+ o.v += 32;
1023
+ return base58Encode(bytes);
1024
+ }
1025
+ function readVecU8AsString(view, data, o) {
1026
+ const len = readU64(view, o);
1027
+ const bytes = new Uint8Array(data, o.v, len);
1028
+ o.v += len;
1029
+ return new TextDecoder().decode(bytes);
1030
+ }
1031
+ function readOptSocketAddr(view, o) {
1032
+ const tag = readU8(view, o);
1033
+ if (tag === 0) return null;
1034
+ const ipBytes = new Uint8Array(view.buffer, view.byteOffset + o.v, 16);
1035
+ o.v += 16;
1036
+ const port = readU16(view, o);
1037
+ const isIpv4 = readBool(view, o);
1038
+ if (isIpv4) {
1039
+ return `${ipBytes[12]}.${ipBytes[13]}.${ipBytes[14]}.${ipBytes[15]}:${port}`;
1040
+ }
1041
+ return `[ipv6]:${port}`;
1042
+ }
1043
+ function readPubkeyVec(view, data, o) {
1044
+ const count = readU64(view, o);
1045
+ const keys = [];
1046
+ for (let i = 0; i < count; i++) {
1047
+ keys.push(readPubkey(data, o));
1048
+ }
1049
+ return keys;
1050
+ }
1051
+ function readGossipPeer(view, data, o) {
1052
+ return {
1053
+ identity: readPubkey(data, o),
1054
+ tpuQuic: readOptSocketAddr(view, o),
1055
+ tpuUdp: readOptSocketAddr(view, o),
1056
+ tpuForwardsQuic: readOptSocketAddr(view, o),
1057
+ tpuForwardsUdp: readOptSocketAddr(view, o),
1058
+ tpuVote: readOptSocketAddr(view, o),
1059
+ tpuVoteQuic: readOptSocketAddr(view, o),
1060
+ gossipAddr: readOptSocketAddr(view, o),
1061
+ shredVersion: readU16(view, o),
1062
+ version: readVecU8AsString(view, data, o),
1063
+ stake: readU64(view, o),
1064
+ commission: readU8(view, o),
1065
+ isDelinquent: readBool(view, o),
1066
+ voteAccount: readPubkey(data, o),
1067
+ lastVote: readU64(view, o),
1068
+ rootSlot: readU64(view, o),
1069
+ wallclock: readU64(view, o),
1070
+ // Geo/ASN enrichment from IPinfo Lite MMDB (server-side)
1071
+ countryCode: readVecU8AsString(view, data, o),
1072
+ continentCode: readVecU8AsString(view, data, o),
1073
+ asn: readVecU8AsString(view, data, o),
1074
+ asName: readVecU8AsString(view, data, o),
1075
+ asDomain: readVecU8AsString(view, data, o)
1076
+ };
1077
+ }
1078
+ function readGossipPeerVec(view, data, o) {
1079
+ const count = readU64(view, o);
1080
+ const peers = [];
1081
+ for (let i = 0; i < count; i++) {
1082
+ peers.push(readGossipPeer(view, data, o));
1083
+ }
1084
+ return peers;
1085
+ }
1086
+ function decodeLeaderMessage(data) {
1087
+ const view = new DataView(data);
1088
+ if (data.byteLength < 1) return null;
1089
+ const msgType = view.getUint8(0);
1090
+ const payload = data.slice(1);
1091
+ const pv = new DataView(payload);
1092
+ switch (msgType) {
1093
+ case LeaderMessageTag.Subscribed: {
1094
+ const text = new TextDecoder().decode(payload);
1095
+ try {
1096
+ return { type: "subscribed", data: JSON.parse(text) };
1097
+ } catch {
1098
+ return null;
1099
+ }
1100
+ }
1101
+ case LeaderMessageTag.Error: {
1102
+ return { type: "error", data: { message: new TextDecoder().decode(payload) } };
1103
+ }
1104
+ case LeaderMessageTag.SlotUpdate: {
1105
+ if (payload.byteLength < 48) return null;
1106
+ const o = { v: 0 };
1107
+ return {
1108
+ type: "slot_update",
1109
+ kind: "snapshot",
1110
+ data: {
1111
+ slot: readU64(pv, o),
1112
+ leader: readPubkey(payload, o),
1113
+ blockHeight: readU64(pv, o)
1114
+ }
1115
+ };
1116
+ }
1117
+ case LeaderMessageTag.Heartbeat: {
1118
+ if (payload.byteLength < 24) return null;
1119
+ const o = { v: 0 };
1120
+ return {
1121
+ type: "heartbeat",
1122
+ kind: "snapshot",
1123
+ data: {
1124
+ timestampMs: readU64(pv, o),
1125
+ currentSlot: readU64(pv, o),
1126
+ connectedClients: readU32(pv, o),
1127
+ gossipPeers: readU32(pv, o)
1128
+ }
1129
+ };
1130
+ }
1131
+ case LeaderMessageTag.SkipEvent: {
1132
+ if (payload.byteLength < 48) return null;
1133
+ const o = { v: 0 };
1134
+ return {
1135
+ type: "skip_event",
1136
+ kind: "event",
1137
+ key: "leader",
1138
+ data: {
1139
+ slot: readU64(pv, o),
1140
+ leader: readPubkey(payload, o),
1141
+ assigned: readU32(pv, o),
1142
+ produced: readU32(pv, o)
1143
+ }
1144
+ };
1145
+ }
1146
+ case LeaderMessageTag.RoutingHealth: {
1147
+ if (payload.byteLength < 8) return null;
1148
+ try {
1149
+ const o = { v: 0 };
1150
+ const leadersTotal = readU32(pv, o);
1151
+ const leadersInGossip = readU32(pv, o);
1152
+ const leadersMissingGossip = readPubkeyVec(pv, payload, o);
1153
+ const leadersWithoutTpuQuic = readPubkeyVec(pv, payload, o);
1154
+ const leadersDelinquent = readPubkeyVec(pv, payload, o);
1155
+ return {
1156
+ type: "routing_health",
1157
+ kind: "snapshot",
1158
+ data: {
1159
+ leadersTotal,
1160
+ leadersInGossip,
1161
+ leadersMissingGossip,
1162
+ leadersWithoutTpuQuic,
1163
+ leadersDelinquent,
1164
+ coverage: `${leadersTotal > 0 ? (leadersInGossip / leadersTotal * 100).toFixed(1) : 0}%`
1165
+ }
1166
+ };
1167
+ } catch {
1168
+ return null;
1169
+ }
1170
+ }
1171
+ case LeaderMessageTag.IpChange: {
1172
+ if (payload.byteLength < 32) return null;
1173
+ try {
1174
+ const o = { v: 0 };
1175
+ const identity = readPubkey(payload, o);
1176
+ const oldIp = readVecU8AsString(pv, payload, o);
1177
+ const newIp = readVecU8AsString(pv, payload, o);
1178
+ const timestampMs = readU64(pv, o);
1179
+ return {
1180
+ type: "ip_change",
1181
+ kind: "event",
1182
+ key: "identity",
1183
+ data: { identity, oldIp, newIp, timestampMs }
1184
+ };
1185
+ } catch {
1186
+ return null;
1187
+ }
1188
+ }
1189
+ case LeaderMessageTag.GossipSnapshot: {
1190
+ if (payload.byteLength < 8) return null;
1191
+ try {
1192
+ const o = { v: 0 };
1193
+ const timestampMs = readU64(pv, o);
1194
+ const peers = readGossipPeerVec(pv, payload, o);
1195
+ return {
1196
+ type: "gossip_snapshot",
1197
+ kind: "snapshot",
1198
+ key: "identity",
1199
+ data: { timestampMs, count: peers.length, peers }
1200
+ };
1201
+ } catch {
1202
+ return null;
1203
+ }
1204
+ }
1205
+ case LeaderMessageTag.GossipDiff: {
1206
+ if (payload.byteLength < 8) return null;
1207
+ try {
1208
+ const o = { v: 0 };
1209
+ const timestampMs = readU64(pv, o);
1210
+ const added = readGossipPeerVec(pv, payload, o);
1211
+ const removed = readPubkeyVec(pv, payload, o);
1212
+ const updated = readGossipPeerVec(pv, payload, o);
1213
+ return {
1214
+ type: "gossip_diff",
1215
+ kind: "diff",
1216
+ key: "identity",
1217
+ data: { timestampMs, added, removed, updated }
1218
+ };
1219
+ } catch {
1220
+ return null;
1221
+ }
1222
+ }
1223
+ case LeaderMessageTag.LeaderSchedule: {
1224
+ if (payload.byteLength < 16) return null;
1225
+ try {
1226
+ const o = { v: 0 };
1227
+ const epoch = readU64(pv, o);
1228
+ const slotsInEpoch = readU64(pv, o);
1229
+ const validatorCount = readU64(pv, o);
1230
+ const schedule = [];
1231
+ for (let i = 0; i < validatorCount; i++) {
1232
+ const identity = readPubkey(payload, o);
1233
+ const slotCount = readU64(pv, o);
1234
+ const slotIndices = [];
1235
+ for (let j = 0; j < slotCount; j++) {
1236
+ slotIndices.push(readU32(pv, o));
1237
+ }
1238
+ schedule.push({ identity, slots: slotIndices.length, slotIndices });
1239
+ }
1240
+ return {
1241
+ type: "leader_schedule",
1242
+ kind: "snapshot",
1243
+ data: { epoch, slotsInEpoch, validators: schedule.length, schedule }
1244
+ };
1245
+ } catch {
1246
+ return null;
1247
+ }
1248
+ }
1249
+ default:
1250
+ return null;
1251
+ }
1252
+ }
1253
+
1254
+ // src/leader-ws/types.ts
1255
+ var LeaderChannel = {
1256
+ /** Full epoch leader schedule (on connect + epoch change) */
1257
+ LeaderSchedule: "leader_schedule",
1258
+ /** Gossip peers (snapshot on connect, then diffs) */
1259
+ Gossip: "gossip",
1260
+ /** Real-time slot updates with current leader */
1261
+ Slots: "slots",
1262
+ /** Skip events, IP changes, routing health */
1263
+ Alerts: "alerts"
1264
+ };
1265
+ var ALL_LEADER_CHANNELS = [
1266
+ LeaderChannel.LeaderSchedule,
1267
+ LeaderChannel.Gossip,
1268
+ LeaderChannel.Slots,
1269
+ LeaderChannel.Alerts
1270
+ ];
1271
+
1272
+ // src/leader-ws/client.ts
1273
+ var LeaderWebSocketError = class extends Error {
1274
+ constructor(code, message, closeCode, closeReason) {
1275
+ super(message);
1276
+ this.code = code;
1277
+ this.closeCode = closeCode;
1278
+ this.closeReason = closeReason;
1279
+ this.name = "LeaderWebSocketError";
1280
+ }
1281
+ get isRecoverable() {
1282
+ return this.code !== "AUTH_FAILED";
1283
+ }
1284
+ };
1285
+ var LeaderWebSocketClient = class {
1286
+ ws = null;
1287
+ config;
1288
+ _state = "disconnected";
1289
+ reconnectAttempts = 0;
1290
+ reconnectTimer = null;
1291
+ isIntentionallyClosed = false;
1292
+ /** Current connection state */
1293
+ get state() {
1294
+ return this._state;
1295
+ }
1296
+ /** Whether currently connected */
1297
+ get isConnected() {
1298
+ return this._state === "connected" && this.ws?.readyState === WebSocket.OPEN;
1299
+ }
1300
+ constructor(config) {
1301
+ this.config = {
1302
+ url: "wss://gateway.k256.xyz/v1/leader-ws",
1303
+ mode: "binary",
1304
+ channels: ALL_LEADER_CHANNELS,
1305
+ autoReconnect: true,
1306
+ reconnectDelayMs: 1e3,
1307
+ maxReconnectDelayMs: 3e4,
1308
+ maxReconnectAttempts: Infinity,
1309
+ ...config
1310
+ };
1311
+ }
1312
+ /**
1313
+ * Connect to the leader-schedule WebSocket
1314
+ */
1315
+ async connect() {
1316
+ if (this._state === "connected" || this._state === "connecting") return;
1317
+ this.isIntentionallyClosed = false;
1318
+ this.setState("connecting");
1319
+ return new Promise((resolve, reject) => {
1320
+ try {
1321
+ const url = `${this.config.url}?apiKey=${encodeURIComponent(this.config.apiKey)}`;
1322
+ this.ws = new WebSocket(url);
1323
+ if (this.config.mode === "binary") {
1324
+ this.ws.binaryType = "arraybuffer";
1325
+ }
1326
+ this.ws.onopen = () => {
1327
+ this.setState("connected");
1328
+ this.reconnectAttempts = 0;
1329
+ if (this.config.mode === "binary") {
1330
+ const payload = JSON.stringify({ channels: this.config.channels });
1331
+ const bytes = new TextEncoder().encode(payload);
1332
+ const msg = new Uint8Array(1 + bytes.length);
1333
+ msg[0] = 1;
1334
+ msg.set(bytes, 1);
1335
+ this.ws.send(msg.buffer);
1336
+ } else {
1337
+ this.ws.send(JSON.stringify({
1338
+ type: "subscribe",
1339
+ channels: this.config.channels,
1340
+ format: "json"
1341
+ }));
1342
+ }
1343
+ this.config.onConnect?.();
1344
+ resolve();
1345
+ };
1346
+ this.ws.onmessage = (event) => {
1347
+ if (this.config.mode === "binary" && event.data instanceof ArrayBuffer) {
1348
+ const decoded = decodeLeaderMessage(event.data);
1349
+ if (decoded) {
1350
+ this.dispatchMessage(decoded);
1351
+ }
1352
+ } else if (typeof event.data === "string") {
1353
+ this.handleJsonMessage(event.data);
1354
+ }
1355
+ };
1356
+ this.ws.onclose = (event) => {
1357
+ const wasConnected = this._state === "connected";
1358
+ this.ws = null;
1359
+ if (this.isIntentionallyClosed) {
1360
+ this.setState("closed");
1361
+ this.config.onDisconnect?.(event.code, event.reason, event.wasClean);
1362
+ return;
1363
+ }
1364
+ this.config.onDisconnect?.(event.code, event.reason, event.wasClean);
1365
+ if (event.code === 1008 || event.code === 4001 || event.code === 4003) {
1366
+ this.setState("closed");
1367
+ this.config.onError?.(new LeaderWebSocketError(
1368
+ "AUTH_FAILED",
1369
+ `Authentication failed: ${event.reason}`,
1370
+ event.code,
1371
+ event.reason
1372
+ ));
1373
+ if (!wasConnected) reject(new LeaderWebSocketError("AUTH_FAILED", event.reason, event.code));
1374
+ return;
1375
+ }
1376
+ if (this.config.autoReconnect && this.reconnectAttempts < this.config.maxReconnectAttempts) {
1377
+ this.scheduleReconnect();
1378
+ } else {
1379
+ this.setState("disconnected");
1380
+ }
1381
+ if (!wasConnected) reject(new LeaderWebSocketError("CONNECTION_FAILED", "WebSocket closed before connect"));
1382
+ };
1383
+ this.ws.onerror = () => {
1384
+ this.config.onError?.(new LeaderWebSocketError("CONNECTION_FAILED", "WebSocket connection error"));
1385
+ };
1386
+ } catch (err) {
1387
+ this.setState("disconnected");
1388
+ reject(err);
1389
+ }
1390
+ });
1391
+ }
1392
+ /**
1393
+ * Disconnect from the WebSocket
1394
+ */
1395
+ disconnect() {
1396
+ this.isIntentionallyClosed = true;
1397
+ this.clearTimers();
1398
+ if (this.ws) {
1399
+ if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
1400
+ this.ws.close(1e3, "Client disconnect");
1401
+ }
1402
+ this.ws = null;
1403
+ }
1404
+ this.setState("closed");
1405
+ }
1406
+ // ── Private ──
1407
+ /** Handle JSON text frame (from gateway JSON mode) */
1408
+ handleJsonMessage(raw) {
1409
+ try {
1410
+ const msg = JSON.parse(raw);
1411
+ this.dispatchMessage(msg);
1412
+ } catch {
1413
+ this.config.onError?.(new LeaderWebSocketError("INVALID_MESSAGE", "Failed to parse message"));
1414
+ }
1415
+ }
1416
+ /** Dispatch a decoded message to typed callbacks */
1417
+ dispatchMessage(msg) {
1418
+ switch (msg.type) {
1419
+ case "subscribed":
1420
+ this.config.onSubscribed?.(msg);
1421
+ break;
1422
+ case "leader_schedule":
1423
+ this.config.onLeaderSchedule?.(msg);
1424
+ break;
1425
+ case "gossip_snapshot":
1426
+ this.config.onGossipSnapshot?.(msg);
1427
+ break;
1428
+ case "gossip_diff":
1429
+ this.config.onGossipDiff?.(msg);
1430
+ break;
1431
+ case "slot_update":
1432
+ this.config.onSlotUpdate?.(msg);
1433
+ break;
1434
+ case "routing_health":
1435
+ this.config.onRoutingHealth?.(msg);
1436
+ break;
1437
+ case "skip_event":
1438
+ this.config.onSkipEvent?.(msg);
1439
+ break;
1440
+ case "ip_change":
1441
+ this.config.onIpChange?.(msg);
1442
+ break;
1443
+ case "heartbeat":
1444
+ this.config.onHeartbeat?.(msg);
1445
+ break;
1446
+ case "error":
1447
+ this.config.onError?.(new LeaderWebSocketError(
1448
+ "SERVER_ERROR",
1449
+ msg.data.message
1450
+ ));
1451
+ break;
1452
+ }
1453
+ this.config.onMessage?.(msg);
1454
+ }
1455
+ setState(state) {
1456
+ const prev = this._state;
1457
+ if (prev === state) return;
1458
+ this._state = state;
1459
+ this.config.onStateChange?.(state, prev);
1460
+ }
1461
+ scheduleReconnect() {
1462
+ this.setState("reconnecting");
1463
+ this.reconnectAttempts++;
1464
+ const delay = Math.min(
1465
+ this.config.reconnectDelayMs * Math.pow(2, this.reconnectAttempts - 1),
1466
+ this.config.maxReconnectDelayMs
1467
+ );
1468
+ this.config.onReconnecting?.(this.reconnectAttempts, delay);
1469
+ this.reconnectTimer = setTimeout(() => {
1470
+ this.connect().catch(() => {
1471
+ });
1472
+ }, delay);
1473
+ }
1474
+ clearTimers() {
1475
+ if (this.reconnectTimer) {
1476
+ clearTimeout(this.reconnectTimer);
1477
+ this.reconnectTimer = null;
1478
+ }
1479
+ }
1480
+ };
1481
+
982
1482
  // src/types/index.ts
983
1483
  var NetworkState = /* @__PURE__ */ ((NetworkState2) => {
984
1484
  NetworkState2[NetworkState2["Low"] = 0] = "Low";
@@ -988,13 +1488,19 @@ var NetworkState = /* @__PURE__ */ ((NetworkState2) => {
988
1488
  return NetworkState2;
989
1489
  })(NetworkState || {});
990
1490
 
1491
+ exports.ALL_LEADER_CHANNELS = ALL_LEADER_CHANNELS;
991
1492
  exports.CloseCode = CloseCode;
992
1493
  exports.K256WebSocketClient = K256WebSocketClient;
993
1494
  exports.K256WebSocketError = K256WebSocketError;
1495
+ exports.LeaderChannel = LeaderChannel;
1496
+ exports.LeaderMessageTag = LeaderMessageTag;
1497
+ exports.LeaderWebSocketClient = LeaderWebSocketClient;
1498
+ exports.LeaderWebSocketError = LeaderWebSocketError;
994
1499
  exports.MessageType = MessageType;
995
1500
  exports.NetworkState = NetworkState;
996
1501
  exports.base58Decode = base58Decode;
997
1502
  exports.base58Encode = base58Encode;
1503
+ exports.decodeLeaderMessage = decodeLeaderMessage;
998
1504
  exports.decodeMessage = decodeMessage;
999
1505
  exports.decodePoolUpdateBatch = decodePoolUpdateBatch;
1000
1506
  exports.isValidPubkey = isValidPubkey;