bittensor-rs 0.1.1

Standalone Rust SDK for Bittensor blockchain interactions
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
//! # Subnet Extrinsics
//!
//! Extrinsics for managing subnets on the Bittensor network:
//! - `register_network`: Register a new subnet
//! - `register_network_with_identity`: Register with identity info
//! - `set_subnet_identity`: Update subnet identity

use crate::api::api;
use crate::error::BittensorError;
use crate::extrinsics::ExtrinsicResponse;
use subxt::OnlineClient;
use subxt::PolkadotConfig;
use tracing::{debug, warn};

/// Subnet identity information
#[derive(Debug, Clone, Default)]
pub struct SubnetIdentity {
    /// Subnet name
    pub name: String,
    /// GitHub repository URL
    pub github_repo: String,
    /// Contact email
    pub contact: String,
    /// Subnet description
    pub description: String,
    /// Subnet URL
    pub url: String,
    /// Discord invite
    pub discord: String,
    /// Logo URL
    pub logo_url: String,
    /// Additional info
    pub additional: String,
}

impl SubnetIdentity {
    /// Create a new subnet identity with just a name
    ///
    /// # Example
    ///
    /// ```
    /// use bittensor_rs::extrinsics::SubnetIdentity;
    ///
    /// let identity = SubnetIdentity::new("My Subnet");
    /// assert_eq!(identity.name, "My Subnet");
    /// ```
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            ..Default::default()
        }
    }

    /// Set the GitHub repository URL
    pub fn with_github(mut self, repo: impl Into<String>) -> Self {
        self.github_repo = repo.into();
        self
    }

    /// Set the contact email
    pub fn with_contact(mut self, contact: impl Into<String>) -> Self {
        self.contact = contact.into();
        self
    }

    /// Set the description
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Set the URL
    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        self.url = url.into();
        self
    }

    /// Set the Discord invite
    pub fn with_discord(mut self, discord: impl Into<String>) -> Self {
        self.discord = discord.into();
        self
    }

    /// Set the logo URL
    pub fn with_logo(mut self, logo: impl Into<String>) -> Self {
        self.logo_url = logo.into();
        self
    }
}

/// Register a new subnet on the network
///
/// This creates a new subnet by paying the registration cost.
/// The subnet netuid is returned on success by parsing the `NetworkAdded` event.
///
/// # Arguments
///
/// * `client` - The subxt client
/// * `signer` - The signer (coldkey)
///
/// # Returns
///
/// The newly registered subnet netuid extracted from the NetworkAdded event
///
/// # Errors
///
/// Returns an error if:
/// - Transaction submission fails
/// - Transaction is not finalized successfully
/// - NetworkAdded event is not found in the transaction events
pub async fn register_network<S>(
    client: &OnlineClient<PolkadotConfig>,
    signer: &S,
) -> Result<ExtrinsicResponse<u16>, BittensorError>
where
    S: subxt::tx::Signer<PolkadotConfig>,
{
    let call = api::tx()
        .subtensor_module()
        .register_network(signer.account_id());

    debug!("Submitting register_network transaction");

    // Submit and watch the transaction to get events
    let tx_progress = client
        .tx()
        .sign_and_submit_then_watch_default(&call, signer)
        .await
        .map_err(|e| BittensorError::TxSubmissionError {
            message: format!("Failed to submit register_network: {}", e),
        })?;

    let tx_hash = tx_progress.extrinsic_hash();
    debug!("Transaction submitted with hash: {:?}", tx_hash);

    // Wait for finalization and get events
    let tx_events = tx_progress
        .wait_for_finalized_success()
        .await
        .map_err(|e| {
            warn!("Transaction finalization failed: {}", e);
            BittensorError::TxFinalizationError {
                reason: format!("register_network transaction failed: {}", e),
            }
        })?;

    debug!("Transaction finalized successfully");

    // Find the NetworkAdded event to extract the netuid
    // NetworkAdded event has format: NetworkAdded(netuid: u16, modality: u16)
    let network_added_event = tx_events
        .find_first::<api::subtensor_module::events::NetworkAdded>()
        .map_err(|e| {
            warn!("Failed to decode NetworkAdded event: {}", e);
            BittensorError::ChainError {
                message: format!("Failed to decode NetworkAdded event: {}", e),
            }
        })?;

    match network_added_event {
        Some(event) => {
            let netuid = event.0;
            debug!(
                "NetworkAdded event found: netuid={}, modality={}",
                netuid, event.1
            );
            Ok(ExtrinsicResponse::success()
                .with_message("Network registered successfully")
                .with_extrinsic_hash(&format!("{:?}", tx_hash))
                .with_data(netuid))
        }
        None => {
            warn!("NetworkAdded event not found in transaction events");
            // Log all events for debugging
            for event in tx_events.iter().flatten() {
                debug!(
                    "Event found: {}::{}",
                    event.pallet_name(),
                    event.variant_name()
                );
            }
            Err(BittensorError::ChainError {
                message: "NetworkAdded event not found - network may not have been registered"
                    .to_string(),
            })
        }
    }
}

