solana-wasi 0.1.0

Solana primitives that actually compile to wasm32-wasip2: pubkeys, PDAs, JSON-RPC over a swappable transport, SPL Token / Token-2022 account parsing, and unsigned v0 transaction construction. No solana-sdk, no C toolchain, no async runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! A small, typed JSON-RPC client.
//!
//! Only the methods a tool plugin actually needs are modelled. Each one returns
//! a Rust type rather than a `serde_json::Value`, because the whole point of
//! this crate is that the plugin above it never hand-parses an RPC response and
//! never accidentally forwards 40KB of it into a model's context window.

use std::cell::Cell;

use base64::Engine;
use serde::Deserialize;
use serde_json::{json, Value};

use crate::error::{Error, Result};
use crate::pubkey::Pubkey;
use crate::transport::Transport;

/// Commitment level sent with every request that accepts one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Commitment {
    /// Seen by this node, may still be dropped.
    Processed,
    /// Voted on by a supermajority. The default.
    #[default]
    Confirmed,
    /// Rooted; will not be rolled back.
    Finalized,
}

impl Commitment {
    /// The wire string.
    pub const fn as_str(self) -> &'static str {
        match self {
            Commitment::Processed => "processed",
            Commitment::Confirmed => "confirmed",
            Commitment::Finalized => "finalized",
        }
    }
}

/// A fetched account, with `data` already base64-decoded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Account {
    /// Balance in lamports.
    pub lamports: u64,
    /// The program that owns, and may write to, this account.
    pub owner: Pubkey,
    /// Raw account data, already base64-decoded.
    pub data: Vec<u8>,
    /// True for a program account.
    pub executable: bool,
    /// Legacy rent field; kept for completeness.
    pub rent_epoch: u64,
}

/// A token amount as the RPC reports it.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct UiTokenAmount {
    /// Raw base units, as a string because it does not fit a JS number.
    pub amount: String,
    /// Decimal places the mint declares.
    pub decimals: u8,
    /// The node's own rendering of `amount`, when it supplied one.
    #[serde(default)]
    pub ui_amount_string: String,
}

/// One row of `getTokenLargestAccounts`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenAccountBalance {
    /// The token account, not its owner.
    pub address: Pubkey,
    /// Balance in base units.
    pub amount: u128,
    /// Decimal places the mint declares.
    pub decimals: u8,
}

/// The pair `getLatestBlockhash` returns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LatestBlockhash {
    /// Base58 blockhash to put in a message.
    pub blockhash: String,
    /// Last block height at which a transaction using it is still accepted.
    pub last_valid_block_height: u64,
}

/// The interesting part of a `simulateTransaction` response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SimulationOutcome {
    /// `None` means the transaction simulated successfully.
    pub err: Option<String>,
    /// Program log lines, in order.
    pub logs: Vec<String>,
    /// Compute units the simulation used.
    pub units_consumed: Option<u64>,
}

/// A JSON-RPC client bound to one endpoint and one [`Transport`].
pub struct RpcClient<T: Transport> {
    url: String,
    transport: T,
    commitment: Commitment,
    next_id: Cell<u64>,
}

impl<T: Transport> RpcClient<T> {
    /// Bind to an endpoint.
    pub fn new(url: impl Into<String>, transport: T) -> Self {
        Self {
            url: url.into(),
            transport,
            commitment: Commitment::default(),
            next_id: Cell::new(1),
        }
    }

    /// Set the commitment used by every subsequent call.
    pub fn with_commitment(mut self, commitment: Commitment) -> Self {
        self.commitment = commitment;
        self
    }

    /// The endpoint with any credential material removed.
    ///
    /// Operators put their API key in the RPC URL (`…/?api-key=…`, or as a path
    /// segment). Use this — never `self.url` — in anything that reaches a log
    /// line, an error message, or a model's context.
    pub fn safe_endpoint(&self) -> String {
        redact_endpoint(&self.url)
    }

