SolanaStudio
Ruby primitives for building on Solana — JSON-RPC client, Ed25519 keypairs, Borsh serialization, and transaction builder with PDA derivation.
Part of the McRitchie ecosystem — see
ECOSYSTEM.mdfor the 5-repo map;house-burn-down.mdfor fresh-Mac recovery.
Installation
# Gemfile
gem "solana-studio", "~> 0.5"Consumer apps use the RubyGems release. Use a local path only while actively developing the gem, and restore the RubyGems dependency before merging.
Usage
Keypair
require "solana-studio"
# Generate a new keypair
kp = Solana::Keypair.generate
kp.address # => "9Fy8P3DvKBh3awt1wr27g4CDh47oDqmJR2FAAQ1bc69D"
kp.to_bytes # => 64-byte Solana format
# Load from file or env
kp = Solana::Keypair.from_json_file("~/.config/solana/id.json")
kp = Solana::Keypair.from_base58(ENV["SOLANA_ADMIN_KEY"])
# Sign a message
signature = kp.sign("hello".b)Client (JSON-RPC)
client = Solana::Client.new(rpc_url: "https://api.devnet.solana.com")
client.get_balance("9Fy8P3DvKBh3awt...")
client.get_latest_blockhash # hash only, "finalized"
client.latest_blockhash # hash + last_valid_block_height, "confirmed"
client.get_block_height # compare against last_valid_block_height
client.send_transaction(wire_b64, preflight_commitment: "confirmed") # match the fetch
client.request_airdrop("9Fy8P3DvKBh3awt...", 1_000_000_000)
client.send_and_confirm(signed_tx_base64)Borsh Serialization
data = Solana::Borsh.encode_u64(1_000_000) +
Solana::Borsh.encode_string("hello") +
Solana::Borsh.encode_pubkey(kp.public_key_bytes)Transaction Builder
tx = Solana::Transaction.new
tx.set_recent_blockhash(client.get_latest_blockhash)
tx.add_signer(keypair)
tx.add_instruction(
program_id: "YourProgramId...",
accounts: [
{ pubkey: keypair.public_key_bytes, is_signer: true, is_writable: true },
{ pubkey: pda, is_signer: false, is_writable: true }
],
data: Solana::Transaction.anchor_discriminator("your_instruction") + payload
)
signature = client.send_and_confirm(tx.serialize_base64)PDA Derivation
pda, bump = Solana::Transaction.find_pda(
["vault".b, wallet_pubkey_bytes],
program_id_bytes
)Network (cluster identity)
A Solana cluster has three names that must agree, and nothing in the protocol
makes them agree for you: the operator's name (devnet), the chain's own
fingerprint (its genesis hash), and the wallet's name (solana:devnet).
Solana::Network is the lookup table that relates them.
Solana::Network.genesis_hash("devnet") # => "EtWTRABZaYq6..."
Solana::Network.cluster_for_genesis(hash) # => "mainnet-beta" (what an RPC ACTUALLY is)
Solana::Network.wallet_standard_chain("mainnet-beta") # => "solana:mainnet" (note: no -beta)
Solana::Network.canonical("mainnet") # => "mainnet-beta"; nil if unrecognized
Solana::Network.expected_for_environment("qa") # => "devnet"Alignment has three outcomes, and collapsing the middle one is a bug:
Solana::Network.alignment(cluster: "devnet", genesis_hash: live_hash)
# => :aligned | :mismatched | :unverifiable:unverifiable means there was no pinned hash to compare — localnet (whose
genesis is minted per boot) or an unrecognized cluster name. Treating it as
:mismatched refuses to boot every local validator; treating it as :aligned
trusts a chain nobody checked.
Gasless cosigned transactions (Solana::Cosign)
The pattern every app with a house wallet needs: the user's wallet signs, the house pays the fee, so users never hold SOL. The server builds the transaction with its fee payer in account 0 and an empty slot for each cosigner, the wallet signs, and the server proves the returned wire is still what it built before it adds its own signature.
The gem holds no keys and knows no program. The caller passes the fee payer's
Solana::Keypair in and supplies its own instructions.
client = Solana::Client.new
builder = Solana::Cosign::Builder.new(client: client, fee_payer: house_keypair)
prepared = builder.build(
instructions: [my_program_instruction], # { program_id:, accounts:, data: }
cosigners: [user_wallet_address],
compute_unit_price: 50_000, # a priority fee; fee-less txs drop on mainnet
compute_unit_limit: 200_000
)
prepared.wire_base64 # hand this to the wallet
prepared.wire_base58 # or this: what a walletOps `prepare` returns
prepared.last_valid_block_height # the deadline: past this height it can never landStore prepared.wire_base64 and prepared.last_valid_block_height server-side
when the signature comes back in a later request, then:
expectation = Solana::Cosign::Expectation.from_wire(stored_wire, fee_payer: house_keypair,
last_valid_block_height: stored_height)
completer = Solana::Cosign::Completer.new(client: client, fee_payer: house_keypair)
result = completer.complete(signed_wire_from_wallet, expectation: expectation,
before_send: ->(signature) { record.update!(signature: signature) })
result.signatureA wire from SolanaStudio.walletOps arrives in base58: pass encoding: :base58
to #verify!, #cosign, #complete or Expectation.from_wire. The encoding is
declared, never guessed — every base58 string is also made of base64 characters.
#complete runs, in order: judge the wire, check every cosigner signature, fill
the fee payer's slot (Transaction.cosign_wire), check the block height against
the deadline, simulate, call before_send, send, confirm. #cosign stops after
the fee payer signs (no RPC), for a flow whose browser broadcasts. #verify!
only judges.
How the wire is judged. A wallet re-encodes what it signs, and on mainnet Phantom may insert Lighthouse instructions, so bytes are never compared. The fee payer must be account 0 and writable; the signer set must be exactly the fee payer plus the cosigners; with ComputeBudget and admitted extra programs (Lighthouse by default) set aside, the instructions must equal the built ones — program, ordered accounts, data and order; ComputeBudget is read and the fee it makes the house pay is capped at 10x the builder's own. A System transfer from the fee payer, a nonce advance, an extra signer, an altered amount: each is refused before the house signs.
Lighthouse is read, not waved through. Most Lighthouse instructions are
assertions, which can only make a transaction fail. Two are not. MemoryWrite
(variant 0) makes a signer fund a "memory" account of any size, and the fee
payer signs every cosigned wire, so a wire naming it as payer would lock the
house's SOL. MemoryClose (variant 1) refunds one. The guard therefore admits a
Lighthouse instruction only when its first data byte is an assertion variant,
2 through 17. It refuses 0 (lighthouse_memory_write), 1
(lighthouse_memory_close), empty data (lighthouse_empty_data) and any other
byte (lighthouse_unknown_disc). It does not refuse an assertion for naming
the fee payer, because Phantom's assertions check the fee payer's own state.
The deployed program is immutable, so the variants cannot drift; the mainnet
evidence is in the Solana::Cosign::LIGHTHOUSE_PROGRAM_ID comment.
extra_programs: accepts only programs the guard has such a rule for, which
today is Lighthouse alone; pass extra_programs: [] to refuse Lighthouse
entirely.
The error class tells you what you may do next.
| Raised | Sent? | What to do |
|---|---|---|
WireRejected |
No | Refuse. #reason is a stable code; the message is for logs only. |
PreflightRejected → BlockhashExpired, SimulationFailed
|
Provably not | Rebuild freely. BlockhashExpired means ask the user to sign again. |
BroadcastFailed → BroadcastExpired
|
Maybe | Look #signature up on chain before rebuilding. |
TransactionFailed |
Landed, failed | The fee was paid. #err has the program error. |
BroadcastExpired is deliberately NOT a PreflightRejected: Solana::Client
retries a lost answer by re-posting the same wire, so a send-time "Blockhash not
found" can follow an attempt that was already forwarded.
Build and send at the same commitment. The builder fetches at "confirmed"
by default and the completer preflights at the commitment the expectation
carries. A confirmed blockhash sent with the RPC's default "finalized"
preflight is refused as Blockhash not found while still valid.
Wallet-first by default. Every slot starts empty and the house signs last.
presign: true signs the fee payer's slot at build instead — the order Phantom
can flag as "could be malicious" — and exists only so server-first flows can
adopt the builder before they flip.
No durable nonce: a nonce transaction is recognized only when
advanceNonceAccount is instruction 0, and Phantom inserts instructions ahead of
it, so a nonce cannot anchor a wallet-signed transaction.
Rails engine (optional)
The gem is Rails-free by default — railties is not a runtime dependency,
and plain-Ruby consumers (scripts, rake tasks, chain-ops) never load a line of
it. When the gem is required inside a Rails process, SolanaStudio::Engine
defines itself and contributes the onchain UI primitives.
Network mismatch guard
The problem: a user whose wallet is set to Mainnet, using a QA app that runs on Devnet. Their wallet simulates against the wrong chain, shows a frightening approval sheet and a balance from a chain nobody is using, and they abandon the flow.
A website cannot detect this directly. Phantom does not expose its selected
network, and the Wallet Standard chains array lists what a wallet supports,
not what it has selected. There is no pre-flight read to write. So the guard
does the only two things that work:
1. Assert at sign-in. Hand the wallet a SIWS chainId and let it contradict
you — the one pre-emptive signal that exists.
var signInInput = SolanaStudio.network.withSignInChainId({
domain: window.location.host,
nonce: nonce
});
// => adds chainId: "solana:devnet"2. Explain after a failure. Wrap any onchain action. The guard never blocks and never swallows an error — it re-throws the original rejection untouched, and hands you a hint only when a mismatch would actually explain the failure.
SolanaStudio.network.guard(
function() { return provider.signTransaction(tx); },
{
action: "Entering this contest",
onHint: function(hint) { Alpine.store('modals').open('network-mismatch', hint); }
}
).then(broadcast); // your existing .catch still receives the real errorclassify(err) returns "likely", "possible", or "unrelated", and is
calibrated to under-claim: an insufficient-funds error stays an
insufficient-funds error. Dressing up an unrelated failure as a network problem
sends the user to fix the wrong thing, which is the bug this feature exists to
remove.
Host setup
<%# once, inside your modal host %>
<template x-if="$store.modals.current().id === 'network-mismatch'">
<%= render "solana_studio/modals/network_mismatch" %>
</template><%# so the browser can read what the server knows %>
<body data-solana-network="<%= Solana::Network.describe(
Solana::Config::NETWORK, environment: Rails.env).to_json %>">The guard falls back to discrete data-solana-cluster / data-app-environment
attributes, so a host can adopt it before changing its layout.
Requires studio-engine's modal host (Alpine.store('modals')) and its shared
modal blocks. The JS is solana_studio/network_guard.js on the asset path.
Wallet sign-in button (the credential slot)
studio-engine owns the sign-in modal, because every app in the ecosystem signs people in and most of them are web2. This gem owns the wallet button inside it, because only a web3 app has wallets.
There is nothing to wire up, on studio-engine 0.68.0 or newer. The engine's auth modal looks for a partial at one fixed path and renders whatever it finds:
solana_studio/auth/_wallet_credential
Bundling this gem puts that partial on the host's view path, so the button
appears. An app that does not bundle it finds nothing and renders nothing — no
wallet markup ships to a newsletter app, and no render call has to be deleted
to keep it out.
The studio-engine floor: 0.68.0
0.68.0 is the first studio-engine that performs the lookup. Until it, the
engine's style/modals/_auth drew the Solana button itself, inline, and never
consulted solana_studio/auth/wallet_credential at all — this gem shipped the
partial, its tests and this section for a button no host rendered. 0.68.0
deleted that inline copy and put the lookup in its place, which is what made the
paragraph above true.
Below the floor the partial is inert, and nothing says so. It sits on the
view path and is never asked for: no render runs, no button comes from it, and
no error reaches the page or the log. A host that edits the partial and sees the
modal unchanged should suspect the engine version first — that silence, not a
stack trace, is the symptom.
Derived by unpacking the published gems rather than reading a changelog: 0.67.2
contains no reference to solana_studio/auth anywhere in app/, and 0.68.0
gates the render on lookup_context.exists?("wallet_credential", ["solana_studio/auth"], true). Match on the namespace, not the basename —
style/modals/_wallet_connect ships unchanged in both releases and answers an
unrelated question.
The two gems set the floor together, and the pair matters more than either
number. Every row below also assumes the host has wallet sign-in configured
on — Studio.auth_method?(:wallet) and Studio.feature?(:web3), the two
questions in the table further down. McRitchie Studio leaves them off, so it
shows no wallet button on any pair of versions:
| studio-engine | this gem | The sign-in modal shows, wallet configured on |
|---|---|---|
| 0.67.2, the last release below the floor | 0.5.3+ | the engine's own inline button; this gem's partial renders nowhere |
| 0.68.0+ | 0.5.3+ | this gem's partial — the arrangement described above |
| either side of the floor | 0.5.2 | no wallet button, silently — see below |
| either side of the floor | not bundled | no wallet button, correctly — a web2 app ships no wallet markup |
0.5.2 is the trap. It shipped solana_studio/auth/_wallet_credential
without solana_studio/modals/_wallet_connect, and both engines gate the
button on that picker resolving (the engine's web3_gem gate), so the credential
partial is present, correct, and suppressed either side of the floor. 0.5.3 is
the first version of this gem shipping both paths, and so the first that can
draw the button at all.
The engine asks two questions and needs both answered yes:
| Question | Answered by | Where |
|---|---|---|
| Does this app want wallet sign-in? |
Studio.auth_method?(:wallet) and Studio.feature?(:web3)
|
the host's config/initializers/studio.rb
|
| Is there a layer that implements it? | this partial resolving on the view path | bundling this gem |
Both matter. McRitchie Studio bundles this gem for the Ruby signing primitives
while shipping web3 off, so the partial is present and the button is
correctly absent. And an app that declares :wallet but forgets the gem gets no
button rather than a missing-partial error in front of someone signing in.
The partial renders inside the modal's own Alpine scope and borrows three
members from it — attested() for the legal-age gate, props.submitting for
the disabled state, and methodOn('wallet') for visibility.
Only the first two are required. methodOn is called behind a typeof test, so
a host that never defined it shows the button rather than hiding it. A bare
call in a host without the member throws, Alpine grades the throw as falsy, and
the button silently never renders — no error a user can see, nothing in the
page to debug. Bundling the gem has already answered is wallet implemented; a
host with no toggle has expressed no opinion about showing it, and the answer to
no opinion is yes. The test stays in Alpine deliberately: Ruby decides whether
this partial exists, Alpine decides whether it shows, and folding the visibility
into Ruby brings back a floating divider on a toggle page.
Locals
| Local | Required | What it does |
|---|---|---|
modal_store |
yes | Alpine store name backing the modal. The engine's real host passes "modals", the living style guide passes "dsModals". No default on purpose: a wrong store name fails as a dead button rather than an error, so missing beats wrong. |
on_click |
no | Alpine expression run once the age gate passes. Defaults to swapping straight to the wallet-connect picker. Parenthesised before it is emitted, so any expression is safe to pass. |
on_click replaces what happens after attested() — never attested()
itself, which stays template text no local can reach. A seam carrying the whole
handler could drop the legal-age gate by simply never calling it, and the button
would look and behave completely normal.
Keeping the gate out of the local guarantees it is called. Making it
control what follows took one more step, because the two land side by side
in a single JavaScript expression and precedence, not the template, decides
which wins. && binds tighter than ||, ?: and comma, so an override built
on any of those would reparse and run its tail with the gate false. The
override is therefore wrapped in parentheses before it is emitted, and you do
not need to bracket it yourself. Measured in Chromium against studio-engine's
vendored Alpine 3.16.1, both directions: with the gate false nothing runs, with
the gate true the whole override runs.
Pass it when the host has to do something before the picker navigates away. The
picker's redirect is unconditional, so a host holding unsaved state must write
it first. Turf Monster stages a contest lineup in localStorage, and adopting
the default would lose that lineup on wallet sign-in:
<%= render "solana_studio/auth/wallet_credential",
modal_store: "modals",
on_click: "openWalletHub()" %>The expression is emitted unescaped, because it is developer-authored code
exactly like the template around it. Keep it free of double quotes — one closes
the attribute early and Alpine mounts the button as a silent no-op — and keep it
an expression: a statement (let x = 1; foo()) or a trailing // comment
is a syntax error once Alpine wraps the handler, measured both before and after
this change.
What those constraints have in common is the point. Every one of them fails loudly — the button visibly does nothing. The precedence bug was the only one that failed silently, and it is the one this change removes.
Why a contributed button and not a second auth modal: Turf Monster wants Google plus magic-link plus wallet, McRitchie Studio wants Google plus magic-link. A forked modal would put a surface both apps sign in through into two files, which is how the wallet picker reached three copies before it was promoted.
Web3 modals
Four partials promoted out of studio-engine, where every consumer paid for them whether or not it shipped a chain feature at all:
| Virtual path | What it is |
|---|---|
solana_studio/modals/wallet_connect |
The Connect-Wallet picker — detected wallets, install rows, and Phantom's mobile deep-link row |
solana_studio/modals/web3_step_up |
The sign-with-your-wallet step-up card |
solana_studio/phantom_deeplink |
Defines window.startPhantomDeepLink(linkMode, currentUserId) — the phone round trip |
solana_studio/deeplink_assets |
An idempotent, non-blocking tweetnacl loader for that round trip |
<%# once, inside your modal host %>
<template x-if="$store.modals.current().id === 'wallet-connect'">
<%= render "solana_studio/modals/wallet_connect" %>
</template>
<template x-if="$store.modals.current().id === 'web3-step-up'">
<%= render "solana_studio/modals/web3_step_up" %>
</template>Render solana_studio/phantom_deeplink once, anywhere the Connect-Wallet
flow can be reached. The picker gates its mobile Phantom row on
startPhantomDeepLink existing, so a host that skips it keeps the install row
instead of painting a button that does nothing.
These require studio-engine at render time. They render its modal host and
its shared blocks (studio/modals/blocks/wallet_brand_sprite, .../card_header)
by name, paint with its utilities (badge, pulse-cta, spinner) and theme
role tokens, and drive its store through $store.<store>.swap(). studio-engine
stays a development dependency here — a runtime one would drag Rails into
every plain-Ruby consumer, which is what lib/solana_studio/engine.rb's guard
exists to prevent — so this is a documented host requirement, not something the
gem can enforce from inside. solana_studio/modals/network_mismatch already
shipped on exactly these terms.
The host JavaScript these modals reach for
Every global below belongs to the host. This gem ships no routes at all,
and the JavaScript it does ship is a different category from the globals below:
solana_studio/network_guard.js plus the redirect-transport primitives
(wallet_transport, redirect_provider, wallet_journal, wallet_ops — see
The wallet intent registry), none of
which provide any global in this table. So none of these can live here. Each is reached behind a typeof guard: an absent one degrades the
card rather than breaking it, and the whole point of writing the list down is
that a consumer meets it here instead of rediscovering it.
| Global | Needed by | Absent means |
|---|---|---|
window.solanaConnectAndVerify(name, opts) |
both | required — nothing can connect |
window.walletProvider |
both | required — no wallet rows paint |
window.handleSolanaVerifySuccess(result) |
both | no post-verify hook runs |
window.startPhantomDeepLink(linkMode, userId) |
picker | the mobile Phantom row is hidden |
parseSolanaError(msg) |
both | the wallet's raw words are shown unmapped |
window.reportWalletFailure(stage, provider, raw, mapped) |
both | this surface is dark |
reportWalletFailure, and why the endpoint is yours
Everything on the wallet surface fails client-side: the throw is caught, mapped, and painted into a paragraph. Without this call nothing about it exists outside the browser — which is how a user whose Phantom held no keypair was told to check their USDC balance seven times in one production session (2026-09-06) before an operator noticed by hand.
The gem calls it; it does not implement it. The reporter and its endpoint are
host-owned because they need an ErrorLog this gem cannot assume — the engine
here mounts no routes by design, so a gem-side reporter would POST at a path a
consumer is not guaranteed to have, and a report that 404s silently is strictly
worse than the silence it replaced: the surface still looks wired. Reference
implementation in turf-monster: app/javascript/solana_errors.js, receiving at
POST /auth/solana/report_failure.
The contract the call sites keep:
-
Called once per caught rejection, with the stage for that surface —
'wallet_connect'from the picker,'web3_step_up'from the step-up card. A stage the host does not recognise should be recorded, not refused; the report is still worth having. -
Both message halves, always.
rawis what the wallet said, captured before the mapper runs;mappedis what the user read. A mis-mapping is invisible in the mapped half alone, and that is the failure the 2026-09-06 incident actually was — a correct mapper meeting a string it had never seen. -
Skipped when the error is already tagged
walletFailureReported. Set that property on any error yoursolanaConnectAndVerifyrethrows after substituting a sentence of your own, and report it from in there, where the wallet's words still exist. Without the tag the same failure files a second row carrying your sentence in both halves — the useless row, and the one an operator meets first. - Fire and forget. The return value is ignored and a throw is swallowed. Do not rely on that: a reporter that throws is a bug, and the guard exists because an observer must never become the incident.
-
Four values, and only these four. No signature, no nonce, no signed SIWS
message — the modals never hold any of them, so none can leak.
rawis free text a wallet composed, so scrub it server-side: a wallet can quote your own nonce back at you inside a field your key allowlist has already approved. A pubkey is fine and should be kept; over-redaction blinds the tool.
The signed statement is not configurable
solana_studio/phantom_deeplink emits Studio.wallet_sign_in_statement, and it
must keep doing so. studio-engine's solana_sessions/phantom_callback
rebuilds the signed message to post for verification, so the two read one
accessor precisely so they cannot drift; a caller-supplied statement would break
the signature check on every mobile sign-in. test/web3_modals_test.rb pins
this from both directions.
Choosing between the loader and your own tag
solana_studio/deeplink_assets appends a script element, so it is
asynchronous. A callback that reads nacl at parse time will lose that race.
Adopt the loader only together with a callback that waits; otherwise keep a
blocking <script> tag of your own with the same SRI-pinned URL. turf-monster
deliberately does the latter.
The wallet intent registry (walletOps)
solana_studio/wallet_ops.js is how one piece of product logic — enter a
contest, rename a user, export a wallet — runs over both wallet transports
from one call site. The inline transport is an injected provider where
await works; the redirect transport hands off to a wallet app by URL and the
page is destroyed mid-operation. A flow is declared once, by name:
SolanaStudio.walletOps.define('contest_entry', {
prepare: function (ctx) { /* → { transaction: '<base58>', ...state } */ },
complete: function (ctx, result, state) { /* result.signedTransaction is base58 */ },
signOnly: true
});
SolanaStudio.walletOps.run('contest_entry', { contestId: 12 }, {
provider: walletProvider.detect(),
expectedAccount: session.address, // optional
owner: currentUser.id, // optional — see below
appUrl: location.origin, // redirect transport only
redirectLink: location.origin + '/auth/phantom/callback',
cluster: document.body.dataset.solanaCluster
});Handlers are registered by name at page load, never passed as closures: a closure is precisely what cannot survive the redirect. Everything the flow needs on the far side travels as JSON in the journal.
The transaction is base58 wire bytes, on every transport
prepare() must return { transaction: '<base58>' }, and complete() is
handed base58 in result.signedTransaction, whichever transport ran. A
transaction that is not a non-empty string is refused by name at the call site,
on both paths.
This is not a preference. Base58 is what survives a page death; a
solanaWeb3.Transaction serialises into a journal as {}. Until 0.9.1 only the
redirect path obeyed it — the inline path passed prepared.transaction straight
to provider.signTransaction, which for an injected wallet must be a Transaction
object — so a single intent could not serve both transports and every
consumer kept a second, hand-rolled desktop call site.
The inline provider's transaction codec
The gem cannot convert between the two shapes: deserializing base58 into a
Transaction needs @solana/web3.js, and the only JavaScript dependency here is
a guarded window.nacl. Taking web3.js would put a browser library on the
critical path of a gem whose other consumers are plain-Ruby, to do work your
wallet adapter already does.
So the conversion is the inline provider's, and it is required in both directions:
| Method | Given | Returns |
|---|---|---|
deserializeTransaction(base58) |
base58 wire bytes | whatever your signTransaction accepts |
serializeTransaction(signed) |
whatever signTransaction resolved |
base58 wire bytes |
Both are checked before the wallet is touched, and an inline provider missing
either is refused by name — a base58 string reaching an extension's
signTransaction throws t.serialize is not a function from inside someone
else's code, and a missing serializeTransaction would not surface until after
the user had already approved a signature.
The return leg is not garnish. Without serializeTransaction the redirect path
hands complete a base58 string and the inline path hands it a signed
Transaction object, your call site branches on which, and nothing has been
unified.
A reference adapter, for a co-signed transaction — the server fills a second
signer slot, so both serialize flags are off and a bare signed.serialize()
would throw on the missing signature:
var base58 = SolanaStudio.walletTransport.base58;
inlineProvider.deserializeTransaction = function (wire) {
return solanaWeb3.Transaction.from(base58.decode(wire));
};
inlineProvider.serializeTransaction = function (signed) {
return base58.encode(
signed.serialize({ requireAllSignatures: false, verifySignatures: false })
);
};Write it once, on the object your detect() returns, and every intent in the app
is covered. Putting it on the intent instead is the same three lines of web3.js
copied into each flow — per-call-site duplication wearing a different hat.
expectedAccount — a UX guard, not a security one
run(..., { expectedAccount: '<base58 address>' }) declares which account the
caller believes it is about to use, and walletOps refuses the trip when a
different one connects. The ownership proof is on-chain — Anchor rejects a
transaction whose signer does not match the PDA's owner, with or without this.
What the declaration buys is a sentence the user can act on instead of a program
error, plus, on the inline transport, a server-minted prepared transaction that
is never wasted.
The refusal carries err.wrongAccount === true and the full err.expected /
err.connected addresses, so a host can compose its own sentence rather than
parse the default one.
It is a string, not a PublicKey, and a non-string is refused: a PublicKey
would stringify correctly inline and be journalled as {} on the redirect path,
matching on a desktop and refusing every mobile trip.
Where it is checked, and what that costs, differs by transport — this is the one place the two genuinely cannot be made identical:
| Transport | Checked | Cost of a wrong wallet |
|---|---|---|
| Inline | after connect(), before prepare()
|
nothing — prepare never runs |
| Redirect, cold session | on the connect callback, before the signing hop | whatever prepare already minted; no signing prompt |
Redirect, warm session (owner) |
locally, before the trip starts | nothing — the trip falls back to a connect hop |
Redirect, warm session (opts.session) |
not checked | — |
The redirect path cannot check earlier because the connect hop destroys the
page: everything prepare returns must already be in the journal before the
navigation.
A session recalled through owner records the address it was established for,
so the check happens locally and costs nothing: a mismatch is a miss, the
trip takes an ordinary connect hop, and the account is checked there. A session
handed in as opts.session carries no address walletOps knows about, so it stays
unchecked — a caller holding one learned the address when it established one, and
that is where the check belongs.
It is a declared value rather than a post-connect hook on purpose. The
connect callback is a different document — in this ecosystem, studio-engine's
wallet callback view, which knows nothing about any consumer's flows — and
resume deliberately does not require a registered handler to advance from
connect to signing. A hook would be looked up on exactly the hop it exists to
guard, come back empty, and be skipped in silence.
owner — one hop for a returning user
Sessions never expire on Phantom, Solflare or Backpack. All three vendors say
so in their own docs — recorded per wallet as sessionsExpire: false, each with
the sessionDocs URL it came from, in wallet_transport.js's PROFILES table
(verified 2026-09-07). Nothing persisted one, so every
mobile signing trip paid two app switches — connect, then sign — and the
second one is where a real user's entry was lost on QA.
Declare an owner and the connect hop's session is written down. The next trip
skips straight to signing:
SolanaStudio.walletOps.run('contest_entry', { contestId: 12 }, {
provider: walletProvider.detect(),
owner: currentUser.id, // string or number; an object is refused
cluster: document.body.dataset.solanaCluster,
// ...
});Omit it and every trip behaves exactly as it did before — same hops, same journal
bytes, including a caller that supplies its own opts.session. Recovery and the
scope stamp are written only for a session this gem recalled; a session you
hand in stays yours to manage, because the gem has no record of it to forget.
The session lives in SolanaStudio.walletSession
(solana_studio/wallet_journal.js, a separate record from the journal: the
journal is single-use and expires in ten minutes, a session is reusable and does
not).
The token is opaque. It decodes to a 64-byte signature plus JSON, and nothing in this gem reads any of it. The wallet is the only authority on whether a session is still good, so a local parse can only produce a second opinion that is wrong in one of two directions.
What the host owes
| Call | When | Why |
|---|---|---|
run(..., { owner, cluster }) |
every trip | scopes the session; without it nothing is stored |
resume(params, { owner, cluster }) |
the callback page, for a plain sign-in connect | walletOps did not start that trip, so the owner can only come from here — and a sign-in session is what makes a user's first action one hop |
walletJournal.purge() |
logout / user switch | sweeps both records. A session outliving a logout is a stranger signing. |
⚠
purge()is a call you must ADD, not one you already make. It sweeps thewallet_dl_prefix. A host carrying aphantom_dl_-era sweep from before this gem existed — turf-monster's layout does — clears neither record, because the prefixes do not match. Adoptownerand that call in the same change: without it a session that never expires, and the dapp encryption secret stored beside it, both survive a logout on a shared device.
A trip started through run carries its own owner in the journal, so resume
needs nothing for it. The stamp is read from the journal in preference to
opts.owner deliberately: the journal says who started the trip, and stamping
the user who happens to be signed in when the wallet answers is the one outcome
that could hand a session to someone who never established it.
When the wallet refuses a stored session
It can, and vendor docs name the causes: an explicit disconnect, a wallet
keypair change, the user switching networks, and an app_url
blocklisting. The refusal arrives on the signing callback — by which point the
user has already left for their wallet and come back, so failing there loses
whatever they were doing.
So the trip does not fail. walletOps forgets the session and takes the hop it skipped: a connect, carrying the same intent, which the ordinary connect callback picks up and advances to signing on its own. The user pays one extra app switch — the two-hop cost they would have paid anyway — instead of starting over.
-
prepare()is not re-run. The journalled intent is reused, so a prepared-transaction row minted for the first attempt is the one that gets signed. Re-preparing would strand the first and mint a second for one user action. - Recovery happens at most once, structurally: the retry intent carries no recovery block, so a second refusal surfaces the wallet's own error.
-
A user rejection (
4001) is not a refusal. The session is fine, the user said no, and it reaches the caller as itself.
Its lifetime ends at exactly four events — a wallet refusal, a scope change
(different user, wallet or cluster), purge(), or walletSession.forget().
There is no timer, because inventing one would contradict the vendor fact the
feature rests on.
signOnly
A co-signed transaction cannot be broadcast by the wallet: the chain rejects
it for the missing signature, and the signed bytes the server needs never come
back. signOnly: true makes the transaction's requirement outrank the wallet's
capability, so the trip takes signTransaction even on Solflare and Backpack,
which do ship a send-side deeplink. Omit it and nothing changes: a wallet that
can broadcast still does. It is a boolean or it is refused.
What walletOps does not do
It does not broadcast, and it mounts no routes. complete is told which side
sent — sendStrategy is 'app-broadcasts' or 'wallet-broadcasts' — and owns
the RPC. The redirect leg also needs a host callback page to call
walletOps.resume(params, { navigate }); studio-engine's
solana_sessions/phantom_callback does this from 0.73.0.
The wallet as a session identity (walletIdentity)
solana_studio/wallet_identity.js makes the connected wallet an identity
source for studio-engine's session-drift primitive (window.StudioSession,
documented in studio-engine's docs/SESSION_DRIFT.md). The engine compares the
identities a page was rendered for with the identities the browser observes now,
and it stays web2: it never learns what a wallet is. This file supplies that
half, and nothing else in the gem depends on it.
Load it after studio/session.js, then register once per window. Registering
the same name twice throws, and on a Turbo host the session store and its
registrations outlive a visit, so a script that runs on every visit must register
only the first time:
<%= javascript_include_tag "studio/session" %>
<%= javascript_include_tag "solana_studio/wallet_identity" %>var wallet = SolanaStudio.walletIdentity.register({
getProvider: hostResolver, // your registry's pick, or omit for window.phantom.solana
trustedConnect: sessionHasAWallet, // see the options table
rescanOn: ["wallet-provider:registered"] // your registry's "a wallet arrived" event, if it has one
});
wallet.source.current(); // { status, address, providerName }
wallet.source.subscribe(function (next, previous) { /* repaint the navbar */ });
document.addEventListener("session:mismatch", function (event) {
if (event.detail.source === "wallet") { /* an undeclared switch */ }
});register returns { source, registration }. Without a StudioSession on the
page, registration is null and the source still runs, so a page can render
wallet state without the session primitive.
SolanaStudio.walletIdentity.create(options) returns the bare source for a host
that registers it itself.
What it reports
status |
Reported to the session | Meaning |
|---|---|---|
unknown |
undefined (cannot tell) |
Provider discovery or a silent connect is still pending |
none |
null |
No wallet provider appeared before the discovery window closed |
disconnected |
null |
A provider is present and holds no account for this site |
connected |
the base58 address | This wallet is connected |
unknown and none never collapse: a page that cannot tell yet must not render
as "you have no wallet". The session sees only the middle column.
A mismatch is a different connected address, and nothing else. A disconnect,
a locked extension, or a page with no wallet is not a switch to someone else, so
the source's equals treats an observed null as agreeing with the bound
address. The page still sees the disconnect through current(). Pass
disconnectIsMismatch: true to count it.
How it reads the wallet
-
Two provider shapes. An injected provider (Phantom's
window.phantom.solana, or a host adapter normalized to it): livepublicKey, plusaccountChanged,connectanddisconnect. A raw Wallet Standard wallet: liveaccountsandstandard:eventschange. -
Live, never cached. Every read goes back to the wallet. On a Wallet
Standard
changeit readswallet.accounts, not the event's copy, because an adapter that cached its account once reported the previous account forever after a switch the wallet never announced. -
Events are best-effort.
focus,visibilitychangeto visible andpageshowre-resolve the provider and re-read it. That catches a switch made while the tab was hidden. - One binding per provider object, however often the page reconciles. A provider replaced by a later one (a Wallet Standard registration superseding the injected object) is detached, and its events are ignored.
Options
| Option | Default | |
|---|---|---|
getProvider |
window.phantom.solana || window.solana |
The provider to watch now, or null. Called on every reconcile. |
trustedConnect |
false |
When the wallet holds no account, ask it silently (onlyIfTrusted / { silent: true }) before believing disconnected. Off by default because a silent connect can pop Phantom's unlock prompt; turn it on only where a wallet session is already expected. |
discoveryMs, discoveryIntervalMs
|
3000, 100
|
How long "no provider yet" stays unknown while a late injection is polled for. 0 reads none at once. |
rescanOn |
[] |
Extra window events that re-resolve the provider. |
name |
"wallet" |
The identity source name, and the key the server binds under. |
bound |
engine default | Passed through to the engine: bound(snapshot) returns the bound identity. |
disconnectIsMismatch |
false |
See above. |
session |
window.StudioSession |
The store register uses. |
What the host owes
-
The server half. Bind the session under the same name:
studio_session_identitiesreturns{ wallet: <the wallet this session signed in with> }. Bind nothing for a session that has no wallet of its own (a guest, or a managed wallet the browser never holds). An unbound source still reports what it sees and never mismatches. -
Holds are per SOURCE, not per address.
StudioSession.expectChange("wallet")marks every switch expected until it is released. A flow that walks through specific wallets, such as a multi-signer ceremony, must still check the observed address against the wallets it declared, or a switch to any other wallet goes quiet for the length of the hold. -
The UI and the re-auth. The switch card, the navbar, and signing in again
with the new wallet (then
StudioSession.refresh()) are the host's.
It never signs, sends, writes storage or opens a modal.
Dependencies
-
ed25519(~> 1.3) — Ed25519 signing and the verification equation. It does not vet the public key, so every verify in this gem (AuthVerifier.verify!,WireMessage#signature_valid?) runsSolana::Ed25519Strictfirst. - Ruby stdlib only (net/http, json, digest, securerandom)
-
No Rails dependency.
railtiesis a development dependency only; the engine loads solely when the host has already loaded Rails.
Development Notes
See RUNBOOK.md for troubleshooting and local test commands.
The durable-nonce primitives: one consumer left, and it is a dead route
Solana::SystemProgram and Solana::NonceAccount landed together in v0.4.6
(2026-06-02, 11ec512) for two consumers: McRitchie Studio's signing console
and turf-monster's operator transactions. Neither is a live flow now.
Re-measured 2026-09-16 against turf-monster origin/accepted (61185cdd); this
note used to say otherwise.
-
The signing console is gone. It was frozen on 2026-08-31 and deleted on
2026-09-04 (the hub's
retire-signing-consoletask), with its doc. -
turf-monster reaches the nonce from one dead route.
Solana::Vault#durable_nonce_confighas one caller,#build_create_contest(admin_signs: true), reached only fromContestsController#prepare_onchain_contest. Nothing underapp/viewsorapp/javascriptcalls that route; onlye2e/rpc-mock.jsnames it. -
No cosign guard admits a nonce advance. turf-monster's cosign guards
refuse every System instruction,
advanceNonceAccountincluded, and so doesSolana::Cosign. -
A nonce cannot anchor a wallet-signed transaction. A nonce transaction is
recognized only when
advanceNonceAccountis instruction 0, and Phantom inserts Lighthouse instructions ahead of it (turf-monster mainnet incident, 2026-06-11). That is why Mr. McRitchie dropped nonce support from the primitives extraction on 2026-09-16.
The files stay, byte-match tested in test/system_program_test.rb, until
turf-monster decides the dead route's fate. Removing them first would break that
route's build step.
The browser lane
The Ruby suite cannot see three things this gem ships: whether
network_guard.js actually runs in a browser, whether
_network_mismatch.html.erb renders (rendering it needs studio-engine's modal
blocks and a view context, so test/views_test.rb only proves it compiles), and
whether the base58 encoder inlined in _phantom_deeplink.html.erb produces the
right bytes. That last one is signing-path code: the deep link encodes the
payload a user signs inside Phantom, so an encoder that mis-encodes yields a
signature over the wrong bytes. The failure is invisible to a String assertion —
the source is identical either way — and lands when someone taps Connect on a
phone. e2e/phantom_deeplink.spec.js decodes the emitted payload with its own
independent implementation and compares bytes, rather than checking the parameter
merely looks like base58.
npm ci && npx playwright install chromium
npx playwright test # ~40s, boots its own server
npx playwright test --headed # watch it
bin/e2e-executed-set-check # did the lane run its WHOLE declared set?The lane drives the shipped bytes: e2e/boot.rb copies the real
app/assets/javascripts/solana_studio/network_guard.js into the dummy's public/,
and the lab pages render the real partials by name. A lab page may set up a
partial's locals and nothing else — test/e2e_lane_contract_test.rb asserts that,
because a page that hand-rolled what the gem does would leave the specs grading the
lab while reporting green over untested gem code.
It is not in bin/release-check. It runs as a parallel CI job, so it adds ~0
to the wall time a PR waits and a release does not install a browser to publish.
Two halves, one number. config/e2e_lane.yml declares how many specs must
execute. bin/e2e-executed-set-check reads Playwright's own receipt after the run
and asserts the executed set against it; test/e2e_lane_contract_test.rb asserts
the committed specs still declare it. Static counting answers "how many are
DECLARED" and can never answer "how many RAN" — and a runtime skip, a stray
--grep, --only-changed, and an uncollected file are four spellings of the same
event. The receipt turns all four into one arithmetic failure.
Derive the counts, never hand-count them: npx playwright test --list.
Run the suite with bin/release-check — the same entry point CI and the release
gate use, so they cannot drift apart. It enumerates test files by glob (no list
to forget a file from) and fails a file that runs zero tests or skips one,
because a suite that quietly stops covering something is the failure a green
build cannot show you. node is required: the browser guard's suite runs the
shipped .js under node with window/document stubs.
License
MIT