/// Register a new subnet with identity information
///
/// This creates a new subnet with associated metadata.
/// The subnet netuid is returned on success by parsing the `NetworkAdded` event.
///
/// # Arguments
///
/// * `client` - The subxt client
/// * `signer` - The signer (coldkey)
/// * `identity` - Subnet identity information
///
/// # Returns
///
/// The newly registered subnet netuid extracted from the NetworkAdded event
///
/// # Errors
///
/// Returns an error if:
/// - Transaction submission fails
/// - Transaction is not finalized successfully
/// - NetworkAdded event is not found in the transaction events
pub async fn register_network_with_identity<S>(
    client: &OnlineClient<PolkadotConfig>,
    signer: &S,
    identity: SubnetIdentity,
) -> Result<ExtrinsicResponse<u16>, BittensorError>
where
    S: subxt::tx::Signer<PolkadotConfig>,
{
    // Save name for logging before consuming identity
    let subnet_name = identity.name.clone();

    // Convert to API type
    let api_identity = api::runtime_types::pallet_subtensor::pallet::SubnetIdentityV3 {
        subnet_name: identity.name.into_bytes(),
        github_repo: identity.github_repo.into_bytes(),
        subnet_contact: identity.contact.into_bytes(),
        subnet_url: identity.url.into_bytes(),
        discord: identity.discord.into_bytes(),
        description: identity.description.into_bytes(),
        logo_url: identity.logo_url.into_bytes(),
        additional: identity.additional.into_bytes(),
    };

    let call = api::tx()
        .subtensor_module()
        .register_network_with_identity(signer.account_id(), Some(api_identity));

    debug!(
        "Submitting register_network_with_identity transaction for '{}'",
        subnet_name
    );

    // Submit and watch the transaction to get events
    let tx_progress = client
        .tx()
        .sign_and_submit_then_watch_default(&call, signer)
        .await
        .map_err(|e| BittensorError::TxSubmissionError {
            message: format!("Failed to submit register_network_with_identity: {}", e),
        })?;

    let tx_hash = tx_progress.extrinsic_hash();
    debug!("Transaction submitted with hash: {:?}", tx_hash);

    // Wait for finalization and get events
    let tx_events = tx_progress
        .wait_for_finalized_success()
        .await
        .map_err(|e| {
            warn!("Transaction finalization failed: {}", e);
            BittensorError::TxFinalizationError {
                reason: format!("register_network_with_identity transaction failed: {}", e),
            }
        })?;

    debug!("Transaction finalized successfully");

    // Find the NetworkAdded event to extract the netuid
    let network_added_event = tx_events
        .find_first::<api::subtensor_module::events::NetworkAdded>()
        .map_err(|e| {
            warn!("Failed to decode NetworkAdded event: {}", e);
            BittensorError::ChainError {
                message: format!("Failed to decode NetworkAdded event: {}", e),
            }
        })?;

    match network_added_event {
        Some(event) => {
            let netuid = event.0;
            debug!(
                "NetworkAdded event found: netuid={}, modality={}",
                netuid, event.1
            );
            Ok(ExtrinsicResponse::success()
                .with_message("Network registered with identity successfully")
                .with_extrinsic_hash(&format!("{:?}", tx_hash))
                .with_data(netuid))
        }
        None => {
            warn!("NetworkAdded event not found in transaction events");
            // Log all events for debugging
            for event in tx_events.iter().flatten() {
                debug!(
                    "Event found: {}::{}",
                    event.pallet_name(),
                    event.variant_name()
                );
            }
            Err(BittensorError::ChainError {
                message: "NetworkAdded event not found - network may not have been registered"
                    .to_string(),
            })
        }
    }
}

