surfpool-sdk 1.3.1

SDK for embedding Surfpool in Rust integration tests
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use std::{
    env,
    path::{Path, PathBuf},
};

use solana_client::rpc_request::RpcRequest;
use solana_epoch_info::EpochInfo;
use solana_keypair::{EncodableKey, Keypair};
use solana_pubkey::Pubkey;
use solana_rpc_client::rpc_client::RpcClient;
use solana_signer::Signer;
use spl_associated_token_account_interface::address::get_associated_token_address_with_program_id;

use crate::error::{SurfnetError, SurfnetResult};
pub mod builders;
use builders::{CheatcodeBuilder, DeployProgram};

/// Direct state manipulation helpers for a running Surfnet.
///
/// These bypass normal transaction flow to instantly set account state —
/// perfect for test setup (funding wallets, minting tokens, etc.).
///
/// ```rust
/// use surfpool_sdk::{Pubkey, Surfnet};
/// use surfpool_sdk::cheatcodes::builders::SetAccount;
///
/// # async fn example() {
/// let surfnet = Surfnet::start().await.unwrap();
/// let cheats = surfnet.cheatcodes();
///
/// // Fund an account with 5 SOL
/// let alice: Pubkey = "...".parse().unwrap();
/// cheats.fund_sol(&alice, 5_000_000_000).unwrap();
///
/// // Fund a token account with 1000 USDC
/// let usdc_mint: Pubkey = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v".parse().unwrap();
/// cheats.fund_token(&alice, &usdc_mint, 1_000_000_000, None).unwrap();
///
/// // Or build a typed cheatcode request:
/// let custom = Pubkey::new_unique();
/// let owner = Pubkey::new_unique();
/// cheats
///     .execute(
///         SetAccount::new(custom)
///             .lamports(42)
///             .owner(owner)
///             .data(vec![1, 2, 3]),
///     )
///     .unwrap();
/// # }
/// ```
pub struct Cheatcodes<'a> {
    rpc_url: &'a str,
}

impl<'a> Cheatcodes<'a> {
    pub(crate) fn new(rpc_url: &'a str) -> Self {
        Self { rpc_url }
    }

    fn rpc_client(&self) -> RpcClient {
        RpcClient::new(self.rpc_url)
    }

    /// Set the SOL balance for an account in lamports.
    ///
    /// ```rust
    /// use surfpool_sdk::{Pubkey, Surfnet};
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    /// let recipient = Pubkey::new_unique();
    ///
    /// cheats.fund_sol(&recipient, 1_000_000_000).unwrap();
    /// # }
    /// ```
    pub fn fund_sol(&self, address: &Pubkey, lamports: u64) -> SurfnetResult<()> {
        let params = serde_json::json!([
            address.to_string(),
            { "lamports": lamports }
        ]);
        self.call_cheatcode("surfnet_setAccount", params)
    }

    /// Set arbitrary account state for a single account.
    ///
    /// This helper updates lamports, owner, and raw account data in one RPC call.
    ///
    /// ```rust
    /// use surfpool_sdk::{Pubkey, Surfnet};
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    /// let address = Pubkey::new_unique();
    /// let owner = Pubkey::new_unique();
    ///
    /// cheats.set_account(&address, 500, &[1, 2, 3], &owner).unwrap();
    /// # }
    /// ```
    pub fn set_account(
        &self,
        address: &Pubkey,
        lamports: u64,
        data: &[u8],
        owner: &Pubkey,
    ) -> SurfnetResult<()> {
        let params = serde_json::json!([
            address.to_string(),
            {
                "lamports": lamports,
                "data": hex::encode(data),
                "owner": owner.to_string()
            }
        ]);
        self.call_cheatcode("surfnet_setAccount", params)
    }