    fn call(&self, method: &str, params: Value) -> Result<Value> {
        let id = self.next_id.get();
        self.next_id.set(id.wrapping_add(1));

        let body = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params,
        })
        .to_string();

        let raw = self.transport.post_json(&self.url, &body)?;
        let parsed: Value = serde_json::from_str(&raw)
            .map_err(|e| Error::UnexpectedResponse(format!("{method}: not JSON: {e}")))?;

        if let Some(err) = parsed.get("error") {
            let code = err.get("code").and_then(Value::as_i64).unwrap_or(0);
            let message = err
                .get("message")
                .and_then(Value::as_str)
                .unwrap_or("unknown")
                .chars()
                .take(200)
                .collect();
            return Err(Error::Rpc { code, message });
        }

        parsed
            .get("result")
            .cloned()
            .ok_or_else(|| Error::UnexpectedResponse(format!("{method}: no result member")))
    }

    fn commitment_cfg(&self) -> Value {
        json!({ "commitment": self.commitment.as_str() })
    }

    /// `getAccountInfo`. `Ok(None)` when the account does not exist.
    pub fn get_account(&self, address: &Pubkey) -> Result<Option<Account>> {
        let result = self.call(
            "getAccountInfo",
            json!([
                address.to_base58(),
                { "encoding": "base64", "commitment": self.commitment.as_str() }
            ]),
        )?;
        parse_account(result.get("value").unwrap_or(&Value::Null))
    }

    /// `getAccountInfo`, erroring when the account is missing.
    pub fn require_account(&self, address: &Pubkey) -> Result<Account> {
        self.get_account(address)?
            .ok_or_else(|| Error::AccountNotFound(address.to_base58()))
    }

    /// `getMultipleAccounts`. One round trip for up to 100 addresses; prefer
    /// this over a loop of `get_account`, both for latency and because most
    /// providers rate-limit on requests, not on bytes.
    pub fn get_multiple_accounts(&self, addresses: &[Pubkey]) -> Result<Vec<Option<Account>>> {
        if addresses.is_empty() {
            return Ok(Vec::new());
        }
        if addresses.len() > 100 {
            return Err(Error::InvalidArgument(
                "getMultipleAccounts accepts at most 100 addresses".into(),
            ));
        }
        let keys: Vec<String> = addresses.iter().map(Pubkey::to_base58).collect();
        let result = self.call(
            "getMultipleAccounts",
            json!([
                keys,
                { "encoding": "base64", "commitment": self.commitment.as_str() }
            ]),
        )?;
        let values = result
            .get("value")
            .and_then(Value::as_array)
            .ok_or_else(|| Error::UnexpectedResponse("getMultipleAccounts: no value".into()))?;
        values.iter().map(parse_account).collect()
    }

    /// `getBalance`, in lamports.
    pub fn get_balance(&self, address: &Pubkey) -> Result<u64> {
        let result = self.call(
            "getBalance",
            json!([address.to_base58(), self.commitment_cfg()]),
        )?;
        result
            .get("value")
            .and_then(Value::as_u64)
            .ok_or_else(|| Error::UnexpectedResponse("getBalance: no value".into()))
    }

    /// `getLatestBlockhash`.
    pub fn get_latest_blockhash(&self) -> Result<LatestBlockhash> {
        let result = self.call("getLatestBlockhash", json!([self.commitment_cfg()]))?;
        let value = result
            .get("value")
            .ok_or_else(|| Error::UnexpectedResponse("getLatestBlockhash: no value".into()))?;
        Ok(LatestBlockhash {
            blockhash: value
                .get("blockhash")
                .and_then(Value::as_str)
                .ok_or_else(|| Error::UnexpectedResponse("getLatestBlockhash: no blockhash".into()))?
                .to_string(),
            last_valid_block_height: value
                .get("lastValidBlockHeight")
                .and_then(Value::as_u64)
                .unwrap_or_default(),
        })
    }

    /// `getSlot`.
    pub fn get_slot(&self) -> Result<u64> {
        self.call("getSlot", json!([self.commitment_cfg()]))?
            .as_u64()
            .ok_or_else(|| Error::UnexpectedResponse("getSlot: not a number".into()))
    }

    /// `getTokenSupply`.
    pub fn get_token_supply(&self, mint: &Pubkey) -> Result<UiTokenAmount> {
        let result = self.call(
            "getTokenSupply",
            json!([mint.to_base58(), self.commitment_cfg()]),
        )?;
        let value = result
            .get("value")
            .ok_or_else(|| Error::UnexpectedResponse("getTokenSupply: no value".into()))?;
        Ok(UiTokenAmount {
            amount: value
                .get("amount")
                .and_then(Value::as_str)
                .unwrap_or("0")
                .to_string(),
            decimals: value.get("decimals").and_then(Value::as_u64).unwrap_or(0) as u8,
            ui_amount_string: value
                .get("uiAmountString")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string(),
        })
    }

    /// `getTokenLargestAccounts` — the top 20 holders by balance.
    pub fn get_token_largest_accounts(&self, mint: &Pubkey) -> Result<Vec<TokenAccountBalance>> {
        let result = self.call(
            "getTokenLargestAccounts",
            json!([mint.to_base58(), self.commitment_cfg()]),
        )?;
        let rows = result
            .get("value")
            .and_then(Value::as_array)
            .ok_or_else(|| Error::UnexpectedResponse("getTokenLargestAccounts: no value".into()))?;

        let mut out = Vec::with_capacity(rows.len());
        for row in rows {
            let address = row
                .get("address")
                .and_then(Value::as_str)
                .ok_or_else(|| Error::UnexpectedResponse("largest accounts: no address".into()))?;
            let amount = row
                .get("amount")
                .and_then(Value::as_str)
                .unwrap_or("0")
                .parse::<u128>()
                .unwrap_or(0);
            out.push(TokenAccountBalance {
                address: Pubkey::from_base58(address)?,
                amount,
                decimals: row.get("decimals").and_then(Value::as_u64).unwrap_or(0) as u8,
            });
        }
        Ok(out)
    }

    /// `getMinimumBalanceForRentExemption`.
    pub fn get_minimum_balance_for_rent_exemption(&self, data_len: usize) -> Result<u64> {
        self.call("getMinimumBalanceForRentExemption", json!([data_len]))?
            .as_u64()
            .ok_or_else(|| Error::UnexpectedResponse("rent exemption: not a number".into()))
    }

    /// `simulateTransaction` with `sigVerify: false`.
    ///
    /// The point of simulating an *unsigned* transaction is that a T1 builder
    /// can prove the thing it is about to hand a human will actually land,
    /// before the human is asked to approve it.
    pub fn simulate_unsigned(&self, tx_base64: &str) -> Result<SimulationOutcome> {
        let result = self.call(
            "simulateTransaction",
            json!([
                tx_base64,
                {
                    "encoding": "base64",
                    "sigVerify": false,
                    "replaceRecentBlockhash": false,
                    "commitment": self.commitment.as_str(),
                }
            ]),
        )?;
        let value = result
            .get("value")
            .ok_or_else(|| Error::UnexpectedResponse("simulateTransaction: no value".into()))?;
        Ok(SimulationOutcome {
            err: match value.get("err") {
                None | Some(Value::Null) => None,
                Some(e) => Some(e.to_string().chars().take(300).collect()),
            },
            logs: value
                .get("logs")
                .and_then(Value::as_array)
                .map(|l| {
                    l.iter()
                        .filter_map(Value::as_str)
                        .map(str::to_string)
                        .collect()
                })
                .unwrap_or_default(),
            units_consumed: value.get("unitsConsumed").and_then(Value::as_u64),
        })
    }

    /// Escape hatch for a method this crate does not model.
    pub fn raw_call(&self, method: &str, params: Value) -> Result<Value> {
        self.call(method, params)
    }
}

