# IoTeX - The Leading Blockchain for IoT and DePIN

## IoTeX 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 IoTeX 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 IoTeX?

IoTeX is the leading blockchain platform for Internet of Things (IoT) and Decentralized Physical Infrastructure Networks (DePIN). Purpose-built for connecting the physical and digital worlds, IoTeX offers:

### **IoT & Machine Integration**

- **Native device connectivity** - Direct integration with billions of IoT devices
- **W3bstream** - Off-chain compute for real-world data processing
- **MachineFi** - Financialize machine resources and data
- **Trusted IoT data** - Verifiable proofs for device-generated data

### **High Performance Infrastructure**

- **5-second block time** - Fast finality for real-time applications
- **Ultra-low fees** - Optimized for high-frequency IoT transactions
- **10,000+ TPS** - Scale for billions of device interactions
- **EVM compatibility** - Deploy existing Ethereum dApps instantly

### **Privacy & Security**

- **Roll-DPoS consensus** - Randomized delegated proof-of-stake
- **Trusted Execution Environment** - Secure computation for sensitive data
- **Privacy-preserving computation** - Process data without exposure
- **Device identity** - Decentralized identity for IoT devices

### **DePIN Ecosystem Leader**

- **$3B+ market cap** - Top DePIN infrastructure blockchain
- **100+ DePIN projects** - Largest decentralized infrastructure ecosystem
- **Real-world assets** - Tokenize and trade physical infrastructure
- **Global device network** - Connected devices across 70+ countries

## Quick Start with IoTeX

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

### Installation & Setup

Ethers.js v6
Web3.js
Viem

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

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

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

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

// Interact with IoT device registry
const deviceRegistry = new Contract(registryAddress, abi, provider);
const deviceData = await deviceRegistry.getDeviceData('device_id');
```

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

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

// Verify connection to IoTeX (Chain ID: 4689)
const chainId = await web3.eth.getChainId();
console.log('Connected to IoTeX:', chainId === 4689);

// Get gas price optimized for IoT transactions
const gasPrice = await web3.eth.getGasPrice();
console.log('IoT-optimized gas price:', gasPrice);

// Read IoT sensor data from smart contract
const sensorContract = new web3.eth.Contract(abi, contractAddress);
const data = await sensorContract.methods.getLatestReading().call();
```

```typescript
import { createPublicClient, http, defineChain } from 'viem';

// Define IoTeX chain
const iotex = defineChain({
  id: 4689,
  name: 'IoTeX',
  network: 'iotex',
  nativeCurrency: {
    decimals: 18,
    name: 'IoTeX',
    symbol: 'IOTX',
  },
  rpcUrls: {
    default: {
      http: ['https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'],
    },
  },
  blockExplorers: {
    default: { name: 'IoTeXScan', url: 'https://iotexscan.io' },
  },
});

// Create IoTeX client
const client = createPublicClient({
  chain: iotex,
  transport: http(),
});

// Read IoT device data
const deviceStatus = await client.readContract({
  address: '0x...',
  abi: deviceAbi,
  functionName: 'getDeviceStatus',
  args: ['device_001'],
});
```

## Network Information

| Parameter  | Value     | Details         |
| ---------- | --------- | --------------- |
| Chain ID   | 4689      | Mainnet         |
| Block Time | 5 seconds | Average         |
| Gas Token  | IOTX      | Native token    |
| Consensus  | Roll-DPoS | Randomized DPoS |

## API Reference

IoTeX supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/) plus custom methods for IoT and DePIN functionality. Access all standard EVM methods for seamless integration.

## IoT & DePIN Integration Patterns

### Device Registration & Management

Register and manage IoT devices on-chain:

```javascript
// Device registration contract
const DeviceRegistry = {
  // Register new IoT device
  async registerDevice(deviceId, metadata) {
    const tx = await contract.registerDevice(
      deviceId,
      metadata.manufacturer,
      metadata.model,
      metadata.location,
      { gasLimit: 100000 }
    );
    return tx.wait();
  },

  // Update device status
  async updateDeviceStatus(deviceId, status, timestamp) {
    const signature = await signDeviceData(deviceId, status, timestamp);
    return contract.updateStatus(deviceId, status, timestamp, signature);
  },

  // Query device history
  async getDeviceHistory(deviceId, fromBlock = 0) {
    const filter = contract.filters.DeviceUpdate(deviceId);
    return contract.queryFilter(filter, fromBlock);
  }
};
```