/// Set or update subnet identity information
///
/// # Arguments
///
/// * `client` - The subxt client
/// * `signer` - The signer (subnet owner coldkey)
/// * `netuid` - The subnet netuid
/// * `identity` - New identity information
pub async fn set_subnet_identity<S>(
    client: &OnlineClient<PolkadotConfig>,
    signer: &S,
    netuid: u16,
    identity: SubnetIdentity,
) -> Result<ExtrinsicResponse<()>, BittensorError>
where
    S: subxt::tx::Signer<PolkadotConfig>,
{
    let call = api::tx().subtensor_module().set_subnet_identity(
        netuid,
        identity.name.into_bytes(),
        identity.github_repo.into_bytes(),
        identity.contact.into_bytes(),
        identity.url.into_bytes(),
        identity.discord.into_bytes(),
        identity.description.into_bytes(),
        identity.logo_url.into_bytes(),
        identity.additional.into_bytes(),
    );

    let tx_hash = client
        .tx()
        .sign_and_submit_default(&call, signer)
        .await
        .map_err(|e| BittensorError::TxSubmissionError {
            message: format!("Failed to set subnet identity: {}", e),
        })?;

    Ok(ExtrinsicResponse::success()
        .with_message("Subnet identity updated")
        .with_extrinsic_hash(&format!("{:?}", tx_hash))
        .with_data(()))
}

/// Register in the root network (netuid 0)
///
/// This registers a hotkey in the root network for senate voting.
///
/// # Arguments
///
/// * `client` - The subxt client
/// * `signer` - The signer (coldkey)
/// * `hotkey` - The hotkey to register
pub async fn root_register<S>(
    client: &OnlineClient<PolkadotConfig>,
    signer: &S,
    hotkey: crate::AccountId,
) -> Result<ExtrinsicResponse<()>, BittensorError>
where
    S: subxt::tx::Signer<PolkadotConfig>,
{
    let call = api::tx().subtensor_module().root_register(hotkey);

    let tx_hash = client
        .tx()
        .sign_and_submit_default(&call, signer)
        .await
        .map_err(|e| BittensorError::TxSubmissionError {
            message: format!("Failed to root register: {}", e),
        })?;

    Ok(ExtrinsicResponse::success()
        .with_message("Root registration successful")
        .with_extrinsic_hash(&format!("{:?}", tx_hash))
        .with_data(()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_subnet_identity_new() {
        let identity = SubnetIdentity::new("Test Subnet");
        assert_eq!(identity.name, "Test Subnet");
        assert!(identity.github_repo.is_empty());
    }

    #[test]
    fn test_subnet_identity_builder() {
        let identity = SubnetIdentity::new("My Subnet")
            .with_github("https://github.com/example/subnet")
            .with_contact("admin@example.com")
            .with_description("A test subnet")
            .with_url("https://example.com")
            .with_discord("abc123")
            .with_logo("https://example.com/logo.png");

        assert_eq!(identity.name, "My Subnet");
        assert_eq!(identity.github_repo, "https://github.com/example/subnet");
        assert_eq!(identity.contact, "admin@example.com");
        assert_eq!(identity.description, "A test subnet");
        assert_eq!(identity.url, "https://example.com");
        assert_eq!(identity.discord, "abc123");
        assert_eq!(identity.logo_url, "https://example.com/logo.png");
    }

    #[test]
    fn test_subnet_identity_default() {
        let identity = SubnetIdentity::default();
        assert!(identity.name.is_empty());
        assert!(identity.github_repo.is_empty());
    }

    #[test]
    fn test_subnet_identity_clone() {
        let identity = SubnetIdentity::new("Test").with_github("https://github.com/test");
        let cloned = identity.clone();
        assert_eq!(identity.name, cloned.name);
        assert_eq!(identity.github_repo, cloned.github_repo);
    }

    #[test]
    fn test_subnet_identity_debug() {
        let identity = SubnetIdentity::new("Test");
        let debug = format!("{:?}", identity);
        assert!(debug.contains("SubnetIdentity"));
        assert!(debug.contains("Test"));
    }
}