fn parse_account(value: &Value) -> Result<Option<Account>> {
    if value.is_null() {
        return Ok(None);
    }
    let owner = value
        .get("owner")
        .and_then(Value::as_str)
        .ok_or_else(|| Error::UnexpectedResponse("account: no owner".into()))?;

    let data = match value.get("data") {
        // ["<base64>", "base64"]
        Some(Value::Array(parts)) => {
            let encoded = parts
                .first()
                .and_then(Value::as_str)
                .ok_or_else(|| Error::UnexpectedResponse("account: empty data array".into()))?;
            let encoding = parts.get(1).and_then(Value::as_str).unwrap_or("base64");
            if encoding != "base64" {
                return Err(Error::UnexpectedResponse(format!(
                    "account: unsupported data encoding `{encoding}`"
                )));
            }
            base64::engine::general_purpose::STANDARD
                .decode(encoded)
                .map_err(|e| Error::UnexpectedResponse(format!("account: bad base64: {e}")))?
        }
        // jsonParsed responses; this crate never asks for them.
        Some(Value::Object(_)) => {
            return Err(Error::UnexpectedResponse(
                "account: jsonParsed encoding is not supported, request base64".into(),
            ))
        }
        _ => Vec::new(),
    };

    Ok(Some(Account {
        lamports: value.get("lamports").and_then(Value::as_u64).unwrap_or(0),
        owner: Pubkey::from_base58(owner)?,
        data,
        executable: value
            .get("executable")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        rent_epoch: value.get("rentEpoch").and_then(Value::as_u64).unwrap_or(0),
    }))
}

/// Strip credential material from an RPC endpoint so it is safe to print.
///
/// Handles the two shapes every provider uses: a query parameter
/// (`?api-key=…`) and a trailing path segment (`/v2/<uuid>`). Anything that is
/// not a bare `scheme://host` collapses to `scheme://host/…`.
pub fn redact_endpoint(url: &str) -> String {
    let (scheme, rest) = match url.split_once("://") {
        Some((s, r)) => (s, r),
        None => return "".to_string(),
    };
    let host_end = rest.find(['/', '?']).unwrap_or(rest.len());
    let host = &rest[..host_end];
    // Credentials can also be smuggled in userinfo (`user:pass@host`).
    let host = host.rsplit('@').next().unwrap_or(host);
    if host_end == rest.len() {
        format!("{scheme}://{host}")
    } else {
        format!("{scheme}://{host}/…")
    }
}