### W3bstream Data Processing

Process IoT data off-chain with verifiable proofs:

```javascript
// W3bstream integration for IoT data
class W3bstreamProcessor {
  constructor(endpoint) {
    this.endpoint = endpoint;
    this.provider = new JsonRpcProvider(
      'https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'
    );
  }

  // Submit IoT data for processing
  async submitData(deviceId, data) {
    // Create data proof
    const proof = await this.createProof(deviceId, data);

    // Submit to W3bstream
    const result = await fetch(`${this.endpoint}/submit`, {
      method: 'POST',
      body: JSON.stringify({
        deviceId,
        data,
        proof,
        timestamp: Date.now()
      })
    });

    // Store proof on-chain
    const tx = await this.storeProof(proof);
    return { proofId: tx.hash, result: await result.json() };
  }

  // Verify data authenticity
  async verifyData(proofId) {
    const proof = await this.contract.getProof(proofId);
    return this.verifyProof(proof);
  }
}
```

### DePIN Infrastructure

Build decentralized physical infrastructure:

```javascript
// DePIN node management
const DePINManager = {
  // Register infrastructure node
  async registerNode(nodeInfo) {
    const stake = ethers.parseEther('1000'); // Minimum stake

    const tx = await contract.registerNode(
      nodeInfo.id,
      nodeInfo.type, // 'sensor', 'gateway', 'compute'
      nodeInfo.location,
      nodeInfo.capabilities,
      { value: stake }
    );

    return tx.wait();
  },

  // Submit proof of work
  async submitProofOfWork(nodeId, data) {
    const proof = await generateWorkProof(nodeId, data);
    return contract.submitProof(nodeId, proof);
  },

  // Claim rewards
  async claimRewards(nodeId) {
    const rewards = await contract.pendingRewards(nodeId);
    if (rewards > 0) {
      return contract.claimRewards(nodeId);
    }
  }
};
```

## Performance Best Practices

### 1. **Batch IoT Data Submissions**

Optimize for high-frequency sensor data:

```javascript
class BatchProcessor {
  constructor() {
    this.batch = [];
    this.batchSize = 100;
  }

  async addReading(deviceId, data) {
    this.batch.push({ deviceId, data, timestamp: Date.now() });

    if (this.batch.length >= this.batchSize) {
      await this.submitBatch();
    }
  }

  async submitBatch() {
    if (this.batch.length === 0) return;

    const merkleRoot = this.calculateMerkleRoot(this.batch);

    // Submit only merkle root on-chain
    const tx = await contract.submitBatch(
      merkleRoot,
      this.batch.length,
      { gasLimit: 200000 }
    );

    // Store full data off-chain
    await this.storeOffchain(this.batch, tx.hash);

    this.batch = [];
    return tx;
  }
}
```

### 2. **Device Connection Pooling**

Manage multiple IoT device connections efficiently:

```javascript
class DeviceConnectionPool {
  constructor(maxConnections = 100) {
    this.pool = new Map();
    this.maxConnections = maxConnections;
  }

  async getConnection(deviceId) {
    if (!this.pool.has(deviceId)) {
      if (this.pool.size >= this.maxConnections) {
        this.evictOldest();
      }

      const connection = await this.createConnection(deviceId);
      this.pool.set(deviceId, {
        connection,
        lastUsed: Date.now()
      });
    }

    const poolEntry = this.pool.get(deviceId);
    poolEntry.lastUsed = Date.now();
    return poolEntry.connection;
  }

  evictOldest() {
    let oldest = Date.now();
    let oldestId = null;

    for (const [id, entry] of this.pool.entries()) {
      if (entry.lastUsed < oldest) {
        oldest = entry.lastUsed;
        oldestId = id;
      }
    }

    if (oldestId) {
      this.pool.delete(oldestId);
    }
  }
}
```

### 3. **Efficient Event Monitoring**

Monitor device events with minimal overhead:

