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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
use std::fmt;
use base64::{engine::general_purpose::STANDARD, Engine as _};
use jsonrpc_core::{futures::future, BoxFuture, Error, Result};
use jsonrpc_derive::rpc;
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
use serde_with::{serde_as, BytesOrString};
use solana_account::Account;
use solana_client::rpc_response::RpcResponseContext;
use solana_clock::Epoch;
use solana_commitment_config::CommitmentConfig;
use solana_rpc_client_api::response::Response as RpcResponse;
use solana_sdk::{
program_option::COption, program_pack::Pack, system_program, transaction::VersionedTransaction,
};
use spl_associated_token_account::get_associated_token_address_with_program_id;
use spl_token::state::{Account as TokenAccount, AccountState};
use surfpool_types::{
types::{ComputeUnitsEstimationResult, ProfileResult},
SimnetEvent,
};
use super::{RunloopContext, SurfnetRpcContext};
use crate::{
rpc::{utils::verify_pubkey, State},
surfnet::{locker::SvmAccessContext, GetAccountResult},
};
#[serde_as]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountUpdate {
/// providing this value sets the lamports in the account
pub lamports: Option<u64>,
/// providing this value sets the data held in this account
#[serde_as(as = "Option<BytesOrString>")]
pub data: Option<Vec<u8>>,
/// providing this value sets the program that owns this account. If executable, the program that loads this account.
pub owner: Option<String>,
/// providing this value sets whether this account's data contains a loaded program (and is now read-only)
pub executable: Option<bool>,
/// providing this value sets the epoch at which this account will next owe rent
pub rent_epoch: Option<Epoch>,
}
impl AccountUpdate {
fn is_full_account_data(&self) -> bool {
self.lamports.is_some()
&& self.owner.is_some()
&& self.executable.is_some()
&& self.rent_epoch.is_some()
&& self.data.is_some()
}
/// Convert the update to an account if all fields are provided
pub fn to_account(&self) -> Result<Option<Account>> {
if self.is_full_account_data() {
Ok(Some(Account {
lamports: self.lamports.unwrap(),
owner: verify_pubkey(&self.owner.clone().unwrap())?,
executable: self.executable.unwrap(),
rent_epoch: self.rent_epoch.unwrap(),
data: self.expect_hex_data()?,
}))
} else {
Ok(None)
}
}
/// Apply the update to the account
pub fn apply(self, account: &mut GetAccountResult) -> Result<()> {
account.apply_update(|account| {
if let Some(lamports) = self.lamports {
account.lamports = lamports;
}
if let Some(owner) = &self.owner {
account.owner = verify_pubkey(owner)?;
}
if let Some(executable) = self.executable {
account.executable = executable;
}
if let Some(rent_epoch) = self.rent_epoch {
account.rent_epoch = rent_epoch;
}
if self.data.is_some() {
account.data = self.expect_hex_data()?;
}
Ok(())
})?;
Ok(())
}
pub fn expect_hex_data(&self) -> Result<Vec<u8>> {
let data = self.data.as_ref().expect("missing expected data field");
hex::decode(data)
.map_err(|e| Error::invalid_params(format!("Invalid hex data provided: {}", e)))
}
}
#[serde_as]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenAccountUpdate {
/// providing this value sets the amount of the token in the account data
pub amount: Option<u64>,
/// providing this value sets the delegate of the token account
pub delegate: Option<SetSomeAccount>,
/// providing this value sets the state of the token account
pub state: Option<String>,
/// providing this value sets the amount authorized to the delegate
pub delegated_amount: Option<u64>,
/// providing this value sets the close authority of the token account
pub close_authority: Option<SetSomeAccount>,
}
#[derive(Debug, Clone)]
pub enum SetSomeAccount {
Account(String),
NoAccount,
}
impl<'de> Deserialize<'de> for SetSomeAccount {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct SetSomeAccountVisitor;
impl<'de> Visitor<'de> for SetSomeAccountVisitor {
type Value = SetSomeAccount;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a Pubkey String or the String 'null'")
}
fn visit_some<D>(self, deserializer: D) -> std::result::Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
Deserialize::deserialize(deserializer).map(|v: String| match v.as_str() {
"null" => SetSomeAccount::NoAccount,
_ => SetSomeAccount::Account(v.to_string()),
})
}
}
deserializer.deserialize_option(SetSomeAccountVisitor)
}
}
impl Serialize for SetSomeAccount {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
SetSomeAccount::Account(val) => serializer.serialize_str(val),
SetSomeAccount::NoAccount => serializer.serialize_str("null"),
}
}
}
impl TokenAccountUpdate {
/// Apply the update to the account
pub fn apply(self, token_account: &mut TokenAccount) -> Result<()> {
if let Some(amount) = self.amount {
token_account.amount = amount;
}
if let Some(delegate) = self.delegate {
match delegate {
SetSomeAccount::Account(pubkey) => {
token_account.delegate = COption::Some(verify_pubkey(&pubkey)?);
}
SetSomeAccount::NoAccount => {
token_account.delegate = COption::None;
}
}
}
if let Some(state) = self.state {
token_account.state = match state.as_str() {
"uninitialized" => AccountState::Uninitialized,
"frozen" => AccountState::Frozen,
"initialized" => AccountState::Initialized,
_ => {
return Err(Error::invalid_params(format!(
"Invalid token account state: {}",
state
)))
}
};
}
if let Some(delegated_amount) = self.delegated_amount {
token_account.delegated_amount = delegated_amount;
}
if let Some(close_authority) = self.close_authority {
match close_authority {
SetSomeAccount::Account(pubkey) => {
token_account.close_authority = COption::Some(verify_pubkey(&pubkey)?);
}
SetSomeAccount::NoAccount => {
token_account.close_authority = COption::None;
}
}
}
Ok(())
}
}
#[rpc]
pub trait SvmTricksRpc {
type Metadata;
/// A "cheat code" method for developers to set or update an account in Surfpool.
///
/// This method allows developers to set or update the lamports, data, owner, executable status,
/// and rent epoch of a given account.
///
/// ## Parameters
/// - `meta`: Metadata passed with the request, such as the client's request context.
/// - `pubkey`: The public key of the account to be updated, as a base-58 encoded string.
/// - `update`: The `AccountUpdate` struct containing the fields to update the account.
///
/// ## Returns
/// A `RpcResponse<()>` indicating whether the account update was successful.
///
/// ## Example Request
/// ```json
/// {
/// "jsonrpc": "2.0",
/// "id": 1,
/// "method": "surfnet_setAccount",
/// "params": ["account_pubkey", {"lamports": 1000, "data": "base58string", "owner": "program_pubkey"}]
/// }
/// ```
///
/// ## Example Response
/// ```json
/// {
/// "jsonrpc": "2.0",
/// "result": {},
/// "id": 1
/// }
/// ```
///
/// # Notes
/// This method is designed to help developers set or modify account properties within Surfpool.
/// Developers can quickly test or update account attributes, such as lamports, program ownership, and executable status.
///
/// # See Also
/// - `getAccount`, `getAccountInfo`, `getAccountBalance`
#[rpc(meta, name = "surfnet_setAccount")]
fn set_account(
&self,
meta: Self::Metadata,
pubkey: String,
update: AccountUpdate,
) -> BoxFuture<Result<RpcResponse<()>>>;
/// A "cheat code" method for developers to set or update a token account in Surfpool.
///
/// This method allows developers to set or update various properties of a token account,
/// including the token amount, delegate, state, delegated amount, and close authority.
///
/// ## Parameters
/// - `meta`: Metadata passed with the request, such as the client's request context.
/// - `owner`: The base-58 encoded public key of the token account's owner.
/// - `mint`: The base-58 encoded public key of the token mint (e.g., the token type).
/// - `update`: The `TokenAccountUpdate` struct containing the fields to update the token account.
/// - `token_program`: The optional base-58 encoded address of the token program (defaults to the system token program).
///
/// ## Returns
/// A `RpcResponse<()>` indicating whether the token account update was successful.
///
/// ## Example Request
/// ```json
/// {
/// "jsonrpc": "2.0",
/// "id": 1,
/// "method": "surfnet_setTokenAccount",
/// "params": ["owner_pubkey", "mint_pubkey", {"amount": 1000, "state": "initialized"}]
/// }
/// ```
///
/// ## Example Response
/// ```json
/// {
/// "jsonrpc": "2.0",
/// "result": {},
/// "id": 1
/// }
/// ```
///
/// # Notes
/// This method is designed to help developers quickly test or modify token account properties in Surfpool.
/// Developers can update attributes such as token amounts, delegates, and authorities for specific token accounts.
///
/// # See Also
/// - `getTokenAccountInfo`, `getTokenAccountBalance`, `getTokenAccountDelegate`
#[rpc(meta, name = "surfnet_setTokenAccount")]
fn set_token_account(
&self,
meta: Self::Metadata,
owner: String,
mint: String,
update: TokenAccountUpdate,
token_program: Option<String>,
) -> BoxFuture<Result<RpcResponse<()>>>;
#[rpc(meta, name = "surfnet_cloneProgramAccount")]
fn clone_program_account(
&self,
meta: Self::Metadata,
source_program_id: String,
destination_program_id: String,
) -> BoxFuture<Result<RpcResponse<()>>>;
/// Estimates the compute units that a given transaction will consume.
///
/// This method simulates the transaction without committing its state changes
/// and returns an estimation of the compute units used, along with logs and
/// potential errors.
///
/// ## Parameters
/// - `meta`: Metadata passed with the request.
/// - `transaction_data`: A base64 encoded string of the `VersionedTransaction`.
/// - `tag`: An optional tag for the transaction.
///
/// ## Returns
/// A `RpcResponse<ProfileResult>` containing the estimation details.
///
/// ## Example Request
/// ```json
/// {
/// "jsonrpc": "2.0",
/// "id": 1,
/// "method": "surfnet_profileTransaction",
/// "params": ["base64_encoded_transaction_string", "optional_tag"]
/// }
/// ```
#[rpc(meta, name = "surfnet_profileTransaction")]
fn estimate_compute_units(
&self,
meta: Self::Metadata,
transaction_data: String, // Base64 encoded VersionedTransaction
tag: Option<String>, // Optional tag for the transaction
) -> BoxFuture<Result<RpcResponse<ProfileResult>>>;
/// Retrieves all profiling results for a given tag.
///
/// ## Parameters
/// - `meta`: Metadata passed with the request.
/// - `tag`: The tag to retrieve profiling results for.
///
/// ## Returns
/// A `RpcResponse<Vec<ProfileResult>>` containing the profiling results.
#[rpc(meta, name = "surfnet_getProfileResults")]
fn get_profile_results(
&self,
meta: Self::Metadata,
tag: String,
) -> Result<RpcResponse<Vec<ProfileResult>>>;
}
pub struct SurfnetCheatcodesRpc;
impl SvmTricksRpc for SurfnetCheatcodesRpc {
type Metadata = Option<RunloopContext>;
fn set_account(
&self,
meta: Self::Metadata,
pubkey_str: String,
update: AccountUpdate,
) -> BoxFuture<Result<RpcResponse<()>>> {
let pubkey = match verify_pubkey(&pubkey_str) {
Ok(res) => res,
Err(e) => return e.into(),
};
let account_update = match update.to_account() {
Err(e) => return Box::pin(future::err(e)),
Ok(res) => res,
};
let SurfnetRpcContext {
svm_locker,
remote_ctx,
} = match meta.get_rpc_context(CommitmentConfig::confirmed()) {
Ok(res) => res,
Err(e) => return e.into(),
};
Box::pin(async move {
// if the account update is contains all fields, we can directly set the account
let (account_to_set, latest_absolute_slot) = if let Some(account) = account_update {
(
GetAccountResult::FoundAccount(pubkey, account, true),
svm_locker.get_latest_absolute_slot(),
)
} else {
// otherwise, we need to fetch the account and apply the update
let SvmAccessContext {
slot, inner: mut account_to_update,
..
} = svm_locker.get_account(&remote_ctx, &pubkey, Some(Box::new(move |svm_locker| {
// if the account does not exist locally or in the remote, create a new account with default values
let _ = svm_locker.simnet_events_tx().send(SimnetEvent::info(format!(
"Account {pubkey} not found, creating a new account from default values"
)));
GetAccountResult::FoundAccount(
pubkey,
Account {
lamports: 0,
owner: system_program::id(),
executable: false,
rent_epoch: 0,
data: vec![],
},
true, // indicate that the account should be updated in the SVM, since it's new
)
}))).await?;
update.apply(&mut account_to_update)?;
(account_to_update, slot)
};
svm_locker.write_account_update(account_to_set);
Ok(RpcResponse {
context: RpcResponseContext::new(latest_absolute_slot),
value: (),
})
})
}
fn set_token_account(
&self,
meta: Self::Metadata,
owner_str: String,
mint_str: String,
update: TokenAccountUpdate,
some_token_program_str: Option<String>,
) -> BoxFuture<Result<RpcResponse<()>>> {
let owner = match verify_pubkey(&owner_str) {
Ok(res) => res,
Err(e) => return e.into(),
};
let mint = match verify_pubkey(&mint_str) {
Ok(res) => res,
Err(e) => return e.into(),
};
let token_program_id = match some_token_program_str {
Some(token_program_str) => match verify_pubkey(&token_program_str) {
Ok(res) => res,
Err(e) => return e.into(),
},
None => spl_token::id(),
};
let associated_token_account =
get_associated_token_address_with_program_id(&owner, &mint, &token_program_id);
let SurfnetRpcContext {
svm_locker,
remote_ctx,
} = match meta.get_rpc_context(CommitmentConfig::confirmed()) {
Ok(res) => res,
Err(e) => return e.into(),
};
Box::pin(async move {
let SvmAccessContext {
slot,
inner: mut token_account,
..
} = svm_locker
.get_account(
&remote_ctx,
&associated_token_account,
Some(Box::new(move |svm_locker| {
let minimum_rent = svm_locker.with_svm_reader(|svm_reader| {
svm_reader
.inner
.minimum_balance_for_rent_exemption(TokenAccount::LEN)
});
let mut data = [0; TokenAccount::LEN];
let default = TokenAccount {
mint,
owner,
state: AccountState::Initialized,
..Default::default()
};
default.pack_into_slice(&mut data);
GetAccountResult::FoundAccount(
associated_token_account,
Account {
lamports: minimum_rent,
owner: token_program_id,
executable: false,
rent_epoch: 0,
data: data.to_vec(),
},
true, // indicate that the account should be updated in the SVM, since it's new
)
})),
)
.await?;
let mut token_account_data = TokenAccount::unpack(token_account.expected_data())
.map_err(|e| {
Error::invalid_params(format!("Failed to unpack token account data: {}", e))
})?;
update.apply(&mut token_account_data)?;
let mut final_account_bytes = [0; TokenAccount::LEN];
token_account_data.pack_into_slice(&mut final_account_bytes);
token_account.apply_update(|account| {
account.data = final_account_bytes.to_vec();
Ok(())
})?;
svm_locker.write_account_update(token_account);
Ok(RpcResponse {
context: RpcResponseContext::new(slot),
value: (),
})
})
}
/// Clones a program account from one program ID to another.
/// A program account contains a pointer to a program data account, which is a PDA derived from the program ID.
/// So, when cloning a program account, we need to clone the program data account as well.
///
/// This method will:
/// 1. Get the program account for the source program ID.
/// 2. Get the program data account for the source program ID.
/// 3. Calculate the program data address for the destination program ID.
/// 4. Set the destination program account's data to point to the calculated destination program address.
/// 5. Copy the source program data account to the destination program data account.
fn clone_program_account(
&self,
meta: Self::Metadata,
source_program_id: String,
destination_program_id: String,
) -> BoxFuture<Result<RpcResponse<()>>> {
let source_program_id = match verify_pubkey(&source_program_id) {
Ok(res) => res,
Err(e) => return e.into(),
};
let destination_program_id = match verify_pubkey(&destination_program_id) {
Ok(res) => res,
Err(e) => return e.into(),
};
let SurfnetRpcContext {
svm_locker,
remote_ctx,
} = match meta.get_rpc_context(CommitmentConfig::confirmed()) {
Ok(res) => res,
Err(e) => return e.into(),
};
Box::pin(async move {
let SvmAccessContext { slot, .. } = svm_locker
.clone_program_account(&remote_ctx, &source_program_id, &destination_program_id)
.await?;
Ok(RpcResponse {
context: RpcResponseContext::new(slot),
value: (),
})
})
}
fn estimate_compute_units(
&self,
meta: Self::Metadata,
transaction_data_b64: String,
tag: Option<String>,
) -> BoxFuture<Result<RpcResponse<ProfileResult>>> {
let svm_locker = match meta.get_svm_locker() {
Ok(locker) => locker,
Err(e) => return e.into(),
};
let transaction_bytes = match STANDARD.decode(&transaction_data_b64) {
Ok(bytes) => bytes,
Err(e) => {
log::error!("Base64 decoding failed: {}", e);
let error_cu_result = ComputeUnitsEstimationResult {
success: false,
compute_units_consumed: 0,
log_messages: None,
error_message: Some(format!("Invalid base64 for transaction data: {}", e)),
};
return Box::pin(future::ok(RpcResponse {
context: RpcResponseContext::new(0),
value: ProfileResult {
compute_units: error_cu_result,
},
}));
}
};
let transaction: VersionedTransaction = match bincode::deserialize(&transaction_bytes) {
Ok(tx) => tx,
Err(e) => {
let error_cu_result = ComputeUnitsEstimationResult {
success: false,
compute_units_consumed: 0,
log_messages: None,
error_message: Some(format!("Failed to deserialize transaction: {}", e)),
};
return Box::pin(future::ok(RpcResponse {
context: RpcResponseContext::new(0),
value: ProfileResult {
compute_units: error_cu_result,
},
}));
}
};
Box::pin(async move {
let SvmAccessContext {
slot,
inner: estimation_result,
..
} = svm_locker.estimate_compute_units(&transaction);
if let Some(tag_str) = tag {
if estimation_result.success {
svm_locker.write_profiling_results(
tag_str,
ProfileResult {
compute_units: estimation_result.clone(),
},
);
}
}
Ok(RpcResponse {
context: RpcResponseContext::new(slot),
value: ProfileResult {
compute_units: estimation_result,
},
})
})
}
fn get_profile_results(
&self,
meta: Self::Metadata,
tag: String,
) -> Result<RpcResponse<Vec<ProfileResult>>> {
meta.with_svm_reader(|svm_reader| {
let results = svm_reader
.tagged_profiling_results
.get(&tag)
.cloned()
.unwrap_or_default();
RpcResponse {
context: RpcResponseContext::new(svm_reader.get_latest_absolute_slot()),
value: results,
}
})
.map_err(Into::into)
}
}