txtx_addon_network_svm/codec/
utils.rs1use std::{str::FromStr, thread::sleep, time::Duration};
2
3use solana_client::nonblocking::rpc_client::RpcClient;
4use solana_clock::DEFAULT_MS_PER_SLOT;
5use solana_loader_v3_interface::{get_program_data_address, state::UpgradeableLoaderState};
6use solana_pubkey::Pubkey;
7
8use txtx_addon_kit::types::{diagnostics::Diagnostic, types::Value};
9use txtx_addon_network_svm_types::anchor::types::Idl;
10
11use crate::commands::setup_surfnet::set_account::SurfpoolAccountUpdate;
12use crate::commands::setup_surfnet::surfnet_update::SurfnetAccountUpdate;
13
14pub fn get_seeds_from_value(value: &Value) -> Result<Vec<Vec<u8>>, Diagnostic> {
15 let seeds = value
16 .as_array()
17 .ok_or_else(|| diagnosed_error!("seeds must be an array"))?
18 .iter()
19 .map(|s| {
20 let bytes = s.to_le_bytes();
21 if bytes.is_empty() {
22 return Err(diagnosed_error!("seed cannot be empty"));
23 }
24 if bytes.len() > 32 {
25 if let Ok(pubkey) = Pubkey::from_str(&s.to_string()) {
26 return Ok(pubkey.to_bytes().to_vec());
27 } else {
28 return Err(diagnosed_error!("seed cannot be longer than 32 bytes",));
29 }
30 }
31 Ok(bytes)
32 })
33 .collect::<Result<Vec<_>, _>>()?;
34
35 if seeds.len() > 16 {
36 return Err(diagnosed_error!("seeds a maximum of 16 seeds can be used"));
37 }
38
39 Ok(seeds)
40}
41
42pub async fn cheatcode_deploy_program(
43 rpc_client: &RpcClient,
44 program_id: Pubkey,
45 data: &Vec<u8>,
46 upgrade_authority: Option<Pubkey>,
47) -> Result<(), Diagnostic> {
48 let program_data_address = get_program_data_address(&program_id);
49 let rent_lamports = rpc_client
50 .get_minimum_balance_for_rent_exemption(data.len())
51 .await
52 .map_err(|e| diagnosed_error!("failed to get rent exemption: {e}"))?;
53
54 let slot = rpc_client
55 .get_slot()
56 .await
57 .map_err(|e| diagnosed_error!("failed to get current slot: {e}"))?;
58
59 let mut program_data = bincode::serialize(&UpgradeableLoaderState::ProgramData {
60 slot,
61 upgrade_authority_address: Some(upgrade_authority.unwrap_or_default()),
64 })
65 .map_err(|e| diagnosed_error!("failed to serialize program data state: {e}"))?;
66 program_data.extend(data);
67
68 let program_data_address_payload = SurfpoolAccountUpdate {
69 public_key: program_data_address,
70 lamports: Some(rent_lamports),
71 data: Some(txtx_addon_kit::hex::encode(program_data)),
72 owner: Some(solana_sdk_ids::bpf_loader_upgradeable::id().to_string()),
73 executable: Some(false),
74 rent_epoch: Some(0),
75 };
76
77 let program_data = bincode::serialize(&UpgradeableLoaderState::Program {
78 programdata_address: program_data_address,
79 })
80 .map_err(|e| diagnosed_error!("failed to serialize program state: {e}"))?;
81
82 let rent_lamports = rpc_client
83 .get_minimum_balance_for_rent_exemption(program_data.len())
84 .await
85 .map_err(|e| diagnosed_error!("failed to get rent exemption: {e}"))?;
86 let program_payload = SurfpoolAccountUpdate {
87 public_key: program_id,
88 lamports: Some(rent_lamports),
89 data: Some(txtx_addon_kit::hex::encode(&program_data)),
90 owner: Some(solana_sdk_ids::bpf_loader_upgradeable::id().to_string()),
91 executable: Some(true),
92 rent_epoch: Some(0),
93 };
94
95 program_data_address_payload.send_request(&rpc_client).await?;
96
97 program_payload.send_request(&rpc_client).await?;
98
99 Ok(())
100}
101
102pub fn cheatcode_register_idl(
103 rpc_client: &solana_client::rpc_client::RpcClient,
104 idl: &Idl,
105) -> Result<serde_json::Value, Diagnostic> {
106 let value = serde_json::to_value(idl).unwrap();
107 let params = serde_json::to_value(&vec![value]).unwrap();
108 send_rpc_request(rpc_client, "surfnet_registerIdl", params)
109}
110
111pub fn send_rpc_request(
112 rpc_client: &solana_client::rpc_client::RpcClient,
113 method: &'static str,
114 params: serde_json::Value,
115) -> Result<serde_json::Value, Diagnostic> {
116 rpc_client
117 .send::<serde_json::Value>(
118 solana_client::rpc_request::RpcRequest::Custom { method },
119 params,
120 )
121 .map_err(|e| diagnosed_error!("`{}` RPC call failed: {e}", method))
122}
123
124pub async fn cheatcode_register_idl_async(
125 rpc_client: &RpcClient,
126 idl: &Idl,
127) -> Result<serde_json::Value, Diagnostic> {
128 let value = serde_json::to_value(idl).unwrap();
129 let params = serde_json::to_value(&vec![value]).unwrap();
130 send_rpc_request_async(rpc_client, "surfnet_registerIdl", params).await
131}
132
133pub async fn send_rpc_request_async(
134 rpc_client: &RpcClient,
135 method: &'static str,
136 params: serde_json::Value,
137) -> Result<serde_json::Value, Diagnostic> {
138 rpc_client
139 .send::<serde_json::Value>(
140 solana_client::rpc_request::RpcRequest::Custom { method },
141 params,
142 )
143 .await
144 .map_err(|e| diagnosed_error!("`{}` RPC call failed: {e}", method))
145}
146
147pub fn wait_n_slots(rpc_client: &solana_client::rpc_client::RpcClient, n: u64) -> u64 {
148 let slot = rpc_client.get_slot().unwrap();
149 loop {
150 sleep(Duration::from_millis(DEFAULT_MS_PER_SLOT));
151 let new_slot = rpc_client.get_slot().unwrap();
152 if new_slot.saturating_sub(slot) >= n {
153 return new_slot;
154 }
155 }
156}