# Bittensor - Decentralized Machine Learning Network

## Description

Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs.

## Bittensor RPC plans and rate limits

- **Free plan:** 20 responses per second, up to 100,000 responses a day.
- **Plans:** $49/mo, $299/mo, $999/mo with 25M, 150M, and 500M included responses. Overages billed at $5/$3/$2 per million responses respectively.
- **Paid rate limits:** 100 to 5,000 responses per second (bursts from 500 to 10,000), no daily limit.
- **Billing:** 1 response = 1 API credit on every shared plan, over HTTPS or WebSocket (WSS) where Bittensor supports it.

Details: [Pricing](https://www.dwellir.com/docs/getting-started/pricing) · [Rate limits](https://www.dwellir.com/docs/getting-started/rate-limits) · [Authentication](https://www.dwellir.com/docs/getting-started/authentication) · [Archive nodes](https://www.dwellir.com/docs/getting-started/archive-nodes)

## Why Build on Bittensor?

Bittensor is a revolutionary blockchain that creates a decentralized marketplace for machine learning models and computational intelligence. Built on Substrate, Bittensor enables:

### **AI-Native Blockchain**

- **Decentralized ML** - Train and serve models in a trustless environment
- **Incentivized Intelligence** - Earn TAO tokens for contributing compute and models
- **Collaborative Learning** - Models improve through network-wide collaboration

### **Advanced Capabilities**

- **Neural Mining** - Mine TAO tokens by running AI models
- **36+ Subnets** - Specialized networks for different AI tasks (expanding to 1024)
- **Yuma Consensus** - Novel consensus mechanism for ML validation

### **Innovation Platform**

- **Open AI Marketplace** - Access diverse AI models and services
- **Composable Intelligence** - Build complex AI systems from network primitives
- **Research Network** - Contribute to cutting-edge ML research

## Quick Start with Bittensor

Connect to Bittensor in seconds with Dwellir's optimized endpoints:

### Installation & Setup

Ethers.js v6
Web3.js
Python

```javascript
import { JsonRpcProvider } from 'ethers';

// Connect to Bittensor mainnet
const provider = new JsonRpcProvider(
  'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'
);

// Get the latest block
const block = await provider.getBlock('latest');
console.log('Latest block:', block.number);

// Query account balance
const balance = await provider.getBalance('0x...');
console.log('Balance:', balance.toString());
```

```javascript
const Web3 = require('web3');

// Connect to Bittensor mainnet
const web3 = new Web3(
  'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'
);

// Get chain ID to verify connection
const chainId = await web3.eth.getChainId();
console.log('Connected to Bittensor:', chainId);

// Get gas price for optimal transaction pricing
const gasPrice = await web3.eth.getGasPrice();
console.log('Current gas price:', gasPrice);
```

```python
from web3 import Web3

# Connect to Bittensor mainnet
w3 = Web3(Web3.HTTPProvider(
    'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'
))

# Check connection
if w3.is_connected():
    print("Connected to Bittensor")

# Get latest block
latest_block = w3.eth.block_number
print(f"Latest block: {latest_block}")

# Get account balance
balance = w3.eth.get_balance('0x...')
print(f"Balance: {balance} TAO")
```

## Network Information

| Parameter    | Value      | Details         |
| ------------ | ---------- | --------------- |
| Chain ID     | N/A        | Substrate-based |
| Block Time   | 12 seconds | Average         |
| Native Token | TAO        | 21M max supply  |
| Consensus    | Yuma       | ML Validation   |

## API Reference

Bittensor exposes both an Ethereum-compatible JSON-RPC (via Frontier) and native Substrate RPC. Use either or both depending on your integration.

### Custom RPC Extensions

Bittensor nodes also expose custom RPC namespaces for chain‑specific AI/ML data:

- `subnetInfo_*`: subnet configuration, hyperparameters, metagraphs
- `neuronInfo_*`: neuron and mechagraph data
- `delegateInfo_*`: delegation and delegate details
- `swap_*`: TAO and ALPHA swap simulation helpers

These are implemented by the chain and surfaced over JSON‑RPC; see the runtime and node RPC code for details. Refer to the links in the Resources section below.

## Common Integration Patterns

### **Subnet Interaction**

Connect to Bittensor subnets for specialized AI tasks:

```javascript
// Query subnet information
async function getSubnetInfo(subnetId) {
  const result = await provider.call({
    to: SUBNET_REGISTRY_ADDRESS,
    data: encodeSubnetQuery(subnetId)
  });

  return decodeSubnetInfo(result);
}

// Register as miner
async function registerMiner(subnetId, modelEndpoint) {
  const tx = {
    to: SUBNET_REGISTRY_ADDRESS,
    data: encodeMinerRegistration(subnetId, modelEndpoint),
    value: REGISTRATION_FEE
  };

  const receipt = await signer.sendTransaction(tx);
  return receipt;
}
```

### **TAO Token Operations**

Manage TAO tokens and staking:

```javascript
// Stake TAO tokens
async function stakeTAO(amount, validatorAddress) {
  const stakingContract = new Contract(
    STAKING_CONTRACT_ADDRESS,
    STAKING_ABI,
    signer
  );

  const tx = await stakingContract.stake(
    validatorAddress,
    { value: parseEther(amount) }
  );

  return tx.wait();
}

// Query staking rewards
async function getStakingRewards(address) {
  const rewards = await stakingContract.pendingRewards(address);
  return formatUnits(rewards, 9); // TAO has 9 decimals
}
```

### **Model Validation**

Validate AI model outputs on-chain:

```javascript
// Submit model output for validation
async function submitModelOutput(subnetId, taskId, output) {
  const validationContract = new Contract(
    VALIDATION_CONTRACT_ADDRESS,
    VALIDATION_ABI,
    signer
  );

  const proof = generateProof(output);
  const tx = await validationContract.submitOutput(
    subnetId,
    taskId,
    output,
    proof
  );

  return tx.wait();
}
```

## Performance Best Practices

### 1. **Efficient Querying**

Optimize queries for Bittensor's unique architecture:

```javascript
// Batch subnet queries
async function batchSubnetQueries(subnetIds) {
  const queries = subnetIds.map(id => ({
    to: SUBNET_REGISTRY_ADDRESS,
    data: encodeSubnetQuery(id)
  }));

  const results = await Promise.all(
    queries.map(q => provider.call(q))
  );

  return results.map(decodeSubnetInfo);
}
```

### 2. **Caching Strategy**

Cache frequently accessed subnet and model data:

```javascript
class SubnetCache {
  constructor(ttl = 60000) { // 1 minute TTL
    this.cache = new Map();
    this.ttl = ttl;
  }

  async get(subnetId, fetcher) {
    const key = `subnet_${subnetId}`;
    const cached = this.cache.get(key);

    if (cached && Date.now() - cached.timestamp < this.ttl) {
      return cached.data;
    }

    const data = await fetcher(subnetId);
    this.cache.set(key, { data, timestamp: Date.now() });
    return data;
  }
}
```

### 3. **Connection Management**

Maintain persistent connections for real-time updates:

```javascript
// WebSocket connection for real-time updates
const wsProvider = new WebSocketProvider(
  'wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'
);

// Subscribe to subnet events
wsProvider.on('subnet_update', (event) => {
  console.log('Subnet updated:', event);
});
```

## Troubleshooting Common Issues

### Error: "Invalid subnet ID"

Ensure you're using valid subnet identifiers:

```javascript
// Validate subnet ID before operations
async function validateSubnet(subnetId) {
  const exists = await provider.call({
    to: SUBNET_REGISTRY_ADDRESS,
    data: encodeSubnetExists(subnetId)
  });

  if (!exists) {
    throw new Error(`Subnet ${subnetId} does not exist`);
  }

  return true;
}
```

### Error: "Insufficient stake"

Check staking requirements before operations:

```javascript
// Check minimum stake requirement
async function checkStakeRequirement(operation) {
  const required = await getMinimumStake(operation);
  const current = await getUserStake(address);

  if (current < required) {
    throw new Error(`Need ${required - current} more TAO staked`);
  }
}
```

## Resources & Tools

### Official Resources

- [Bittensor Documentation](https://docs.bittensor.com)
- [Taostats Explorer](https://taostats.io)
- [Bittensor GitHub](https://github.com/opentensor/bittensor)

### Developer Tools

- [Bittensor SDK](https://pypi.org/project/bittensor/)
- [Subnet Template](https://github.com/opentensor/subnet-template)

### Need Help?

- **Email**: <support@dwellir.com>
- **Docs**: You're here!
- **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)

***

*Start building on Bittensor with Dwellir's enterprise-grade RPC infrastructure. [Get your API key](https://dashboard.dwellir.com/register)*
