# Getting Started with IoTeX Node.js SDK

## Installation

### Prerequisites

- Node.js 18.0.0 or higher
- npm 8.0.0 or higher

### Install from npm

```bash
npm install iotex-node-sdk
```

### Install from source

```bash
git clone https://github.com/your-repo/iotex-node-sdk.git
cd iotex-node-sdk
npm install
npm run build
```

## Quick Verification

After installation, verify everything works:

```bash
# Run verification script
./scripts/verify-installation.sh

# Or run quick start example
npm run example:quick-start
```

## Your First IoTeX Application

### 1. Basic Setup

Create a new file `my-first-app.ts`:

```typescript
import { IoTeXSDK } from 'iotex-node-sdk';

async function main() {
  // Create SDK instance
  const sdk = IoTeXSDK.mainnet();

  // Connect to blockchain
  await sdk.connect();
  console.log('Connected to IoTeX!');

  // Your code here...

  // Disconnect when done
  sdk.disconnect();
}

main().catch(console.error);
```

### 2. Check Account Balance

```typescript
import { IoTeXSDK } from 'iotex-node-sdk';

async function checkBalance() {
  const sdk = IoTeXSDK.mainnet();
  await sdk.connect();

  const address = 'io1gh7xfrsnj6p5uqgjpk9xq6jg9na28aewgp7a9v';
  const balance = await sdk.account.getBalance(address);

  console.log(`Balance: ${balance} IOTX`);

  sdk.disconnect();
}

checkBalance();
```

### 3. Create New Account

```typescript
import { IoTeXSDK } from 'iotex-node-sdk';

async function createAccount() {
  const sdk = IoTeXSDK.mainnet();
  await sdk.connect();

  // Create account (stored in keystore)
  const account = await sdk.account.create('my-secure-password');

  console.log('New account created:');
  console.log('Address:', account.address);
  console.log('Private key:', account.privateKey);
  console.log('(Keep your private key safe!)');

  sdk.disconnect();
}

createAccount();
```

### 4. Query Blockchain Information

```typescript
import { IoTeXSDK } from 'iotex-node-sdk';

async function getBlockchainInfo() {
  const sdk = IoTeXSDK.mainnet();
  await sdk.connect();

  // Get chain metadata
  const chainMeta = await sdk.blockchain.getChainMeta();
  console.log('Current height:', chainMeta.height.toString());
  console.log('Current epoch:', chainMeta.epoch.num.toString());

  // Get latest block
  const block = await sdk.blockchain.getBlock(Number(chainMeta.height));
  console.log('Latest block hash:', block.blockHash);
  console.log('Block producer:', block.producerAddress);

  sdk.disconnect();
}

getBlockchainInfo();
```

### 5. Get Delegates

```typescript
import { IoTeXSDK } from 'iotex-node-sdk';

async function getDelegates() {
  const sdk = IoTeXSDK.mainnet();
  await sdk.connect();

  const delegates = await sdk.node.getDelegates();

  console.log('Top 10 Delegates:');
  for (let i = 0; i < Math.min(10, delegates.length); i++) {
    const d = delegates[i];
    console.log(`${d.rank}. ${d.name} - ${d.votes} IOTX`);
  }

  sdk.disconnect();
}

getDelegates();
```

## Common Use Cases

### Working with HD Wallet

```typescript
import { IoTeXSDK } from 'iotex-node-sdk';

async function hdWalletExample() {
  const sdk = IoTeXSDK.mainnet();
  await sdk.connect();

  // Create HD wallet
  const mnemonic = await sdk.account.createHDWallet('password', 'english');
  console.log('Mnemonic (save this!):', mnemonic);

  // Derive accounts
  const account1 = await sdk.account.deriveHDAccount('password', 0, 0, 0);
  const account2 = await sdk.account.deriveHDAccount('password', 0, 0, 1);

  console.log('Account 1:', account1.address);
  console.log('Account 2:', account2.address);

  // Don't forget to delete HD wallet when testing
  sdk.account.deleteHDWallet();

  sdk.disconnect();
}

hdWalletExample();
```

### Address Conversion

```typescript
import { toEthAddress, toIoAddress } from 'iotex-node-sdk';

// Convert IoTeX to Ethereum format
const ethAddr = toEthAddress('io1hp6y4eqr90j7tmul4w2wa8pm7wx462hq0mg4tw');
console.log('Ethereum:', ethAddr);
// Output: 0xb8744ae4032be5e5ef9fab94ee9c3bf38d5d2ae0

// Convert Ethereum to IoTeX format
const ioAddr = toIoAddress('0xb8744ae4032be5e5ef9fab94ee9c3bf38d5d2ae0');
console.log('IoTeX:', ioAddr);
// Output: io1hp6y4eqr90j7tmul4w2wa8pm7wx462hq0mg4tw
```