    /// Fund a token account (creates the ATA if needed).
    ///
    /// Uses `spl_token` program by default. Pass `token_program` to use Token-2022.
    ///
    /// ```rust
    /// use surfpool_sdk::{Pubkey, Surfnet};
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    /// let owner = Pubkey::new_unique();
    /// let mint = Pubkey::new_unique();
    ///
    /// cheats.fund_token(&owner, &mint, 1_000, None).unwrap();
    /// # }
    /// ```
    pub fn fund_token(
        &self,
        owner: &Pubkey,
        mint: &Pubkey,
        amount: u64,
        token_program: Option<&Pubkey>,
    ) -> SurfnetResult<()> {
        let program = token_program.copied().unwrap_or(spl_token_program_id());
        let params = serde_json::json!([
            owner.to_string(),
            mint.to_string(),
            { "amount": amount },
            program.to_string()
        ]);
        self.call_cheatcode("surfnet_setTokenAccount", params)
    }

    /// Set the token balance for a wallet/mint pair.
    ///
    /// This is an alias for [`Self::fund_token`].
    ///
    /// ```rust
    /// use surfpool_sdk::{Pubkey, Surfnet};
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    /// let owner = Pubkey::new_unique();
    /// let mint = Pubkey::new_unique();
    ///
    /// cheats.set_token_balance(&owner, &mint, 5_000, None).unwrap();
    /// # }
    /// ```
    pub fn set_token_balance(
        &self,
        owner: &Pubkey,
        mint: &Pubkey,
        amount: u64,
        token_program: Option<&Pubkey>,
    ) -> SurfnetResult<()> {
        self.fund_token(owner, mint, amount, token_program)
    }

    /// Get the associated token address for a wallet/mint pair.
    ///
    /// ```rust
    /// use surfpool_sdk::{Pubkey, Surfnet};
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    /// let owner = Pubkey::new_unique();
    /// let mint = Pubkey::new_unique();
    ///
    /// let ata = cheats.get_ata(&owner, &mint, None);
    /// println!("{ata}");
    /// # }
    /// ```
    pub fn get_ata(&self, owner: &Pubkey, mint: &Pubkey, token_program: Option<&Pubkey>) -> Pubkey {
        let program = token_program.copied().unwrap_or(spl_token_program_id());
        get_associated_token_address_with_program_id(owner, mint, &program)
    }

    /// Fund multiple accounts with SOL using repeated `surfnet_setAccount` calls.
    ///
    /// ```rust
    /// use surfpool_sdk::{Pubkey, Surfnet};
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    /// let alice = Pubkey::new_unique();
    /// let bob = Pubkey::new_unique();
    ///
    /// cheats
    ///     .fund_sol_many(&[(&alice, 1_000_000), (&bob, 2_000_000)])
    ///     .unwrap();
    /// # }
    /// ```
    pub fn fund_sol_many(&self, accounts: &[(&Pubkey, u64)]) -> SurfnetResult<()> {
        for (address, lamports) in accounts {
            self.fund_sol(address, *lamports)?;
        }
        Ok(())
    }

    /// Fund multiple wallets with the same token and amount.
    ///
    /// ```rust
    /// use surfpool_sdk::{Pubkey, Surfnet};
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    /// let alice = Pubkey::new_unique();
    /// let bob = Pubkey::new_unique();
    /// let mint = Pubkey::new_unique();
    ///
    /// cheats
    ///     .fund_token_many(&[&alice, &bob], &mint, 1_000, None)
    ///     .unwrap();
    /// # }
    /// ```
    pub fn fund_token_many(
        &self,
        owners: &[&Pubkey],
        mint: &Pubkey,
        amount: u64,
        token_program: Option<&Pubkey>,
    ) -> SurfnetResult<()> {
        for owner in owners {
            self.fund_token(owner, mint, amount, token_program)?;
        }
        Ok(())
    }

    /// Move Surfnet time forward to an absolute epoch.
    ///
    /// ```rust
    /// use surfpool_sdk::Surfnet;
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    ///
    /// let epoch_info = cheats.time_travel_to_epoch(10).unwrap();
    /// assert!(epoch_info.epoch >= 10);
    /// # }
    /// ```
    pub fn time_travel_to_epoch(&self, epoch: u64) -> SurfnetResult<EpochInfo> {
        self.time_travel(serde_json::json!([{ "absoluteEpoch": epoch }]))
    }

