k256-sdk 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 441531a7c9cb1a3c7e357c47f270cf941b935b9cad3fbb7708a301a2c2886810
4
+ data.tar.gz: '09304c0416afc3b6a68602fa072bd6bf101bd8acda4c6ffacf51725c86ee7825'
5
+ SHA512:
6
+ metadata.gz: 7869faf88938bb6d508b27889460aa98b72f830bc63673aac9c7f8e9d635357573687cbd4dd8e46748e0a9e64e47b9ae1baca97c2c1e0cbf1e91e62c7bab176f
7
+ data.tar.gz: 001dc522decff3492664f432e1daa617fe56131ab899cbbd5f34d96a206e4dd567b67cffa81e832f6286bd68ded99ad22fe1bf789c0d789927b0c639a845c699
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-2026 K256
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # K256 Ruby SDK
2
+
3
+ Official Ruby SDK for [K256](https://k256.xyz) - the gateway to decentralized finance.
4
+
5
+ Connect any application to Solana's liquidity ecosystem. One API. All venues. Full observability.
6
+
7
+ [![Gem Version](https://badge.fury.io/rb/k256-sdk.svg)](https://badge.fury.io/rb/k256-sdk)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
+
10
+ ## Installation
11
+
12
+ Add to your Gemfile:
13
+
14
+ ```ruby
15
+ gem 'k256-sdk'
16
+ ```
17
+
18
+ Or install directly:
19
+
20
+ ```bash
21
+ gem install k256-sdk
22
+ ```
23
+
24
+ ## Quick Start
25
+
26
+ ```ruby
27
+ require 'k256'
28
+
29
+ client = K256::Client.new(api_key: ENV['K256_API_KEY'])
30
+
31
+ client.on_pool_update do |update|
32
+ puts "Pool #{update.pool_address}: slot=#{update.slot}"
33
+ end
34
+
35
+ client.on_priority_fees do |fees|
36
+ puts "Recommended fee: #{fees.recommended} microlamports"
37
+ end
38
+
39
+ client.on_blockhash do |bh|
40
+ puts "Blockhash: #{bh.blockhash} (slot #{bh.slot})"
41
+ end
42
+
43
+ client.on_error do |err|
44
+ puts "Error: #{err}"
45
+ end
46
+
47
+ client.connect
48
+ client.subscribe(channels: ['pools', 'priority_fees', 'blockhash'])
49
+
50
+ # Keep running
51
+ sleep
52
+ ```
53
+
54
+ ## Module Structure
55
+
56
+ ```
57
+ K256
58
+ ├── Client # WebSocket client
59
+ ├── Decoder # Binary message decoder
60
+ ├── Base58 # Base58 encoding utilities
61
+ ├── MessageType # Message type constants
62
+ ├── PoolUpdate # Pool state update struct
63
+ ├── PriorityFees # Priority fees struct
64
+ ├── Blockhash # Blockhash struct
65
+ └── Quote # Quote struct
66
+ ```
67
+
68
+ ## Architecture
69
+
70
+ This SDK follows the cross-language conventions defined in [ARCHITECTURE.md](../ARCHITECTURE.md).
71
+
72
+ ## License
73
+
74
+ MIT
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ module K256
4
+ # Base58 encoding/decoding utilities for Solana addresses.
5
+ module Base58
6
+ ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
7
+ BASE = ALPHABET.length
8
+ INDEXES = ALPHABET.each_char.with_index.to_h.freeze
9
+
10
+ class << self
11
+ # Encode bytes to base58 string.
12
+ #
13
+ # @param data [String, Array<Integer>] Bytes to encode
14
+ # @return [String] Base58-encoded string
15
+ def encode(data)
16
+ data = data.bytes if data.is_a?(String)
17
+ return "" if data.empty?
18
+
19
+ # Count leading zeros
20
+ leading_zeros = data.take_while(&:zero?).length
21
+
22
+ # Convert to big integer
23
+ num = data.reduce(0) { |acc, byte| (acc << 8) + byte }
24
+
25
+ # Convert to base58
26
+ result = []
27
+ while num.positive?
28
+ num, remainder = num.divmod(BASE)
29
+ result.unshift(ALPHABET[remainder])
30
+ end
31
+
32
+ # Add leading '1's for leading zeros
33
+ ("1" * leading_zeros) + result.join
34
+ end
35
+
36
+ # Decode base58 string to bytes.
37
+ #
38
+ # @param str [String] Base58-encoded string
39
+ # @return [Array<Integer>] Decoded bytes
40
+ # @raise [ArgumentError] if string contains invalid characters
41
+ def decode(str)
42
+ return [] if str.empty?
43
+
44
+ # Count leading '1's
45
+ leading_ones = str.chars.take_while { |c| c == "1" }.length
46
+
47
+ # Convert from base58 to integer
48
+ num = 0
49
+ str.each_char do |c|
50
+ index = INDEXES[c]
51
+ raise ArgumentError, "Invalid Base58 character: #{c}" if index.nil?
52
+
53
+ num = num * BASE + index
54
+ end
55
+
56
+ # Convert to bytes
57
+ result = []
58
+ while num.positive?
59
+ result.unshift(num & 0xFF)
60
+ num >>= 8
61
+ end
62
+
63
+ # Add leading zero bytes
64
+ ([0] * leading_ones) + result
65
+ end
66
+
67
+ # Check if a string is a valid Solana public key.
68
+ #
69
+ # @param address [String] Base58-encoded address
70
+ # @return [Boolean] True if valid
71
+ def valid_pubkey?(address)
72
+ return false if address.nil? || address.length < 32 || address.length > 44
73
+
74
+ begin
75
+ decoded = decode(address)
76
+ decoded.length == 32
77
+ rescue ArgumentError
78
+ false
79
+ end
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,283 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "websocket-client-simple"
4
+ require "json"
5
+
6
+ module K256
7
+ # K256 WebSocket client for real-time Solana liquidity data.
8
+ #
9
+ # @example
10
+ # client = K256::Client.new(api_key: ENV['K256_API_KEY'])
11
+ #
12
+ # client.on_pool_update { |update| puts update.pool_address }
13
+ # client.on_priority_fees { |fees| puts fees.recommended }
14
+ #
15
+ # client.connect
16
+ # client.subscribe(channels: ['pools', 'priority_fees', 'blockhash'])
17
+ class Client
18
+ DEFAULT_ENDPOINT = "wss://gateway.k256.xyz/v1/ws"
19
+
20
+ attr_reader :api_key, :endpoint, :reconnect, :connected
21
+
22
+ # Create a new K256 WebSocket client.
23
+ #
24
+ # @param api_key [String] K256 API key
25
+ # @param endpoint [String] WebSocket endpoint URL
26
+ # @param reconnect [Boolean] Whether to automatically reconnect
27
+ # @param reconnect_delay_initial [Float] Initial reconnect delay in seconds
28
+ # @param reconnect_delay_max [Float] Maximum reconnect delay in seconds
29
+ def initialize(
30
+ api_key:,
31
+ endpoint: DEFAULT_ENDPOINT,
32
+ reconnect: true,
33
+ reconnect_delay_initial: 1.0,
34
+ reconnect_delay_max: 60.0
35
+ )
36
+ @api_key = api_key
37
+ @endpoint = endpoint
38
+ @reconnect = reconnect
39
+ @reconnect_delay_initial = reconnect_delay_initial
40
+ @reconnect_delay_max = reconnect_delay_max
41
+ @reconnect_delay = reconnect_delay_initial
42
+
43
+ @callbacks = {}
44
+ @ws = nil
45
+ @connected = false
46
+ @running = false
47
+ @last_subscription = nil
48
+ end
49
+
50
+ # Register a callback for pool updates.
51
+ #
52
+ # @yield [PoolUpdate] Pool update
53
+ def on_pool_update(&block)
54
+ @callbacks[:pool_update] = block
55
+ end
56
+
57
+ # Register a callback for priority fee updates.
58
+ #
59
+ # @yield [PriorityFees] Priority fees
60
+ def on_priority_fees(&block)
61
+ @callbacks[:priority_fees] = block
62
+ end
63
+
64
+ # Register a callback for blockhash updates.
65
+ #
66
+ # @yield [Blockhash] Blockhash
67
+ def on_blockhash(&block)
68
+ @callbacks[:blockhash] = block
69
+ end
70
+
71
+ # Register a callback for quote updates.
72
+ #
73
+ # @yield [Quote] Quote
74
+ def on_quote(&block)
75
+ @callbacks[:quote] = block
76
+ end
77
+
78
+ # Register a callback for heartbeat messages.
79
+ #
80
+ # @yield [Heartbeat] Heartbeat
81
+ def on_heartbeat(&block)
82
+ @callbacks[:heartbeat] = block
83
+ end
84
+
85
+ # Register a callback for errors.
86
+ #
87
+ # @yield [String] Error message
88
+ def on_error(&block)
89
+ @callbacks[:error] = block
90
+ end
91
+
92
+ # Register a callback for connection established.
93
+ #
94
+ # @yield Called when connected
95
+ def on_connected(&block)
96
+ @callbacks[:connected] = block
97
+ end
98
+
99
+ # Register a callback for disconnection.
100
+ #
101
+ # @yield Called when disconnected
102
+ def on_disconnected(&block)
103
+ @callbacks[:disconnected] = block
104
+ end
105
+
106
+ # Connect to the K256 WebSocket.
107
+ def connect
108
+ @running = true
109
+ do_connect
110
+ end
111
+
112
+ # Disconnect from the WebSocket.
113
+ def disconnect
114
+ @running = false
115
+ @ws&.close
116
+ @ws = nil
117
+ @connected = false
118
+ end
119
+
120
+ # Subscribe to channels.
121
+ #
122
+ # @param channels [Array<String>] List of channels
123
+ # @param protocols [Array<String>, nil] Optional DEX protocols to filter
124
+ # @param pools [Array<String>, nil] Optional pool addresses to filter
125
+ # @param token_pairs [Array<Array<String>>, nil] Optional token pairs to filter
126
+ def subscribe(channels:, protocols: nil, pools: nil, token_pairs: nil)
127
+ @last_subscription = {
128
+ channels: channels,
129
+ protocols: protocols,
130
+ pools: pools,
131
+ token_pairs: token_pairs
132
+ }
133
+
134
+ send_subscribe if @connected
135
+ end
136
+
137
+ # Unsubscribe from all channels.
138
+ def unsubscribe
139
+ @last_subscription = nil
140
+ send_json(type: "unsubscribe") if @connected
141
+ end
142
+
143
+ private
144
+
145
+ def do_connect
146
+ url = "#{@endpoint}?apiKey=#{@api_key}"
147
+
148
+ @ws = WebSocket::Client::Simple.connect(url)
149
+ client = self
150
+
151
+ @ws.on :open do
152
+ client.send(:handle_open)
153
+ end
154
+
155
+ @ws.on :message do |msg|
156
+ client.send(:handle_message, msg)
157
+ end
158
+
159
+ @ws.on :close do |e|
160
+ client.send(:handle_close, e)
161
+ end
162
+
163
+ @ws.on :error do |e|
164
+ client.send(:handle_error, e)
165
+ end
166
+ end
167
+
168
+ def handle_open
169
+ @connected = true
170
+ @reconnect_delay = @reconnect_delay_initial
171
+ @callbacks[:connected]&.call
172
+ send_subscribe if @last_subscription
173
+ end
174
+
175
+ def handle_message(msg)
176
+ if msg.type == :binary
177
+ handle_binary_message(msg.data)
178
+ else
179
+ handle_text_message(msg.data)
180
+ end
181
+ end
182
+
183
+ def handle_binary_message(data)
184
+ return if data.bytesize < 1
185
+
186
+ msg_type = data.getbyte(0)
187
+ payload = data[1..]
188
+
189
+ case msg_type
190
+ when MessageType::POOL_UPDATE
191
+ if @callbacks[:pool_update]
192
+ update = Decoder.decode_pool_update(payload)
193
+ @callbacks[:pool_update].call(update) if update
194
+ end
195
+ when MessageType::POOL_UPDATE_BATCH
196
+ if @callbacks[:pool_update]
197
+ updates = Decoder.decode_pool_update_batch(payload)
198
+ updates.each { |u| @callbacks[:pool_update].call(u) }
199
+ end
200
+ when MessageType::PRIORITY_FEES
201
+ if @callbacks[:priority_fees]
202
+ fees = Decoder.decode_priority_fees(payload)
203
+ @callbacks[:priority_fees].call(fees) if fees
204
+ end
205
+ when MessageType::BLOCKHASH
206
+ if @callbacks[:blockhash]
207
+ bh = Decoder.decode_blockhash(payload)
208
+ @callbacks[:blockhash].call(bh) if bh
209
+ end
210
+ when MessageType::QUOTE
211
+ if @callbacks[:quote]
212
+ quote = Decoder.decode_quote(payload)
213
+ @callbacks[:quote].call(quote) if quote
214
+ end
215
+ when MessageType::ERROR
216
+ @callbacks[:error]&.call(payload.force_encoding("UTF-8"))
217
+ end
218
+ end
219
+
220
+ def handle_text_message(data)
221
+ json = JSON.parse(data)
222
+ type = json["type"]
223
+
224
+ case type
225
+ when "heartbeat"
226
+ if @callbacks[:heartbeat]
227
+ hb = Heartbeat.new(
228
+ timestamp_ms: json["timestamp_ms"],
229
+ uptime_seconds: json["uptime_seconds"],
230
+ messages_received: json["messages_received"],
231
+ messages_sent: json["messages_sent"],
232
+ subscriptions: json["subscriptions"]
233
+ )
234
+ @callbacks[:heartbeat].call(hb)
235
+ end
236
+ when "subscribed"
237
+ # Subscription confirmed
238
+ when "error"
239
+ @callbacks[:error]&.call(json["message"])
240
+ end
241
+ rescue JSON::ParserError
242
+ # Ignore invalid JSON
243
+ end
244
+
245
+ def handle_close(_event)
246
+ @connected = false
247
+ @callbacks[:disconnected]&.call
248
+
249
+ schedule_reconnect if @running && @reconnect
250
+ end
251
+
252
+ def handle_error(error)
253
+ @callbacks[:error]&.call(error.message)
254
+ end
255
+
256
+ def schedule_reconnect
257
+ jitter = rand * 0.5
258
+ delay = [@reconnect_delay + jitter, @reconnect_delay_max].min
259
+
260
+ Thread.new do
261
+ sleep(delay)
262
+ do_connect if @running
263
+ end
264
+
265
+ @reconnect_delay = [@reconnect_delay * 2, @reconnect_delay_max].min
266
+ end
267
+
268
+ def send_subscribe
269
+ return unless @last_subscription
270
+
271
+ msg = { type: "subscribe", channels: @last_subscription[:channels] }
272
+ msg[:protocols] = @last_subscription[:protocols] if @last_subscription[:protocols]
273
+ msg[:pools] = @last_subscription[:pools] if @last_subscription[:pools]
274
+ msg[:token_pairs] = @last_subscription[:token_pairs] if @last_subscription[:token_pairs]
275
+
276
+ send_json(msg)
277
+ end
278
+
279
+ def send_json(data)
280
+ @ws&.send(data.to_json)
281
+ end
282
+ end
283
+ end
@@ -0,0 +1,330 @@
1
+ # frozen_string_literal: true
2
+
3
+ module K256
4
+ # Binary message decoder for K256 WebSocket protocol.
5
+ module Decoder
6
+ class << self
7
+ # Decode priority fees from binary payload.
8
+ # Wire format: 119 bytes, little-endian.
9
+ #
10
+ # @param data [String] Binary payload (without message type byte)
11
+ # @return [PriorityFees, nil] Decoded fees or nil if too short
12
+ def decode_priority_fees(data)
13
+ return nil if data.bytesize < 119
14
+
15
+ bytes = data.bytes
16
+
17
+ PriorityFees.new(
18
+ slot: read_u64_le(bytes, 0),
19
+ timestamp_ms: read_u64_le(bytes, 8),
20
+ recommended: read_u64_le(bytes, 16),
21
+ state: bytes[24],
22
+ is_stale: bytes[25] != 0,
23
+ swap_p50: read_u64_le(bytes, 26),
24
+ swap_p75: read_u64_le(bytes, 34),
25
+ swap_p90: read_u64_le(bytes, 42),
26
+ swap_p99: read_u64_le(bytes, 50),
27
+ swap_samples: read_u32_le(bytes, 58),
28
+ landing_p50_fee: read_u64_le(bytes, 62),
29
+ landing_p75_fee: read_u64_le(bytes, 70),
30
+ landing_p90_fee: read_u64_le(bytes, 78),
31
+ landing_p99_fee: read_u64_le(bytes, 86),
32
+ top_10_fee: read_u64_le(bytes, 94),
33
+ top_25_fee: read_u64_le(bytes, 102),
34
+ spike_detected: bytes[110] != 0,
35
+ spike_fee: read_u64_le(bytes, 111)
36
+ )
37
+ end
38
+
39
+ # Decode blockhash from binary payload.
40
+ # Wire format: 65 bytes, little-endian.
41
+ #
42
+ # @param data [String] Binary payload (without message type byte)
43
+ # @return [Blockhash, nil] Decoded blockhash or nil if too short
44
+ def decode_blockhash(data)
45
+ return nil if data.bytesize < 65
46
+
47
+ bytes = data.bytes
48
+
49
+ Blockhash.new(
50
+ slot: read_u64_le(bytes, 0),
51
+ timestamp_ms: read_u64_le(bytes, 8),
52
+ blockhash: Base58.encode(bytes[16, 32]),
53
+ block_height: read_u64_le(bytes, 48),
54
+ last_valid_block_height: read_u64_le(bytes, 56),
55
+ is_stale: bytes[64] != 0
56
+ )
57
+ end
58
+
59
+ # Decode a single pool update from binary payload.
60
+ #
61
+ # @param data [String] Binary payload (without message type byte)
62
+ # @return [PoolUpdate, nil] Decoded update or nil if decoding fails
63
+ def decode_pool_update(data)
64
+ return nil if data.bytesize < 8
65
+
66
+ bytes = data.bytes
67
+ offset = 0
68
+
69
+ # serialized_state: Bytes (u64 len + bytes)
70
+ state_len = read_u64_le(bytes, offset)
71
+ offset += 8
72
+ return nil if offset + state_len > bytes.length
73
+ serialized_state = bytes[offset, state_len].pack("C*")
74
+ offset += state_len
75
+
76
+ # sequence (u64)
77
+ return nil if offset + 8 > bytes.length
78
+ sequence = read_u64_le(bytes, offset)
79
+ offset += 8
80
+
81
+ # slot (u64)
82
+ return nil if offset + 8 > bytes.length
83
+ slot = read_u64_le(bytes, offset)
84
+ offset += 8
85
+
86
+ # write_version (u64)
87
+ return nil if offset + 8 > bytes.length
88
+ write_version = read_u64_le(bytes, offset)
89
+ offset += 8
90
+
91
+ # protocol_name: String (u64 len + UTF-8 bytes)
92
+ return nil if offset + 8 > bytes.length
93
+ protocol_len = read_u64_le(bytes, offset)
94
+ offset += 8
95
+ return nil if offset + protocol_len > bytes.length
96
+ protocol_name = bytes[offset, protocol_len].pack("C*").force_encoding("UTF-8")
97
+ offset += protocol_len
98
+
99
+ # pool_address: [u8; 32]
100
+ return nil if offset + 32 > bytes.length
101
+ pool_address = Base58.encode(bytes[offset, 32])
102
+ offset += 32
103
+
104
+ # all_token_mints: Vec<[u8; 32]>
105
+ return nil if offset + 8 > bytes.length
106
+ mint_count = read_u64_le(bytes, offset)
107
+ offset += 8
108
+ return nil if offset + mint_count * 32 > bytes.length
109
+ token_mints = mint_count.times.map do
110
+ mint = Base58.encode(bytes[offset, 32])
111
+ offset += 32
112
+ mint
113
+ end
114
+
115
+ # all_token_balances: Vec<u64>
116
+ return nil if offset + 8 > bytes.length
117
+ balance_count = read_u64_le(bytes, offset)
118
+ offset += 8
119
+ return nil if offset + balance_count * 8 > bytes.length
120
+ token_balances = balance_count.times.map do
121
+ balance = read_u64_le(bytes, offset)
122
+ offset += 8
123
+ balance
124
+ end
125
+
126
+ # all_token_decimals: Vec<i32>
127
+ return nil if offset + 8 > bytes.length
128
+ decimals_count = read_u64_le(bytes, offset)
129
+ offset += 8
130
+ return nil if offset + decimals_count * 4 > bytes.length
131
+ token_decimals = decimals_count.times.map do
132
+ dec = read_i32_le(bytes, offset)
133
+ offset += 4
134
+ dec
135
+ end
136
+
137
+ # best_bid: Option<OrderLevel>
138
+ best_bid = nil
139
+ if offset < bytes.length && bytes[offset] == 1
140
+ offset += 1
141
+ return nil if offset + 16 > bytes.length
142
+ best_bid = OrderLevel.new(
143
+ price: read_u64_le(bytes, offset),
144
+ size: read_u64_le(bytes, offset + 8)
145
+ )
146
+ offset += 16
147
+ elsif offset < bytes.length
148
+ offset += 1
149
+ end
150
+
151
+ # best_ask: Option<OrderLevel>
152
+ best_ask = nil
153
+ if offset < bytes.length && bytes[offset] == 1
154
+ offset += 1
155
+ return nil if offset + 16 > bytes.length
156
+ best_ask = OrderLevel.new(
157
+ price: read_u64_le(bytes, offset),
158
+ size: read_u64_le(bytes, offset + 8)
159
+ )
160
+ end
161
+
162
+ PoolUpdate.new(
163
+ sequence: sequence,
164
+ slot: slot,
165
+ write_version: write_version,
166
+ protocol_name: protocol_name,
167
+ pool_address: pool_address,
168
+ token_mints: token_mints,
169
+ token_balances: token_balances,
170
+ token_decimals: token_decimals,
171
+ best_bid: best_bid,
172
+ best_ask: best_ask,
173
+ serialized_state: serialized_state
174
+ )
175
+ rescue StandardError
176
+ nil
177
+ end
178
+
179
+ # Decode a batch of pool updates.
180
+ # Wire format: [u16 count][u32 len1][payload1]...
181
+ #
182
+ # @param data [String] Binary payload (without message type byte)
183
+ # @return [Array<PoolUpdate>] Decoded updates
184
+ def decode_pool_update_batch(data)
185
+ return [] if data.bytesize < 2
186
+
187
+ bytes = data.bytes
188
+ count = read_u16_le(bytes, 0)
189
+ offset = 2
190
+
191
+ updates = []
192
+ count.times do
193
+ break if offset + 4 > bytes.length
194
+
195
+ payload_len = read_u32_le(bytes, offset)
196
+ offset += 4
197
+
198
+ break if offset + payload_len > bytes.length
199
+
200
+ update_data = bytes[offset, payload_len].pack("C*")
201
+ update = decode_pool_update(update_data)
202
+ updates << update if update
203
+
204
+ offset += payload_len
205
+ end
206
+
207
+ updates
208
+ end
209
+
210
+ # Decode a quote from binary payload.
211
+ #
212
+ # @param data [String] Binary payload (without message type byte)
213
+ # @return [Quote, nil] Decoded quote or nil if decoding fails
214
+ def decode_quote(data)
215
+ return nil if data.bytesize < 8
216
+
217
+ bytes = data.bytes
218
+ offset = 0
219
+
220
+ # topic_id: String (u64 len + UTF-8 bytes)
221
+ topic_len = read_u64_le(bytes, offset)
222
+ offset += 8
223
+ topic_id = bytes[offset, topic_len].pack("C*").force_encoding("UTF-8")
224
+ offset += topic_len
225
+
226
+ # timestamp_ms (u64)
227
+ timestamp_ms = read_u64_le(bytes, offset)
228
+ offset += 8
229
+
230
+ # sequence (u64)
231
+ sequence = read_u64_le(bytes, offset)
232
+ offset += 8
233
+
234
+ # input_mint ([u8; 32])
235
+ input_mint = Base58.encode(bytes[offset, 32])
236
+ offset += 32
237
+
238
+ # output_mint ([u8; 32])
239
+ output_mint = Base58.encode(bytes[offset, 32])
240
+ offset += 32
241
+
242
+ # in_amount (u64)
243
+ in_amount = read_u64_le(bytes, offset)
244
+ offset += 8
245
+
246
+ # out_amount (u64)
247
+ out_amount = read_u64_le(bytes, offset)
248
+ offset += 8
249
+
250
+ # price_impact_bps (i32)
251
+ price_impact_bps = read_i32_le(bytes, offset)
252
+ offset += 4
253
+
254
+ # context_slot (u64)
255
+ context_slot = read_u64_le(bytes, offset)
256
+ offset += 8
257
+
258
+ # algorithm: String (u64 len + UTF-8 bytes)
259
+ algo_len = read_u64_le(bytes, offset)
260
+ offset += 8
261
+ algorithm = bytes[offset, algo_len].pack("C*").force_encoding("UTF-8")
262
+ offset += algo_len
263
+
264
+ # is_improvement (bool)
265
+ is_improvement = bytes[offset] != 0
266
+ offset += 1
267
+
268
+ # is_cached (bool)
269
+ is_cached = bytes[offset] != 0
270
+ offset += 1
271
+
272
+ # is_stale (bool)
273
+ is_stale = bytes[offset] != 0
274
+ offset += 1
275
+
276
+ # route_plan_json: Vec<u8> (u64 len + bytes)
277
+ route_plan_json = nil
278
+ if offset + 8 <= bytes.length
279
+ route_len = read_u64_le(bytes, offset)
280
+ offset += 8
281
+ if route_len.positive? && offset + route_len <= bytes.length
282
+ route_plan_json = bytes[offset, route_len].pack("C*").force_encoding("UTF-8")
283
+ end
284
+ end
285
+
286
+ Quote.new(
287
+ topic_id: topic_id,
288
+ timestamp_ms: timestamp_ms,
289
+ sequence: sequence,
290
+ input_mint: input_mint,
291
+ output_mint: output_mint,
292
+ in_amount: in_amount,
293
+ out_amount: out_amount,
294
+ price_impact_bps: price_impact_bps,
295
+ context_slot: context_slot,
296
+ algorithm: algorithm,
297
+ is_improvement: is_improvement,
298
+ is_cached: is_cached,
299
+ is_stale: is_stale,
300
+ route_plan_json: route_plan_json
301
+ )
302
+ rescue StandardError
303
+ nil
304
+ end
305
+
306
+ private
307
+
308
+ def read_u64_le(bytes, offset)
309
+ bytes[offset, 8].each_with_index.reduce(0) do |acc, (byte, i)|
310
+ acc | (byte << (i * 8))
311
+ end
312
+ end
313
+
314
+ def read_u32_le(bytes, offset)
315
+ bytes[offset, 4].each_with_index.reduce(0) do |acc, (byte, i)|
316
+ acc | (byte << (i * 8))
317
+ end
318
+ end
319
+
320
+ def read_u16_le(bytes, offset)
321
+ bytes[offset] | (bytes[offset + 1] << 8)
322
+ end
323
+
324
+ def read_i32_le(bytes, offset)
325
+ val = read_u32_le(bytes, offset)
326
+ val >= 0x80000000 ? val - 0x100000000 : val
327
+ end
328
+ end
329
+ end
330
+ end
data/lib/k256/types.rb ADDED
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ module K256
4
+ # WebSocket binary message type identifiers.
5
+ # These correspond to the first byte of each binary message.
6
+ module MessageType
7
+ POOL_UPDATE = 0x01 # Server → Client: Single pool update
8
+ SUBSCRIBE = 0x02 # Client → Server: Subscribe request (JSON)
9
+ SUBSCRIBED = 0x03 # Server → Client: Subscription confirmed (JSON)
10
+ UNSUBSCRIBE = 0x04 # Client → Server: Unsubscribe all
11
+ PRIORITY_FEES = 0x05 # Server → Client: Priority fee update
12
+ BLOCKHASH = 0x06 # Server → Client: Recent blockhash
13
+ QUOTE = 0x07 # Server → Client: Streaming quote update
14
+ QUOTE_SUBSCRIBED = 0x08 # Server → Client: Quote subscription confirmed
15
+ SUBSCRIBE_QUOTE = 0x09 # Client → Server: Subscribe to quote stream
16
+ UNSUBSCRIBE_QUOTE = 0x0A # Client → Server: Unsubscribe from quote
17
+ PING = 0x0B # Client → Server: Ping keepalive
18
+ PONG = 0x0C # Server → Client: Pong response
19
+ HEARTBEAT = 0x0D # Server → Client: Connection stats (JSON)
20
+ POOL_UPDATE_BATCH = 0x0E # Server → Client: Batched pool updates
21
+ ERROR = 0xFF # Server → Client: Error message (UTF-8)
22
+ end
23
+
24
+ # Network congestion state.
25
+ module NetworkState
26
+ LOW = 0 # Low congestion - minimal fees needed
27
+ NORMAL = 1 # Normal congestion
28
+ HIGH = 2 # High congestion - higher fees recommended
29
+ EXTREME = 3 # Extreme congestion - maximum fees recommended
30
+ end
31
+
32
+ # Order book level with price and size.
33
+ OrderLevel = Struct.new(:price, :size, keyword_init: true)
34
+
35
+ # Real-time pool state update from K256 WebSocket.
36
+ PoolUpdate = Struct.new(
37
+ :sequence,
38
+ :slot,
39
+ :write_version,
40
+ :protocol_name,
41
+ :pool_address,
42
+ :token_mints,
43
+ :token_balances,
44
+ :token_decimals,
45
+ :best_bid,
46
+ :best_ask,
47
+ :serialized_state,
48
+ keyword_init: true
49
+ )
50
+
51
+ # Priority fee recommendations from K256.
52
+ # Wire format: 119 bytes, little-endian.
53
+ PriorityFees = Struct.new(
54
+ :slot, # offset 0
55
+ :timestamp_ms, # offset 8
56
+ :recommended, # offset 16
57
+ :state, # offset 24
58
+ :is_stale, # offset 25
59
+ :swap_p50, # offset 26
60
+ :swap_p75, # offset 34
61
+ :swap_p90, # offset 42
62
+ :swap_p99, # offset 50
63
+ :swap_samples, # offset 58
64
+ :landing_p50_fee, # offset 62
65
+ :landing_p75_fee, # offset 70
66
+ :landing_p90_fee, # offset 78
67
+ :landing_p99_fee, # offset 86
68
+ :top_10_fee, # offset 94
69
+ :top_25_fee, # offset 102
70
+ :spike_detected, # offset 110
71
+ :spike_fee, # offset 111
72
+ keyword_init: true
73
+ )
74
+
75
+ # Recent blockhash from K256.
76
+ # Wire format: 65 bytes, little-endian.
77
+ Blockhash = Struct.new(
78
+ :slot, # offset 0
79
+ :timestamp_ms, # offset 8
80
+ :blockhash, # offset 16 (32 bytes)
81
+ :block_height, # offset 48
82
+ :last_valid_block_height, # offset 56
83
+ :is_stale, # offset 64
84
+ keyword_init: true
85
+ )
86
+
87
+ # Swap quote from K256.
88
+ Quote = Struct.new(
89
+ :topic_id,
90
+ :timestamp_ms,
91
+ :sequence,
92
+ :input_mint,
93
+ :output_mint,
94
+ :in_amount,
95
+ :out_amount,
96
+ :price_impact_bps,
97
+ :context_slot,
98
+ :algorithm,
99
+ :is_improvement,
100
+ :is_cached,
101
+ :is_stale,
102
+ :route_plan_json,
103
+ keyword_init: true
104
+ )
105
+
106
+ # Connection heartbeat with stats.
107
+ Heartbeat = Struct.new(
108
+ :timestamp_ms,
109
+ :uptime_seconds,
110
+ :messages_received,
111
+ :messages_sent,
112
+ :subscriptions,
113
+ keyword_init: true
114
+ )
115
+
116
+ # Token metadata.
117
+ Token = Struct.new(
118
+ :address,
119
+ :symbol,
120
+ :name,
121
+ :decimals,
122
+ :logo_uri,
123
+ :tags,
124
+ :extensions,
125
+ keyword_init: true
126
+ )
127
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module K256
4
+ VERSION = "0.1.0"
5
+ end
data/lib/k256.rb ADDED
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "k256/version"
4
+ require_relative "k256/types"
5
+ require_relative "k256/base58"
6
+ require_relative "k256/decoder"
7
+ require_relative "k256/client"
8
+
9
+ # K256 SDK - The gateway to Solana's liquidity ecosystem
10
+ #
11
+ # @example
12
+ # require 'k256'
13
+ #
14
+ # client = K256::Client.new(api_key: ENV['K256_API_KEY'])
15
+ #
16
+ # client.on_pool_update do |update|
17
+ # puts "Pool #{update.pool_address}: slot=#{update.slot}"
18
+ # end
19
+ #
20
+ # client.connect
21
+ # client.subscribe(channels: ['pools', 'priority_fees', 'blockhash'])
22
+ module K256
23
+ class Error < StandardError; end
24
+ class ConnectionError < Error; end
25
+ class DecodeError < Error; end
26
+ end
metadata ADDED
@@ -0,0 +1,112 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: k256-sdk
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - K256
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-01-30 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: websocket-client-simple
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.8'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.8'
27
+ - !ruby/object:Gem::Dependency
28
+ name: json
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.6'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.6'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.12'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.12'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rubocop
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.50'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.50'
69
+ description: Connect any application to Solana's liquidity ecosystem. One API. All
70
+ venues. Full observability.
71
+ email:
72
+ - support@k256.xyz
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - LICENSE
78
+ - README.md
79
+ - lib/k256.rb
80
+ - lib/k256/base58.rb
81
+ - lib/k256/client.rb
82
+ - lib/k256/decoder.rb
83
+ - lib/k256/types.rb
84
+ - lib/k256/version.rb
85
+ homepage: https://k256.xyz
86
+ licenses:
87
+ - MIT
88
+ metadata:
89
+ homepage_uri: https://k256.xyz
90
+ source_code_uri: https://github.com/k256-xyz/k256-sdks
91
+ changelog_uri: https://github.com/k256-xyz/k256-sdks/releases
92
+ documentation_uri: https://docs.k256.xyz
93
+ post_install_message:
94
+ rdoc_options: []
95
+ require_paths:
96
+ - lib
97
+ required_ruby_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: 3.0.0
102
+ required_rubygems_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ requirements: []
108
+ rubygems_version: 3.0.3.1
109
+ signing_key:
110
+ specification_version: 4
111
+ summary: Official Ruby SDK for K256 - the gateway to Solana's liquidity ecosystem
112
+ test_files: []