solana-sdp 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: e006d934cc75d32a431afa36112f78edb06d66dce75632eb3d5247b8c491d29b
4
+ data.tar.gz: 3766da4b325de50624bb961f60521e07705eb3b70a9115e5be4681152c6083a7
5
+ SHA512:
6
+ metadata.gz: e43f33123cccad9386df7844d227861ffa61499d6a873a90629d32273a62e1f7c9b365add4eff823bf504f204e78106d7f3456de4ec823ed8042772912b42e9e
7
+ data.tar.gz: 245615dd77504bd7a4d5890e9868ad01b0137f5c58d8aba6efd02c5b20dbedb98e64d2fecb36cfd705989bd13481e81767bf7ffbf9db210abf1a022d4f56d319
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Jose Ferrer
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # solana-sdp
2
+
3
+ Ruby SDK for the [Solana Developer Platform](https://github.com/solana-foundation/solana-developer-platform) (SDP) wallets and payments API.
4
+
5
+ Plain Ruby, zero runtime dependencies (`Net::HTTP`), typed rescuable errors that mirror SDP's real failure modes, and a retry posture that never re-sends a transfer.
6
+
7
+ > SDP is pre-mainnet, unaudited, and devnet-oriented — so is this gem. Tested against SDP **v0.28** (see [Version pin](#version-pin) below).
8
+
9
+ ## Install
10
+
11
+ Add to your Gemfile:
12
+
13
+ ```ruby
14
+ gem "solana-sdp"
15
+ ```
16
+
17
+ Or install directly:
18
+
19
+ ```sh
20
+ gem install solana-sdp
21
+ ```
22
+
23
+ Requires Ruby >= 3.2.
24
+
25
+ ## Quickstart
26
+
27
+ Point the client at a running SDP instance (local default: `http://127.0.0.1:8787`) with an API key:
28
+
29
+ ```ruby
30
+ require "solana-sdp"
31
+
32
+ # Reads SDP_API_BASE_URL / SDP_API_KEY from ENV, or pass them explicitly.
33
+ client = Sdp::Client.new(api_key: "sk_...")
34
+
35
+ # One-time custody setup for the project (provider defaults to SDP's
36
+ # configured custody provider; pass provider: "privy" etc. for managed custody).
37
+ client.initialize_custody
38
+
39
+ # Create a wallet (requires a managed custody provider — see
40
+ # Sdp::ProviderCapabilityError below for what happens on local custody).
41
+ wallet = client.create_wallet(label: "user-42")
42
+ wallet.id # => "wal_..." (SDP's walletId — what the payments API expects)
43
+ wallet.public_key # => "8x3f..."
44
+
45
+ # Check balances. A missing token row means "unavailable", never zero —
46
+ # SDP swallows RPC failures upstream.
47
+ client.wallet_balances(wallet.id).each do |balance|
48
+ puts "#{balance.token}: #{balance.ui_amount} (#{balance.usd_value || "no price"})"
49
+ end
50
+
51
+ # Send a transfer (synchronous sign-and-send; SDP confirms before responding).
52
+ transfer = client.create_transfer(
53
+ source: wallet.id,
54
+ destination: "Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS",
55
+ amount: "0.05",
56
+ token: "SOL"
57
+ )
58
+ transfer.status # => "confirmed"
59
+ transfer.signature # => on-chain signature
60
+
61
+ # List transfers — returns a lazy enumerator that auto-paginates by
62
+ # following meta.hasMore. Pass page: to pin a single page instead.
63
+ client.list_transfers(wallet: wallet.id, direction: "outbound").each do |t|
64
+ puts "#{t.created_at} #{t.amount} #{t.token} -> #{t.destination} [#{t.status}]"
65
+ end
66
+ ```
67
+
68
+ Also available: `prepare_transfer` (build but don't sign/send, for non-custodial flows), `get_transfer`, `list_wallets`.
69
+
70
+ `list_wallets` returns an **Array** (`[Sdp::Wallet, ...]`) today — SDP does not paginate `/v1/wallets` at v0.28, so the result is fetched eagerly. When SDP adds pagination this will become a lazy Enumerator (matching `list_transfers`). Use Enumerable methods (`.find`, `.each`, `.map`) rather than array indexing or `.length` to stay forward-compatible.
71
+
72
+ ## Error taxonomy
73
+
74
+ Everything raised by this gem subclasses `Sdp::Error`, which carries `#code`, `#http_status`, `#details`, and `#meta` alongside the message. Both `#details` and `#meta` are Hashes with **snake_case symbol keys** — SDP's camelCase JSON is converted to Ruby style throughout (e.g. `error.details[:field_errors]`, not `"fieldErrors"` or `:fieldErrors`). The taxonomy mirrors how SDP actually fails:
75
+
76
+ | Class | Raised when | Retryable? |
77
+ |---|---|---|
78
+ | `Sdp::ConfigurationError` | At construction: `SDP_API_KEY` missing/blank | No — fix config |
79
+ | `Sdp::BadRequest` | 400 — the request itself is wrong (validation errors) | No |
80
+ | `Sdp::ProviderCapabilityError` (< `BadRequest`) | The configured custody provider cannot serve the request: 400 wallet-provisioning gate, or 409 on a second `initialize_custody` | No — change provider config |
81
+ | `Sdp::Unauthorized` | 401 — key missing, malformed, or revoked | No |
82
+ | `Sdp::Forbidden` | 403 | No |
83
+ | `Sdp::InsufficientPermissions` (< `Forbidden`) | 403 with `INSUFFICIENT_PERMISSIONS` — key lacks the required scope | No |
84
+ | `Sdp::NotFound` | 404 — but see the [wallet-scoped key note](#the-wallet-scoped-404) | No |
85
+ | `Sdp::Conflict` | 409 — resource already exists / conflicting state | No |
86
+ | `Sdp::SigningPending` | HTTP 202 — accepted, awaiting additional signatures (multisig/approval flows). **Not a success** | No — poll/approve |
87
+ | `Sdp::TransactionFailed` | `TRANSACTION_FAILED` — the on-chain transaction was attempted and failed (e.g. insufficient lamports) | **Never** — outcome semantics, not transport |
88
+ | `Sdp::RateLimited` | 429 | Yes, with backoff |
89
+ | `Sdp::Timeout` | Read timeout — for POSTs the outcome is **unknown** | Reads yes; writes: reconcile first |
90
+ | `Sdp::Unavailable` | Connection refused/reset, connect timeout, or a 5xx that isn't a recognized capability gate | Yes — the request wasn't processed |
91
+ | `Sdp::TransferExecutionError` (< `Sdp::Error`) | 502 `SOLANA_RPC_ERROR` carrying SDP's NativeAdapter signature — the fee-payment provider cannot submit transactions. **Not caught by `rescue Sdp::Unavailable`** — it is not a transient error | No — configuration fix |
92
+
93
+ Two of these encode SDP capability gates that otherwise surface as cryptic generic errors (discriminator strings verified against SDP v0.28, documented in `lib/sdp/errors.rb`):
94
+
95
+ - **`Sdp::ProviderCapabilityError`** — with local custody, SDP holds a single root wallet and `POST /v1/wallets` is rejected ("Wallet provisioning not supported for provider: local"). Wallet-per-User requires a managed provider (e.g. privy): pass `provider:` to `create_wallet` or set `SDP_CUSTODY_PROVIDER`. Also raised when `initialize_custody` is called twice for the same org+project (409) — initialization is one-time.
96
+ - **`Sdp::TransferExecutionError`** — with `FEE_PAYMENT_PROVIDER=native`, SDP can build and sign transfers but cannot submit them; the 502 message contains the `NativeAdapter` signature. Fix: run Kora and set `FEE_PAYMENT_PROVIDER=kora`. A 502 that does *not* match this signature stays `Sdp::Unavailable` — a real RPC outage is never mislabeled as a configuration problem.
97
+
98
+ ## Retry posture
99
+
100
+ - **GETs retry exactly once** on `Sdp::Timeout` / `Sdp::Unavailable` (transport-level failures), then raise.
101
+ - **POSTs never retry.** SDP has no idempotency key at v0.28: re-sending a transfer after a read timeout risks a double-spend, because the first attempt may have landed on-chain. On `Sdp::Timeout` from a write, reconcile first (e.g. `list_transfers` filtered by wallet, or match a memo) before re-submitting.
102
+ - `Sdp::TransactionFailed` is never retried blindly — it reports an on-chain outcome, not a transport failure.
103
+ - `Sdp::Unavailable` means the request was not processed (connection never opened, or a 5xx without SDP's error envelope), so it is safe to retry — with backoff for `Sdp::RateLimited`.
104
+
105
+ ### The wallet-scoped 404
106
+
107
+ Wallet-scoped API keys return **404 (not 403)** for wallets outside their scope. "Not found" can therefore mean "not yours". Every `Sdp::NotFound` message carries this hint so the failure is diagnosable from logs.
108
+
109
+ ## Version pin
110
+
111
+ ```ruby
112
+ Sdp::COMPATIBLE_SDP_VERSION # => "0.28"
113
+ ```
114
+
115
+ SDP breaks its API between minor versions. Every release of this gem names the SDP version it was tested against, both here and in the `Sdp::COMPATIBLE_SDP_VERSION` constant. The covered API surface is pinned to a vendored copy of SDP's OpenAPI spec (`spec/openapi-v0.28.json`); contract tests assert every field this gem reads exists in that spec, and `rake "sdp:drift[path/to/newer/openapi.json]"` diffs a newer SDP spec against the pin to report exactly which covered endpoints changed. On an SDP version bump: re-vendor the spec, re-run the contract tests, update `COMPATIBLE_SDP_VERSION`.
116
+
117
+ Running against a different SDP version may work, but field shapes (e.g. `usdValue` on balances) are known to change between minors.
118
+
119
+ ## Scope
120
+
121
+ This gem covers SDP's wallets and payments surface: custody initialization, wallet provisioning and listing, balances, and transfers (create/prepare/list/get). Ramps, issuance, and the dashboard APIs are out of scope.
122
+
123
+ A Rails engine builds on this client — Wallet-per-User provisioning, transfer persistence, and realtime balance updates — as [solrengine-sdp](https://github.com/solrengine/sdp).
124
+
125
+ ## See also
126
+
127
+ - [solrengine-sdp](https://github.com/solrengine/sdp) — the Rails engine on top of this client: Wallet-per-User provisioning, tracked transfers, live balance updates.
128
+ - [solrengine.org](https://solrengine.org) — the SolRengine family: the connect-your-wallet stack, and how both custody models compose.
129
+ - [Solana Developer Platform](https://github.com/solana-foundation/solana-developer-platform) — the SDP itself: the wallets + payments API this gem covers.
130
+
131
+ ## Development
132
+
133
+ ```sh
134
+ bundle install
135
+ bundle exec rake test # minitest + WebMock, no network
136
+ bundle exec rubocop
137
+ ```
138
+
139
+ ## License
140
+
141
+ MIT. See [LICENSE.txt](LICENSE.txt).
data/lib/sdp/client.rb ADDED
@@ -0,0 +1,293 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "json"
6
+ require "uri"
7
+
8
+ require_relative "errors"
9
+ require_relative "pagination"
10
+ require_relative "resources/wallets"
11
+ require_relative "resources/payments"
12
+
13
+ module Sdp
14
+ # Zero-dependency Net::HTTP request core for the SDP API.
15
+ #
16
+ # Success envelope: { "data": ..., "meta": ... }
17
+ # Error envelope: { "error": { "code", "message", "details" }, "meta": ... }
18
+ #
19
+ # Retry policy: GETs retry once on Timeout/Unavailable. POSTs NEVER retry —
20
+ # SDP has no idempotency key, so re-sending a transfer risks a double-spend.
21
+ #
22
+ # Endpoint methods live in resource modules layered on top of the #get/#post
23
+ # primitives below; this class owns auth, envelope handling, the typed error
24
+ # mapping, and the retry posture.
25
+ class Client
26
+ include Resources::Wallets
27
+ include Resources::Payments
28
+
29
+ DEFAULT_BASE_URL = "http://127.0.0.1:8787"
30
+ OPEN_TIMEOUT = 2 # seconds — fail fast when the stack isn't up
31
+ READ_TIMEOUT = 10 # seconds — transfer confirmation is synchronous
32
+
33
+ # Wallet-scoped API keys return 404 (not 403) for wallets outside their
34
+ # scope, which reads like "does not exist" when it really means "not
35
+ # yours". Appended to every NotFound so the failure is diagnosable.
36
+ NOT_FOUND_HINT = "(hint: wallet-scoped API keys return 404 for wallets outside their scope)"
37
+
38
+ # Request-layer result: the unwrapped envelope `data` plus `meta`.
39
+ # Resource methods generally return data to callers; pagination needs
40
+ # meta (hasMore/page), so the request layer always carries both.
41
+ Response = Struct.new(:data, :meta, keyword_init: true)
42
+
43
+ attr_reader :base_url
44
+
45
+ def initialize(base_url: ENV.fetch("SDP_API_BASE_URL", DEFAULT_BASE_URL),
46
+ api_key: ENV["SDP_API_KEY"],
47
+ open_timeout: OPEN_TIMEOUT,
48
+ read_timeout: READ_TIMEOUT)
49
+ # Strip first, then guard: an ENV key with a trailing newline passes a
50
+ # naive blank-check but then makes every request raise a raw ArgumentError
51
+ # from the "Bearer …\n" header. Normalize once, at the boundary.
52
+ @api_key = api_key.to_s.strip
53
+ if @api_key.empty?
54
+ raise ConfigurationError, "SDP_API_KEY is missing or blank. " \
55
+ "Pass api_key: or set the SDP_API_KEY environment variable."
56
+ end
57
+
58
+ @base_url = base_url.to_s.chomp("/")
59
+ # base_url is documented as ConfigurationError-covered, so validate it at
60
+ # boot (mirroring the api_key fail-fast) instead of letting an unusable
61
+ # URL surface as a cryptic transport error on the first request.
62
+ parsed = begin
63
+ URI.parse(@base_url)
64
+ rescue URI::InvalidURIError
65
+ nil
66
+ end
67
+ unless parsed.is_a?(URI::HTTP) && !parsed.host.to_s.empty?
68
+ raise ConfigurationError, "SDP_API_BASE_URL is invalid: expected an http(s) URL with a " \
69
+ "host, got #{@base_url.inspect}. Pass base_url: or set the SDP_API_BASE_URL environment variable."
70
+ end
71
+
72
+ @open_timeout = open_timeout
73
+ @read_timeout = read_timeout
74
+ end
75
+
76
+ # Redacted on purpose: the API key is a bearer secret and must never leak
77
+ # into consoles, logs, or exception-capture payloads via the default
78
+ # #inspect (which would dump every instance variable, @api_key included).
79
+ def inspect
80
+ "#<#{self.class} base_url=#{@base_url.inspect}>"
81
+ end
82
+
83
+ # Request primitives — the internal API the resource modules build on.
84
+ # Both return a Response(data:, meta:) with recursively snake_cased
85
+ # symbol keys, or raise a typed Sdp::Error.
86
+
87
+ # Reads are safe to retry exactly once on transport-level failures.
88
+ def get(path, query: nil)
89
+ uri = build_uri(path, query)
90
+ with_read_retry do
91
+ perform(Net::HTTP::Get.new(uri), uri, idempotent: true)
92
+ end
93
+ end
94
+
95
+ def post(path, payload = nil)
96
+ uri = build_uri(path, nil)
97
+ request = Net::HTTP::Post.new(uri)
98
+ request["Content-Type"] = "application/json"
99
+ request.body = JSON.generate(payload) unless payload.nil?
100
+ perform(request, uri, idempotent: false) # no retry wrapper — writes are never retried
101
+ end
102
+
103
+ private
104
+
105
+ def with_read_retry
106
+ attempts = 0
107
+ begin
108
+ attempts += 1
109
+ yield
110
+ rescue Sdp::Timeout, Sdp::Unavailable
111
+ retry if attempts < 2
112
+ raise
113
+ end
114
+ end
115
+
116
+ # idempotent: is the safety hinge. A GET can be re-sent freely, so any
117
+ # transport failure on it is "unreachable" (Unavailable, retryable). A POST
118
+ # has no upstream idempotency key, so once the socket was live we cannot
119
+ # know whether the transfer was processed — those failures must surface as
120
+ # the unknown-outcome Timeout (reconcile before re-sending), never as a
121
+ # retryable Unavailable that would risk a double-spend.
122
+ def perform(request, uri, idempotent:)
123
+ request["Authorization"] = "Bearer #{@api_key}"
124
+ request["Accept"] = "application/json"
125
+
126
+ response = Net::HTTP.start(
127
+ uri.host, uri.port,
128
+ use_ssl: uri.scheme == "https",
129
+ open_timeout: @open_timeout,
130
+ read_timeout: @read_timeout
131
+ ) { |http| http.request(request) }
132
+
133
+ handle(response, uri.path)
134
+ rescue Net::OpenTimeout => e
135
+ # The TCP connection never opened — the request was definitely not
136
+ # sent, so this is "unreachable" (safe to retry/fall back), never the
137
+ # unknown-outcome Timeout that triggers transfer reconciliation. Holds
138
+ # for POSTs too: nothing crossed the wire.
139
+ raise Sdp::Unavailable.new("SDP unreachable (connect timeout): #{e.message}", http_status: nil)
140
+ rescue Net::ReadTimeout => e
141
+ # The request was fully sent and we timed out awaiting the response —
142
+ # the outcome is unknown for everyone, so always Timeout.
143
+ raise Sdp::Timeout.new("SDP request timed out: #{e.message}", http_status: nil)
144
+ rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, SocketError,
145
+ OpenSSL::SSL::SSLError, Errno::ETIMEDOUT => e
146
+ # Connection never established / DNS failure / TLS handshake failure /
147
+ # connect-phase timeout — all provably pre-send, so the request was not
148
+ # processed. Safe to retry regardless of method.
149
+ raise Sdp::Unavailable.new("SDP unreachable: #{e.message}", http_status: nil)
150
+ rescue Errno::ECONNRESET, EOFError, Errno::EPIPE, Net::WriteTimeout => e
151
+ # The socket was live (reset/EOF/broken-pipe/write-timeout). For a GET
152
+ # this is still safe to retry. For a POST the reset can land AFTER the
153
+ # body was delivered and processed — outcome unknown — so it must map to
154
+ # Timeout (reconcile), not the retryable Unavailable.
155
+ if idempotent
156
+ raise Sdp::Unavailable.new("SDP unreachable: #{e.message}", http_status: nil)
157
+ else
158
+ raise Sdp::Timeout.new("SDP write failed mid-flight, outcome unknown: #{e.message}", http_status: nil)
159
+ end
160
+ end
161
+
162
+ def build_uri(path, query)
163
+ uri = URI.parse("#{@base_url}#{path}")
164
+ if query
165
+ compacted = query.compact
166
+ uri.query = URI.encode_www_form(compacted) unless compacted.empty?
167
+ end
168
+ uri
169
+ end
170
+
171
+ def handle(response, path)
172
+ status = response.code.to_i
173
+ body = parse_body(response.body)
174
+
175
+ # HTTP 202 is SDP's "accepted, awaiting signatures" response. It is in
176
+ # the 2xx range but carries the ERROR envelope, so it must be handled
177
+ # before the success branch or it silently parses as a success.
178
+ raise_typed_error(status, body, path) if status == 202
179
+
180
+ if (200..299).cover?(status)
181
+ # parse_body returns nil both for an empty body (204, fine) and for a
182
+ # non-empty body that failed to parse. The latter must not slip through
183
+ # as Response(data: nil) — that NoMethodErrors later in resource
184
+ # readers. Distinguish the two by the raw body and raise a typed error
185
+ # for the truncated/unparseable case.
186
+ if body.nil? && !response.body.to_s.empty?
187
+ raise Sdp::Unavailable.new("malformed response from SDP (unparseable body)", http_status: status)
188
+ end
189
+
190
+ data = body.is_a?(Hash) && body.key?("data") ? body["data"] : body
191
+ meta = body.is_a?(Hash) ? body["meta"] : nil
192
+ return Response.new(data: symbolize(data), meta: symbolize(meta))
193
+ end
194
+
195
+ raise_typed_error(status, body, path)
196
+ end
197
+
198
+ def parse_body(raw)
199
+ return nil if raw.nil? || raw.empty?
200
+ JSON.parse(raw)
201
+ rescue JSON::ParserError
202
+ nil
203
+ end
204
+
205
+ def raise_typed_error(status, body, path)
206
+ error = body.is_a?(Hash) ? body["error"] : nil
207
+ code = error.is_a?(Hash) ? error["code"] : nil
208
+ message = (error.is_a?(Hash) && error["message"]) || "SDP request failed (HTTP #{status})"
209
+ details =
210
+ if error.is_a?(Hash)
211
+ symbolize(error["details"])
212
+ elsif body.is_a?(Hash) && body.key?("data")
213
+ # A 202 (or similar) can carry a data envelope rather than an error
214
+ # object (e.g. a pending transfer's id). Surface that as details so
215
+ # the rescued SigningPending can recover the transferId.
216
+ symbolize(body["data"])
217
+ end
218
+ meta = body.is_a?(Hash) ? symbolize(body["meta"]) : nil
219
+
220
+ klass = error_class_for(status, code)
221
+ klass, message = capability_gate(klass, status, code, message, path)
222
+ message = "#{message} #{NOT_FOUND_HINT}" if klass <= Sdp::NotFound
223
+ raise klass.new(message, code: code, http_status: status, details: details, meta: meta)
224
+ end
225
+
226
+ # FL-10/FL-11: SDP reports custody/fee-payment capability gates as
227
+ # generic 400/409/502 responses. Discriminators verified against SDP
228
+ # v0.28 (pattern constants documented in errors.rb). The upstream
229
+ # message is preserved and the fix is appended, so logs keep the
230
+ # original evidence.
231
+ def capability_gate(klass, status, code, message, path)
232
+ if status == 400 && path.to_s.end_with?("/v1/wallets") &&
233
+ message.to_s.match?(Sdp::ProviderCapabilityError::PROVISIONING_GATE_PATTERN)
234
+ [ Sdp::ProviderCapabilityError,
235
+ "#{message} — local custody holds a single root wallet; Wallet-per-User requires a " \
236
+ "managed provider (e.g. privy) — set provider: on create_wallet or SDP_CUSTODY_PROVIDER." ]
237
+ elsif status == 409 && path.to_s.end_with?("/v1/wallets/initialize")
238
+ [ Sdp::ProviderCapabilityError,
239
+ "#{message} — custody is already initialized for this organization/project; " \
240
+ "initialize_custody is one-time. Use list_wallets to find the existing root wallet." ]
241
+ elsif status == 502 && code == "SOLANA_RPC_ERROR" &&
242
+ message.to_s.match?(Sdp::TransferExecutionError::NATIVE_ADAPTER_PATTERN)
243
+ [ Sdp::TransferExecutionError,
244
+ "#{message} — SDP's native fee adapter cannot submit transactions; " \
245
+ "run Kora and set FEE_PAYMENT_PROVIDER=kora." ]
246
+ else
247
+ [ klass, message ]
248
+ end
249
+ end
250
+
251
+ # Code takes precedence over status; status is the fallback. A 5xx that
252
+ # doesn't carry SDP's error shape is treated as Unavailable (proxy error,
253
+ # crash page, etc.) so GETs can retry it.
254
+ def error_class_for(status, code)
255
+ case code
256
+ when "UNAUTHORIZED" then return Sdp::Unauthorized
257
+ when "INSUFFICIENT_PERMISSIONS" then return Sdp::InsufficientPermissions
258
+ when "FORBIDDEN" then return Sdp::Forbidden
259
+ when "TRANSACTION_FAILED" then return Sdp::TransactionFailed
260
+ when "RATE_LIMITED" then return Sdp::RateLimited
261
+ when "NOT_FOUND" then return Sdp::NotFound
262
+ when "CONFLICT" then return Sdp::Conflict
263
+ when "SIGNING_PENDING" then return Sdp::SigningPending
264
+ when "BAD_REQUEST", "VALIDATION_ERROR" then return Sdp::BadRequest
265
+ end
266
+
267
+ case status
268
+ when 202 then Sdp::SigningPending
269
+ when 401 then Sdp::Unauthorized
270
+ when 403 then Sdp::Forbidden
271
+ when 404 then Sdp::NotFound
272
+ when 409 then Sdp::Conflict
273
+ when 429 then Sdp::RateLimited
274
+ when 400..499 then Sdp::BadRequest
275
+ when 500..599 then Sdp::Unavailable
276
+ else Sdp::Error
277
+ end
278
+ end
279
+
280
+ # camelCase JSON → snake_case symbol keys, recursively.
281
+ def symbolize(value)
282
+ case value
283
+ when Hash then value.each_with_object({}) { |(k, v), h| h[underscore_key(k)] = symbolize(v) }
284
+ when Array then value.map { |v| symbolize(v) }
285
+ else value
286
+ end
287
+ end
288
+
289
+ def underscore_key(key)
290
+ key.to_s.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase.to_sym
291
+ end
292
+ end
293
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sdp
4
+ # The curated SDP surface this gem covers, pinned against the vendored
5
+ # OpenAPI spec (spec/openapi-v0.28.json). Consumed by the contract tests
6
+ # (test/sdp/contract_test.rb) and the sdp:drift rake task.
7
+ #
8
+ # Path templates use the {param} style of SDP's generated spec. When a
9
+ # resource method is added or removed, this map changes in the same commit.
10
+ module Coverage
11
+ # method/path identify the operation; success_status is the documented
12
+ # success response; reads maps a navigation path inside the success
13
+ # schema to the camelCase fields our structs read at that node. A "[]"
14
+ # segment descends into array items; the empty path is the schema root.
15
+ Endpoint = Struct.new(:method, :path, :success_status, :reads, keyword_init: true)
16
+
17
+ # Fields read by Sdp::Wallet.from_hash.
18
+ WALLET_FIELDS = %w[id walletId publicKey label status provider purpose createdAt balances].freeze
19
+ # Fields read by Sdp::Balance.from_hash. usdValue is optional upstream —
20
+ # presence in the schema's properties is what we pin, not requiredness.
21
+ BALANCE_FIELDS = %w[token mint amount uiAmount decimals usdValue].freeze
22
+ # Fields read by Sdp::Transfer.from_hash.
23
+ TRANSFER_FIELDS = %w[id direction status signature token amount source destination memo error createdAt].freeze
24
+
25
+ COVERED_ENDPOINTS = [
26
+ # NOTE: at v0.28 the initialize 201 response has NO data envelope —
27
+ # configId/publicKey/walletId sit at the schema root.
28
+ Endpoint.new(method: "post", path: "/v1/wallets/initialize", success_status: "201",
29
+ reads: { [] => %w[configId publicKey walletId] }),
30
+ Endpoint.new(method: "post", path: "/v1/wallets", success_status: "201",
31
+ reads: { %w[data wallet] => WALLET_FIELDS }),
32
+ Endpoint.new(method: "get", path: "/v1/wallets", success_status: "200",
33
+ reads: { [ "data", "wallets", "[]" ] => WALLET_FIELDS }),
34
+ Endpoint.new(method: "get", path: "/v1/payments/wallets/{walletId}/balances", success_status: "200",
35
+ reads: { %w[data walletBalances] => %w[walletId balances],
36
+ [ "data", "walletBalances", "balances", "[]" ] => BALANCE_FIELDS }),
37
+ Endpoint.new(method: "post", path: "/v1/payments/transfers", success_status: "200",
38
+ reads: { %w[data transfer] => TRANSFER_FIELDS }),
39
+ Endpoint.new(method: "post", path: "/v1/payments/transfers/prepare", success_status: "200",
40
+ reads: { %w[data] => %w[transfer preparedTransaction simulation],
41
+ %w[data transfer] => TRANSFER_FIELDS,
42
+ %w[data preparedTransaction] => %w[serialized blockhash lastValidBlockHeight] }),
43
+ Endpoint.new(method: "get", path: "/v1/payments/transfers", success_status: "200",
44
+ reads: { [ "data", "[]" ] => TRANSFER_FIELDS }),
45
+ Endpoint.new(method: "get", path: "/v1/payments/transfers/{transferId}", success_status: "200",
46
+ reads: { %w[data transfer] => TRANSFER_FIELDS })
47
+ ].freeze
48
+
49
+ class << self
50
+ # The application/json schema of the endpoint's documented success
51
+ # response, $ref-resolved. nil when the spec doesn't document it.
52
+ def success_schema(spec, endpoint)
53
+ operation = spec.dig("paths", endpoint.path, endpoint.method)
54
+ schema = operation&.dig("responses", endpoint.success_status, "content", "application/json", "schema")
55
+ resolve(spec, schema)
56
+ end
57
+
58
+ # Navigates a (resolved) schema along a reads path. "[]" descends into
59
+ # array items; any other segment descends into that property. Returns
60
+ # the resolved node, or nil as soon as the path breaks.
61
+ def walk(spec, schema, segments)
62
+ segments.reduce(resolve(spec, schema)) do |node, segment|
63
+ break nil unless node
64
+
65
+ child = segment == "[]" ? node["items"] : node.dig("properties", segment)
66
+ resolve(spec, child)
67
+ end
68
+ end
69
+
70
+ # Follows "$ref": "#/components/schemas/X" pointers (recursively, with
71
+ # a depth guard). SDP's generated spec is fully inlined today (zero
72
+ # $refs at v0.28) — this keeps the guard working if that changes.
73
+ def resolve(spec, node, depth = 0)
74
+ return node unless node.is_a?(Hash) && node["$ref"].is_a?(String)
75
+ return nil if depth > 10
76
+
77
+ name = node["$ref"][%r{\A#/components/schemas/(.+)\z}, 1]
78
+ return nil unless name
79
+
80
+ resolve(spec, spec.dig("components", "schemas", name), depth + 1)
81
+ end
82
+ end
83
+ end
84
+ end
data/lib/sdp/drift.rb ADDED
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "coverage"
5
+
6
+ module Sdp
7
+ # Diffs a newer SDP OpenAPI spec against the vendored pin, restricted to
8
+ # the covered surface (Sdp::Coverage::COVERED_ENDPOINTS). Drives the
9
+ # `rake "sdp:drift[path]"` task.
10
+ #
11
+ # A diff is a REPORT, not a build failure: SDP moving must never break this
12
+ # gem's own CI, so #run always returns normally (the rake task exits 0).
13
+ # The one hard rule: an unreadable spec prints "drift check unavailable"
14
+ # and never a false "no drift" claim.
15
+ module Drift
16
+ module_function
17
+
18
+ # Prints a drift report to `out`. Returns the findings array, or nil when
19
+ # the check could not run at all.
20
+ def run(pinned_path:, newer_path:, out: $stdout)
21
+ newer = read_spec(newer_path)
22
+ if newer.nil?
23
+ out.puts "drift check unavailable: could not read newer spec at #{newer_path.inspect}"
24
+ return nil
25
+ end
26
+
27
+ pinned = read_spec(pinned_path)
28
+ if pinned.nil?
29
+ out.puts "drift check unavailable: could not read pinned spec at #{pinned_path.inspect}"
30
+ return nil
31
+ end
32
+
33
+ findings = diff(pinned, newer)
34
+ if findings.empty?
35
+ out.puts "No drift on the covered surface (#{Coverage::COVERED_ENDPOINTS.size} endpoints)."
36
+ else
37
+ out.puts "Drift detected on the covered surface (#{findings.size} finding(s) — report, not a failure):"
38
+ findings.each { |finding| out.puts " - #{finding}" }
39
+ end
40
+ findings
41
+ end
42
+
43
+ # Compares the two parsed specs over the covered endpoints only.
44
+ # Returns human-readable finding strings; uncovered endpoints (ramps,
45
+ # issuance, ...) never appear here no matter how much they change.
46
+ def diff(pinned, newer)
47
+ Coverage::COVERED_ENDPOINTS.flat_map do |endpoint|
48
+ label = "#{endpoint.method.upcase} #{endpoint.path}"
49
+ newer_operation = newer.dig("paths", endpoint.path, endpoint.method)
50
+ next [ "#{label}: endpoint missing from newer spec" ] unless newer_operation
51
+
52
+ response_findings(label, endpoint, pinned, newer) +
53
+ request_findings(label, endpoint, pinned, newer)
54
+ end
55
+ end
56
+
57
+ def read_spec(path)
58
+ JSON.parse(File.read(path.to_s))
59
+ rescue StandardError
60
+ nil
61
+ end
62
+
63
+ # For every schema node the gem reads, reports fields that disappeared
64
+ # (removed/renamed) and fields that became required (shape guarantees
65
+ # changed — e.g. the v0.28→v0.29 usdValue change on balances).
66
+ def response_findings(label, endpoint, pinned, newer)
67
+ pinned_schema = Coverage.success_schema(pinned, endpoint)
68
+ newer_schema = Coverage.success_schema(newer, endpoint)
69
+ return [ "#{label}: success response #{endpoint.success_status} missing from newer spec" ] unless newer_schema
70
+ return [] unless pinned_schema # nothing pinned to compare against
71
+
72
+ endpoint.reads.flat_map do |segments, _fields|
73
+ at = segments.empty? ? "response root" : "response #{segments.join('.')}"
74
+ pinned_node = Coverage.walk(pinned, pinned_schema, segments)
75
+ newer_node = Coverage.walk(newer, newer_schema, segments)
76
+ next [] unless pinned_node
77
+ next [ "#{label}: #{at} no longer present in newer spec" ] unless newer_node
78
+
79
+ findings = []
80
+ removed = properties(pinned_node) - properties(newer_node)
81
+ findings << "#{label}: #{at} removed/renamed field(s): #{removed.join(', ')}" unless removed.empty?
82
+
83
+ newly_required = required(newer_node) - required(pinned_node)
84
+ unless newly_required.empty?
85
+ findings << "#{label}: #{at} field(s) became required: #{newly_required.join(', ')}"
86
+ end
87
+ findings
88
+ end
89
+ end
90
+
91
+ # Reports request-body params that became required in the newer spec —
92
+ # existing gem calls would start failing with 400s.
93
+ def request_findings(label, endpoint, pinned, newer)
94
+ pinned_required = request_required(pinned, endpoint)
95
+ newer_required = request_required(newer, endpoint)
96
+
97
+ added = newer_required - pinned_required
98
+ return [] if added.empty?
99
+
100
+ [ "#{label}: request body added required param(s): #{added.join(', ')}" ]
101
+ end
102
+
103
+ def request_required(spec, endpoint)
104
+ schema = spec.dig("paths", endpoint.path, endpoint.method,
105
+ "requestBody", "content", "application/json", "schema")
106
+ required(Coverage.resolve(spec, schema))
107
+ end
108
+
109
+ def properties(node)
110
+ props = node.is_a?(Hash) ? node["properties"] : nil
111
+ props.is_a?(Hash) ? props.keys : []
112
+ end
113
+
114
+ def required(node)
115
+ req = node.is_a?(Hash) ? node["required"] : nil
116
+ req.is_a?(Array) ? req : []
117
+ end
118
+ end
119
+ end
data/lib/sdp/errors.rb ADDED
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sdp
4
+ # Base class for every error raised by Sdp::Client.
5
+ #
6
+ # SDP's uniform error shape is:
7
+ # { "error": { "code": "...", "message": "...", "details": ... }, "meta": { ... } }
8
+ #
9
+ # The upstream message is preserved as the exception message; the upstream
10
+ # code, HTTP status, details, and meta ride along for logging/branching.
11
+ class Error < StandardError
12
+ attr_reader :code, :http_status, :details, :meta
13
+
14
+ def initialize(message = nil, code: nil, http_status: nil, details: nil, meta: nil)
15
+ super(message)
16
+ @code = code
17
+ @http_status = http_status
18
+ @details = details
19
+ @meta = meta
20
+ end
21
+ end
22
+
23
+ # Raised at construction/boot when SDP_API_KEY (or base URL) is unusable.
24
+ class ConfigurationError < Error; end
25
+
26
+ # 400 / BAD_REQUEST / VALIDATION_ERROR — the request itself is wrong.
27
+ class BadRequest < Error; end
28
+
29
+ # A request the configured custody provider cannot serve — not a malformed
30
+ # request. Raised for the FL-10 gates:
31
+ #
32
+ # - 400 whose message matches PROVISIONING_GATE_PATTERN: local custody
33
+ # holds exactly one root wallet, so POST /v1/wallets is rejected.
34
+ # Wallet-per-User requires a managed provider (e.g. privy).
35
+ # - 409 on POST /v1/wallets/initialize: custody is already initialized for
36
+ # this organization/project — initialization is one-time.
37
+ #
38
+ # Subclasses BadRequest so existing rescues keep working; never retryable —
39
+ # the same request fails until the provider configuration changes.
40
+ class ProviderCapabilityError < BadRequest
41
+ # Verified against SDP v0.28: assertCustodyProviderCanCreateWallet
42
+ # (apps/sdp-api/src/services/custody-provider-lifecycle.service.ts) and
43
+ # createProviderWallet (services/domain/signing/provider-wallet-lifecycle.ts)
44
+ # both throw:
45
+ # "Wallet provisioning not supported for provider: ${provider}"
46
+ PROVISIONING_GATE_PATTERN = /Wallet provisioning not supported/i
47
+ end
48
+
49
+ # 502 / SOLANA_RPC_ERROR carrying the NativeAdapter signature — the FL-11
50
+ # gate. With FEE_PAYMENT_PROVIDER=native, SDP can build and sign transfers
51
+ # but cannot SUBMIT them; the fix is configuration (run Kora, set
52
+ # FEE_PAYMENT_PROVIDER=kora), so retrying is pointless. A 502 that does
53
+ # NOT match the pattern is a real upstream outage and stays Unavailable —
54
+ # mislabeling an RPC outage as "configure Kora" would be worse than a
55
+ # generic error.
56
+ class TransferExecutionError < Error
57
+ # Verified against SDP v0.28: NativeAdapter#signAndSend
58
+ # (apps/sdp-api/src/services/adapters/fee-payment/native/native.adapter.ts)
59
+ # throws:
60
+ # "NativeAdapter.signAndSend not supported - use KoraAdapter for gasless transactions"
61
+ # (#signAsFeePayer throws the same shape with its own method name).
62
+ NATIVE_ADAPTER_PATTERN = /NativeAdapter\.\w+ not supported - use KoraAdapter/
63
+ end
64
+
65
+ # 401 / UNAUTHORIZED — key missing, malformed, or revoked.
66
+ class Unauthorized < Error; end
67
+
68
+ # 403 / FORBIDDEN — authenticated but not allowed.
69
+ class Forbidden < Error; end
70
+
71
+ # 403 / INSUFFICIENT_PERMISSIONS — key lacks the required scope.
72
+ class InsufficientPermissions < Forbidden; end
73
+
74
+ # 404 / NOT_FOUND — wallet or transfer does not exist. Beware: wallet-scoped
75
+ # API keys return 404 (not 403) for wallets outside their scope.
76
+ class NotFound < Error; end
77
+
78
+ # 409 / CONFLICT — the resource already exists or is in a conflicting state
79
+ # (e.g. initializing a project wallet twice).
80
+ class Conflict < Error; end
81
+
82
+ # HTTP 202 / SIGNING_PENDING — the request was accepted but the transaction
83
+ # is awaiting additional signatures (multisig/approval flows). NOT a
84
+ # success: there is no data envelope, only an error-shaped body. Carries
85
+ # code/http_status/details so callers can surface approval progress.
86
+ class SigningPending < Error; end
87
+
88
+ # TRANSACTION_FAILED — the on-chain transaction was attempted and failed
89
+ # (e.g. insufficient lamports). Never blindly retried: outcome semantics
90
+ # differ from transport errors.
91
+ class TransactionFailed < Error; end
92
+
93
+ # 429 / RATE_LIMITED.
94
+ class RateLimited < Error; end
95
+
96
+ # Net::ReadTimeout. For POSTs the outcome is UNKNOWN — callers must
97
+ # reconcile before re-submitting (no idempotency key upstream; retrying a
98
+ # transfer risks a double-spend).
99
+ class Timeout < Error; end
100
+
101
+ # Connection refused/reset, connect timeout, or a 5xx without SDP's error
102
+ # shape. The request was never processed, so it is safe to retry.
103
+ class Unavailable < Error; end
104
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sdp
4
+ # Lazy enumeration over SDP list endpoints.
5
+ #
6
+ # Two modes, keyed on whether the caller pinned a page:
7
+ #
8
+ # - No :page in the query — auto-paginate. The enumerator fetches the first
9
+ # page on first consumption and follows meta.hasMore, requesting the next
10
+ # page only when iteration runs past the rows already fetched (so
11
+ # `enum.take(3)` against a 20-row first page performs exactly one
12
+ # request). Filters are re-sent on every page request.
13
+ # - Explicit :page — single page. The enumerator yields exactly that page's
14
+ # rows and never fetches another, even when meta.hasMore is true.
15
+ #
16
+ # :pageSize is clamped client-side to MAX_PAGE_SIZE — SDP rejects larger
17
+ # values, and a clamped request is more useful than a guaranteed 400.
18
+ #
19
+ # Non-paginated list endpoints (GET /v1/wallets at v0.28) flow through the
20
+ # same helper: their meta carries no hasMore, so enumeration stops after a
21
+ # single fetch — and they pick up auto-pagination for free if SDP paginates
22
+ # them in a later version.
23
+ module Pagination
24
+ MAX_PAGE_SIZE = 100 # SDP's pageSize ceiling (v0.28)
25
+ MAX_PAGES = 10_000 # defensive ceiling; empty-page + hasMore guards are the primary stop
26
+
27
+ # client — anything exposing #get(path, query:) → Client::Response
28
+ # query — wire-shaped (camelCase keys), nils allowed (compacted here)
29
+ # mapper — called once per page with the Response; returns that page's rows
30
+ def self.enumerate(client, path, query = {}, &mapper)
31
+ query = query.compact
32
+ query[:pageSize] = [ query[:pageSize].to_i, MAX_PAGE_SIZE ].min if query.key?(:pageSize)
33
+ single_page = query.key?(:page)
34
+
35
+ Enumerator.new do |yielder|
36
+ page = query[:page]
37
+ loop do
38
+ request_query = page ? query.merge(page: page) : query
39
+ response = client.get(path, query: request_query)
40
+ rows = mapper.call(response)
41
+ rows.each { |row| yielder << row }
42
+
43
+ break if single_page
44
+
45
+ meta = response.meta || {}
46
+ # An empty page also stops: hasMore with zero rows would loop forever.
47
+ break if rows.empty? || !meta[:has_more]
48
+
49
+ # Advance a LOCAL counter the client owns; ignore meta[:page] so a
50
+ # server that echoes the wrong page number cannot cause an infinite
51
+ # loop or a TypeError (string "1" + 1).
52
+ page = (page || 1) + 1
53
+ break if page > MAX_PAGES
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Sdp
6
+ # A transfer as SDP reports it. SDP omits optional fields entirely —
7
+ # source/destination/amount/memo can be ABSENT from the JSON, not null —
8
+ # so every member is nil when SDP didn't send it.
9
+ Transfer = Struct.new(:id, :direction, :status, :signature, :token, :amount,
10
+ :source, :destination, :memo, :error, :created_at,
11
+ keyword_init: true) do
12
+ def self.from_hash(hash)
13
+ hash ||= {}
14
+ new(
15
+ id: hash[:id],
16
+ direction: hash[:direction],
17
+ status: hash[:status],
18
+ signature: hash[:signature],
19
+ token: hash[:token],
20
+ amount: hash[:amount],
21
+ source: hash[:source],
22
+ destination: hash[:destination],
23
+ memo: hash[:memo],
24
+ error: hash[:error],
25
+ created_at: hash[:created_at]
26
+ )
27
+ end
28
+ end
29
+
30
+ # Result of POST /v1/payments/transfers/prepare: the provisional transfer
31
+ # plus the unsigned transaction the caller must sign and submit before
32
+ # blockhash expiry. simulation is SDP's simulation result passed through
33
+ # as a hash when present.
34
+ PreparedTransfer = Struct.new(:transfer, :serialized, :blockhash, :last_valid_block_height, :simulation,
35
+ keyword_init: true) do
36
+ def self.from_hash(hash)
37
+ hash ||= {}
38
+ prepared = hash[:prepared_transaction] || {}
39
+ new(
40
+ transfer: Transfer.from_hash(hash[:transfer]),
41
+ serialized: prepared[:serialized],
42
+ blockhash: prepared[:blockhash],
43
+ last_valid_block_height: prepared[:last_valid_block_height],
44
+ simulation: hash[:simulation]
45
+ )
46
+ end
47
+ end
48
+
49
+ module Resources
50
+ # Payment endpoints: transfer create/prepare/list/get.
51
+ module Payments
52
+ # POST /v1/payments/transfers → Sdp::Transfer
53
+ # Synchronous sign-and-send: SDP confirms before responding, and the
54
+ # request is NEVER retried (no idempotency key upstream — see Client
55
+ # docs). amount is serialized as a decimal string; token is "SOL" or
56
+ # an SPL mint address.
57
+ def create_transfer(source:, destination:, amount:, token: "SOL", memo: nil)
58
+ response = post("/v1/payments/transfers", transfer_payload(source, destination, amount, token, memo))
59
+ data = response.data
60
+ src = data.is_a?(Hash) ? (data[:transfer] || data) : data
61
+ Transfer.from_hash(src)
62
+ end
63
+
64
+ # POST /v1/payments/transfers/prepare → Sdp::PreparedTransfer
65
+ # Builds — but does not sign or send — the transaction, for
66
+ # non-custodial flows where the caller holds the keys.
67
+ def prepare_transfer(source:, destination:, amount:, token: "SOL", memo: nil,
68
+ reference_address: nil, options: nil)
69
+ payload = transfer_payload(source, destination, amount, token, memo)
70
+ payload[:referenceAddress] = reference_address if reference_address
71
+ payload[:options] = options if options
72
+ PreparedTransfer.from_hash(post("/v1/payments/transfers/prepare", payload).data)
73
+ end
74
+
75
+ # GET /v1/payments/transfers → Enumerator yielding Sdp::Transfer
76
+ #
77
+ # Auto-paginates: without page:, the returned lazy enumerator follows
78
+ # meta.hasMore across pages, fetching each page only when iteration
79
+ # reaches it and re-sending the filters every time. With an explicit
80
+ # page:, it yields exactly that page and never fetches another.
81
+ # page_size is clamped to Pagination::MAX_PAGE_SIZE (100).
82
+ #
83
+ # Filters: wallet: (walletId), wallet_address:, token:, direction:
84
+ # ("inbound"/"outbound"), status: (string or array, sent
85
+ # comma-separated), page:, page_size:.
86
+ def list_transfers(wallet: nil, wallet_address: nil, token: nil, direction: nil,
87
+ status: nil, page: nil, page_size: nil)
88
+ query = {
89
+ wallet: wallet,
90
+ walletAddress: wallet_address,
91
+ token: token,
92
+ direction: direction,
93
+ status: status && Array(status).join(","),
94
+ page: page,
95
+ pageSize: page_size
96
+ }.compact
97
+ Pagination.enumerate(self, "/v1/payments/transfers", query) do |response|
98
+ rows = response.data.is_a?(Array) ? response.data : []
99
+ rows.map { |transfer| Transfer.from_hash(transfer) }
100
+ end
101
+ end
102
+
103
+ # GET /v1/payments/transfers/:id → Sdp::Transfer
104
+ def get_transfer(transfer_id)
105
+ response = get("/v1/payments/transfers/#{encode_path_segment(transfer_id)}")
106
+ data = response.data
107
+ src = data.is_a?(Hash) ? (data[:transfer] || data) : data
108
+ Transfer.from_hash(src)
109
+ end
110
+
111
+ private
112
+
113
+ def transfer_payload(source, destination, amount, token, memo)
114
+ payload = { source: source, destination: destination, token: token, amount: amount.to_s }
115
+ payload[:memo] = memo if memo
116
+ payload
117
+ end
118
+
119
+ def encode_path_segment(segment)
120
+ URI.encode_uri_component(segment.to_s)
121
+ end
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Sdp
6
+ # Token balance row from GET /v1/payments/wallets/:id/balances.
7
+ # amount is base units (string); ui_amount is the decimal string.
8
+ # usd_value is passed through when SDP includes it and is nil otherwise
9
+ # (varies across SDP versions) — nil means "no price", never zero.
10
+ Balance = Struct.new(:token, :mint, :amount, :ui_amount, :decimals, :usd_value, keyword_init: true) do
11
+ def self.from_hash(hash)
12
+ hash ||= {}
13
+ new(
14
+ token: hash[:token],
15
+ mint: hash[:mint],
16
+ amount: hash[:amount],
17
+ ui_amount: hash[:ui_amount],
18
+ decimals: hash[:decimals],
19
+ usd_value: hash[:usd_value]
20
+ )
21
+ end
22
+ end
23
+
24
+ # Custody wallet. #id is SDP's walletId — the identifier the payments API
25
+ # expects — not the database row id. balances is only populated when the
26
+ # list was fetched with include_balances: true.
27
+ Wallet = Struct.new(:id, :public_key, :label, :status, :provider, :purpose, :created_at, :balances,
28
+ keyword_init: true) do
29
+ def self.from_hash(hash)
30
+ hash ||= {}
31
+ new(
32
+ id: hash[:wallet_id] || hash[:id],
33
+ public_key: hash[:public_key],
34
+ label: hash[:label],
35
+ status: hash[:status],
36
+ provider: hash[:provider],
37
+ purpose: hash[:purpose],
38
+ created_at: hash[:created_at],
39
+ balances: hash[:balances]&.map { |balance| Balance.from_hash(balance) }
40
+ )
41
+ end
42
+ end
43
+
44
+ module Resources
45
+ # Wallet endpoints: custody initialize, create, list, plus the balances
46
+ # read (which lives under /v1/payments but is wallet-shaped).
47
+ module Wallets
48
+ # POST /v1/wallets/initialize — one-time project custody setup.
49
+ # Both fields are optional; the request is sent without a body when
50
+ # neither is given. Returns the snake_cased data hash exactly as SDP
51
+ # sent it (custody config + root wallet fields incl. :public_key) —
52
+ # kept tolerant because the shape varies by custody provider.
53
+ def initialize_custody(provider: nil, wallet_label: nil)
54
+ payload = { provider: provider, walletLabel: wallet_label }.compact
55
+ post("/v1/wallets/initialize", payload.empty? ? nil : payload).data
56
+ end
57
+
58
+ # POST /v1/wallets → Sdp::Wallet. Wallet#id is SDP's walletId.
59
+ def create_wallet(label:, provider: nil)
60
+ response = post("/v1/wallets", { label: label, provider: provider }.compact)
61
+ data = response.data
62
+ src = data.is_a?(Hash) ? (data[:wallet] || data) : data
63
+ Wallet.from_hash(src)
64
+ end
65
+
66
+ # GET /v1/wallets → [Sdp::Wallet, ...]
67
+ # Filters (camelCased on the wire): provider:, project_id:,
68
+ # include_balances:. Not paginated at v0.28 — the whole list comes back
69
+ # in one response — but routed through Pagination.enumerate so a
70
+ # paginated upstream upgrade is a one-line change here.
71
+ def list_wallets(provider: nil, project_id: nil, include_balances: nil)
72
+ query = { provider: provider, projectId: project_id, includeBalances: include_balances }.compact
73
+ Pagination.enumerate(self, "/v1/wallets", query) do |response|
74
+ rows =
75
+ case response.data
76
+ when Array then response.data
77
+ when Hash then response.data[:wallets] || []
78
+ else []
79
+ end
80
+ rows.map { |wallet| Wallet.from_hash(wallet) }
81
+ end.to_a
82
+ end
83
+
84
+ # GET /v1/payments/wallets/:id/balances → [Sdp::Balance, ...]
85
+ # Upstream swallows RPC failures, so a token row (even SOL) may be
86
+ # MISSING entirely — a missing row means "unavailable", never zero.
87
+ def wallet_balances(wallet_id)
88
+ data = get("/v1/payments/wallets/#{encode_path_segment(wallet_id)}/balances").data
89
+ container = data.is_a?(Hash) ? (data[:wallet_balances] || data) : {}
90
+ (container[:balances] || []).map { |balance| Balance.from_hash(balance) }
91
+ end
92
+
93
+ private
94
+
95
+ def encode_path_segment(segment)
96
+ URI.encode_uri_component(segment.to_s)
97
+ end
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sdp
4
+ VERSION = "0.1.0"
5
+
6
+ # The SDP release this gem version is tested against. SDP breaks its API
7
+ # between minors, so every gem release names its verified upstream version.
8
+ COMPATIBLE_SDP_VERSION = "0.28"
9
+ end
data/lib/sdp.rb ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "sdp/version"
4
+ require_relative "sdp/errors"
5
+ require_relative "sdp/client"
6
+ require_relative "sdp/coverage"
7
+
8
+ # Ruby client for the Solana Developer Platform (SDP).
9
+ module Sdp
10
+ end
data/lib/solana-sdp.rb ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Entry point matching the gem name: `require "solana-sdp"`.
4
+ require_relative "sdp"
metadata ADDED
@@ -0,0 +1,58 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: solana-sdp
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jose Ferrer
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-06-13 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: 'Zero-dependency Net::HTTP client for SDP''s wallets and payments API:
14
+ typed errors, envelope unwrapping, and a safe retry posture.'
15
+ email:
16
+ - estoy@moviendo.me
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - LICENSE.txt
22
+ - README.md
23
+ - lib/sdp.rb
24
+ - lib/sdp/client.rb
25
+ - lib/sdp/coverage.rb
26
+ - lib/sdp/drift.rb
27
+ - lib/sdp/errors.rb
28
+ - lib/sdp/pagination.rb
29
+ - lib/sdp/resources/payments.rb
30
+ - lib/sdp/resources/wallets.rb
31
+ - lib/sdp/version.rb
32
+ - lib/solana-sdp.rb
33
+ homepage: https://github.com/solrengine/solana-sdp
34
+ licenses:
35
+ - MIT
36
+ metadata:
37
+ homepage_uri: https://github.com/solrengine/solana-sdp
38
+ source_code_uri: https://github.com/solrengine/solana-sdp
39
+ post_install_message:
40
+ rdoc_options: []
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: 3.2.0
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '0'
53
+ requirements: []
54
+ rubygems_version: 3.5.22
55
+ signing_key:
56
+ specification_version: 4
57
+ summary: Ruby client for the Solana Developer Platform (SDP)
58
+ test_files: []