    /// Move Surfnet time forward to an absolute slot.
    ///
    /// ```rust
    /// use surfpool_sdk::Surfnet;
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    ///
    /// let epoch_info = cheats.time_travel_to_slot(1_000).unwrap();
    /// assert!(epoch_info.absolute_slot >= 1_000);
    /// # }
    /// ```
    pub fn time_travel_to_slot(&self, slot: u64) -> SurfnetResult<EpochInfo> {
        self.time_travel(serde_json::json!([{ "absoluteSlot": slot }]))
    }

    /// Move Surfnet time forward to an absolute Unix timestamp in milliseconds.
    ///
    /// ```rust
    /// use surfpool_sdk::Surfnet;
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    ///
    /// let epoch_info = cheats.time_travel_to_timestamp(1_700_000_000_000).unwrap();
    /// assert!(epoch_info.absolute_slot > 0);
    /// # }
    /// ```
    pub fn time_travel_to_timestamp(&self, timestamp: u64) -> SurfnetResult<EpochInfo> {
        self.time_travel(serde_json::json!([{ "absoluteTimestamp": timestamp }]))
    }

    /// Deploy a program from local workspace artifacts.
    ///
    /// This looks for:
    /// - `target/deploy/{program_name}.so`
    /// - `target/deploy/{program_name}-keypair.json`
    /// - `target/idl/{program_name}.json` (optional)
    ///
    /// If an IDL file exists, it is registered after the program bytes are written.
    ///
    /// ```rust
    /// use surfpool_sdk::Surfnet;
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    ///
    /// let program_id = cheats.deploy_program("my_program").unwrap();
    /// println!("{program_id}");
    /// # }
    /// ```
    pub fn deploy_program(&self, program_name: &str) -> SurfnetResult<Pubkey> {
        let target_dir = resolve_target_dir(program_name)?;
        let deploy_dir = target_dir.join("deploy");
        let idl_dir = target_dir.join("idl");
        let so_path = deploy_dir.join(format!("{program_name}.so"));
        let keypair_path = deploy_dir.join(format!("{program_name}-keypair.json"));
        let idl_path = idl_dir.join(format!("{program_name}.json"));

        let builder = DeployProgram::from_keypair_path(&keypair_path)?
            .so_path(so_path)
            .idl_path_if_exists(idl_path);

        self.deploy(builder)
    }

    /// Deploy a program described by a [`DeployProgram`] builder.
    ///
    /// This writes the program bytes with `surfnet_writeProgram` and, when present,
    /// registers the parsed IDL with `surfnet_registerIdl`.
    ///
    /// ```rust
    /// use surfpool_sdk::{Pubkey, Surfnet};
    /// use surfpool_sdk::cheatcodes::builders::DeployProgram;
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    /// let program_id = Pubkey::new_unique();
    ///
    /// let deployed_program = cheats
    ///     .deploy(
    ///         DeployProgram::new(program_id)
    ///             .so_path("target/deploy/my_program.so")
    ///             .idl_path("target/idl/my_program.json"),
    ///     )
    ///     .unwrap();
    ///
    /// assert_eq!(deployed_program, program_id);
    /// # }
    /// ```
    pub fn deploy(&self, builder: DeployProgram) -> SurfnetResult<Pubkey> {
        let program_id = builder.program_id();
        let program_bytes = builder.load_so_bytes()?;
        self.write_program(&program_id, &program_bytes)?;

        if let Some(mut idl) = builder.load_idl()? {
            idl.address = program_id.to_string();
            self.register_idl(&idl)?;
        }

        Ok(program_id)
    }