### Amount Conversion

```typescript
import { iotxToRau, rauToIotx } from 'iotex-node-sdk';

// Convert IOTX to Rau (smallest unit)
const rau = iotxToRau('100');
console.log('100 IOTX =', rau.toString(), 'Rau');
// Output: 100 IOTX = 100000000000000000000 Rau

// Convert Rau to IOTX
const iotx = rauToIotx(BigInt('100000000000000000000'));
console.log(iotx, 'IOTX');
// Output: 100 IOTX
```

### Error Handling

```typescript
import { IoTeXSDK, IoTeXError } from 'iotex-node-sdk';

async function withErrorHandling() {
  const sdk = IoTeXSDK.mainnet();

  try {
    await sdk.connect();
    const balance = await sdk.account.getBalance('invalid-address');
  } catch (error) {
    if (error instanceof IoTeXError) {
      console.error('Error code:', error.code);
      console.error('Message:', error.message);
      console.error('Details:', error.details);
    } else {
      console.error('Unexpected error:', error);
    }
  } finally {
    sdk.disconnect();
  }
}

withErrorHandling();
```

## Network Configuration

### Mainnet

```typescript
const sdk = IoTeXSDK.mainnet();
// or
const sdk = new IoTeXSDK({
  endpoint: 'api.iotex.one:443',
  secure: true
});
```

### Testnet

```typescript
const sdk = IoTeXSDK.testnet();
// or
const sdk = new IoTeXSDK({
  endpoint: 'api.testnet.iotex.one:443',
  secure: true
});
```

### Local Node

```typescript
const sdk = IoTeXSDK.localhost();
// or
const sdk = new IoTeXSDK({
  endpoint: 'localhost:14014',
  secure: false
});
```

## Available Scripts

After installation, you can run:

```bash
# Build the project
npm run build

# Run tests
npm test
npm run test:watch      # Watch mode
npm run test:coverage   # With coverage

# Run examples
npm run example:quick-start
npm run example:balance
npm run example:delegates
npm run example:account
npm run example:hdwallet
npm run example:blockchain

# Code quality
npm run lint
npm run format
npm run format:check

# Clean build
npm run clean
```

## Project Structure

```
your-project/
├── node_modules/
│   └── iotex-node-sdk/
├── src/
│   └── index.ts         # Your application
├── package.json
└── tsconfig.json
```

## TypeScript Configuration

Add to your `tsconfig.json`:

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "lib": ["ES2022"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}
```

## Best Practices

### 1. Always Disconnect

```typescript
async function goodPractice() {
  const sdk = IoTeXSDK.mainnet();
  try {
    await sdk.connect();
    // Your code here
  } finally {
    sdk.disconnect(); // Always disconnect
  }
}
```

### 2. Secure Password Storage

```typescript
// ❌ Bad: Hardcoded password
const account = await sdk.account.create('password123');

// ✅ Good: Use environment variables
const password = process.env.WALLET_PASSWORD || '';
const account = await sdk.account.create(password);
```

### 3. Error Handling

```typescript
// ✅ Good: Always handle errors
try {
  const balance = await sdk.account.getBalance(address);
} catch (error) {
  if (error instanceof IoTeXError) {
    // Handle SDK errors
  } else {
    // Handle other errors
  }
}
```

### 4. Validate Inputs

```typescript
import { isValidAddress, validateAmount } from 'iotex-node-sdk';

// ✅ Good: Validate before using
if (!isValidAddress(userInput)) {
  throw new Error('Invalid address');
}

validateAmount(amountString); // Throws if invalid
```

## Next Steps

1. **Explore Examples**: Check out `examples/` directory for more examples
2. **Read Documentation**: See `README.md` for complete API reference
3. **Join Community**: Join IoTeX Discord for support
4. **Contribute**: Contributions are welcome!

## Troubleshooting

### Connection Issues

```typescript
// Check if connected
const isConnected = await sdk.isConnected();
if (!isConnected) {
  console.error('Not connected to blockchain');
}
```

### Build Issues

```bash
# Clean and rebuild
npm run clean
npm install
npm run build
```

### Test Failures

```bash
# Run specific test
npm test -- conversion.test.ts

# Skip integration tests
npm test -- --testPathIgnorePatterns=integration
```

## Support

- 📖 Documentation: [README.md](./README.md)
- 🐛 Issues: [GitHub Issues](https://github.com/your-repo/issues)
- 💬 Discord: [IoTeX Community](https://discord.gg/iotex)
- 📚 IoTeX Docs: [docs.iotex.io](https://docs.iotex.io)

## License

MIT - See [LICENSE](./LICENSE) for details