```javascript
class EventMonitor {
  constructor(provider) {
    this.provider = provider;
    this.filters = new Map();
  }

  async watchDevice(deviceId, callback) {
    // Create optimized filter
    const filter = {
      address: CONTRACT_ADDRESS,
      topics: [
        ethers.id('DeviceUpdate(string,uint256,bytes32)'),
        ethers.id(deviceId)
      ]
    };

    // Use WebSocket for real-time updates
    this.provider.on(filter, async (log) => {
      const parsed = this.parseLog(log);
      await callback(parsed);
    });

    this.filters.set(deviceId, filter);
  }

  stopWatching(deviceId) {
    const filter = this.filters.get(deviceId);
    if (filter) {
      this.provider.off(filter);
      this.filters.delete(deviceId);
    }
  }
}
```

## Troubleshooting Common Issues

### Error: "Device not registered"

Ensure IoT devices are properly registered before submitting data:

```javascript
async function ensureDeviceRegistered(deviceId) {
  try {
    const device = await contract.getDevice(deviceId);
    return device.isActive;
  } catch (error) {
    if (error.message.includes('Device not found')) {
      // Auto-register device
      await contract.registerDevice(
        deviceId,
        DEFAULT_METADATA,
        { gasLimit: 150000 }
      );
      return true;
    }
    throw error;
  }
}
```

### Error: "Invalid sensor data format"

Validate IoT data before submission:

```javascript
function validateSensorData(data) {
  const required = ['deviceId', 'timestamp', 'value'];

  for (const field of required) {
    if (!data[field]) {
      throw new Error(`Missing required field: ${field}`);
    }
  }

  // Validate timestamp is recent (within 5 minutes)
  const fiveMinutes = 5 * 60 * 1000;
  if (Date.now() - data.timestamp > fiveMinutes) {
    throw new Error('Timestamp too old');
  }

  // Validate value ranges
  if (data.value < MIN_VALUE || data.value > MAX_VALUE) {
    throw new Error('Value out of range');
  }

  return true;
}
```

### Error: "W3bstream proof verification failed"

Handle W3bstream proof errors:

```javascript
async function submitWithRetry(data, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const proof = await w3bstream.generateProof(data);
      const tx = await contract.submitProof(proof);
      return tx;
    } catch (error) {
      if (error.message.includes('proof verification')) {
        // Regenerate proof with fresh nonce
        data.nonce = Date.now();
        continue;
      }
      throw error;
    }
  }
  throw new Error('Failed to submit proof after retries');
}
```

## Migration Guide

### From Ethereum/EVM Chains

IoTeX is fully EVM-compatible with additional IoT features:

```javascript
// Before (Ethereum)
const provider = new JsonRpcProvider('https://eth-mainnet.example.com');
const contract = new Contract(address, abi, provider);

// After (IoTeX)
const provider = new JsonRpcProvider(
  'https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'
);
const contract = new Contract(address, abi, provider);

// All Ethereum tools work
// Same development workflow
// Additional IoT capabilities
// Note: Different chain ID (4689)
// Note: IOTX as gas token (not ETH)
// Access to W3bstream and MachineFi
```

### Integrating IoT Devices

Connect physical devices to IoTeX:

```javascript
// Device SDK integration
import { IoTeXDevice } from '@iotex/device-sdk';

const device = new IoTeXDevice({
  deviceId: 'sensor_001',
  privateKey: process.env.DEVICE_KEY,
  endpoint: 'https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'
});

// Auto-submit sensor readings
device.on('reading', async (data) => {
  await device.submitToBlockchain(data);
});

// Start monitoring
device.startMonitoring({
  interval: 60000, // Every minute
  sensors: ['temperature', 'humidity']
});
```

## Resources & Tools

### Official Resources

- [IoTeX Documentation](https://docs.iotex.io)
- [IoTeX Explorer](https://iotexscan.io)
- [W3bstream Docs](https://docs.w3bstream.com)

### Developer Tools

- [IoTeX Developer Portal](https://developers.iotex.io/)
- [IoTeX GitHub](https://github.com/iotexproject)
- [IoTeX Core](https://github.com/iotexproject/iotex-core)

### DePIN Resources

- [DePINscan Explorer](https://depinscan.io)
- [MachineFi Portal](https://machinefi.com)
- [IoTeX DePIN Guide](https://docs.iotex.io/depin)

### Need Help?

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

***

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