    /// Execute a typed cheatcode builder.
    ///
    /// ```rust
    /// use surfpool_sdk::{Pubkey, Surfnet};
    /// use surfpool_sdk::cheatcodes::builders::ResetAccount;
    ///
    /// # async fn example() {
    /// let surfnet = Surfnet::start().await.unwrap();
    /// let cheats = surfnet.cheatcodes();
    /// let address = Pubkey::new_unique();
    ///
    /// cheats.execute(ResetAccount::new(address)).unwrap();
    /// # }
    /// ```
    pub fn execute<B: CheatcodeBuilder>(&self, builder: B) -> SurfnetResult<()> {
        self.call_cheatcode(B::METHOD, builder.build())
    }

    /// Internal helper for `surfnet_timeTravel` requests that return [`EpochInfo`].
    fn time_travel(&self, params: serde_json::Value) -> SurfnetResult<EpochInfo> {
        let client = self.rpc_client();
        client
            .send::<EpochInfo>(
                RpcRequest::Custom {
                    method: "surfnet_timeTravel",
                },
                params,
            )
            .map_err(|e| SurfnetError::Cheatcode(format!("surfnet_timeTravel: {e}")))
    }

    fn write_program(&self, program_id: &Pubkey, data: &[u8]) -> SurfnetResult<()> {
        const PROGRAM_CHUNK_BYTES: usize = 15 * 1024 * 1024;

        for (index, chunk) in data.chunks(PROGRAM_CHUNK_BYTES).enumerate() {
            let offset = index * PROGRAM_CHUNK_BYTES;
            let params = serde_json::json!([program_id.to_string(), hex::encode(chunk), offset,]);
            self.call_cheatcode("surfnet_writeProgram", params)?;
        }

        Ok(())
    }

    fn register_idl(&self, idl: &surfpool_types::Idl) -> SurfnetResult<()> {
        let client = self.rpc_client();
        client
            .send::<serde_json::Value>(
                RpcRequest::Custom {
                    method: "surfnet_registerIdl",
                },
                serde_json::json!([idl]),
            )
            .map_err(|e| SurfnetError::Cheatcode(format!("surfnet_registerIdl: {e}")))?;
        Ok(())
    }

    /// Internal helper for cheatcodes that return `()`.
    fn call_cheatcode(&self, method: &'static str, params: serde_json::Value) -> SurfnetResult<()> {
        let client = self.rpc_client();
        client
            .send::<serde_json::Value>(RpcRequest::Custom { method }, params)
            .map_err(|e| SurfnetError::Cheatcode(format!("{method}: {e}")))?;
        Ok(())
    }
}

fn spl_token_program_id() -> Pubkey {
    // spl_token::id() = TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
    Pubkey::from_str_const("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
}

fn read_keypair_pubkey(path: &Path) -> SurfnetResult<Pubkey> {
    Keypair::read_from_file(path)
        .map(|keypair| keypair.pubkey())
        .map_err(|e| {
            SurfnetError::Cheatcode(format!(
                "failed to read deploy keypair from {}: {e}",
                path.display()
            ))
        })
}

fn resolve_target_dir(program_name: &str) -> SurfnetResult<PathBuf> {
    if let Ok(explicit_target_dir) = env::var("CARGO_TARGET_DIR") {
        let target_dir = PathBuf::from(explicit_target_dir);
        if has_program_artifacts(&target_dir, program_name) {
            return Ok(target_dir);
        }
    }

    let current_dir = env::current_dir().map_err(|e| {
        SurfnetError::Cheatcode(format!("failed to resolve current working directory: {e}"))
    })?;

    for ancestor in current_dir.ancestors() {
        let target_dir = ancestor.join("target");
        if has_program_artifacts(&target_dir, program_name) {
            return Ok(target_dir);
        }
    }

    Err(SurfnetError::Cheatcode(format!(
        "failed to locate target/deploy artifacts for program `{program_name}` starting from {}",
        current_dir.display()
    )))
}

fn has_program_artifacts(target_dir: &Path, program_name: &str) -> bool {
    target_dir
        .join("deploy")
        .join(format!("{program_name}.so"))
        .exists()
        && target_dir
            .join("deploy")
            .join(format!("{program_name}-keypair.json"))
            .exists()
}

#[cfg(test)]
mod tests;