# Tatum SDK Integration Guide

## Overview

The Tatum SDK provides a convenient interface for interacting with the DeFi Oracle Meta Mainnet (ChainID 138) while using your own RPC endpoints. This guide explains how to integrate and use the Tatum SDK with ChainID 138.

## Important Notes

**Key Limitations:**
- With custom RPC, **only RPC calls are redirected to your node**
- Tatum's cloud services (Notifications, Blockchain Data, etc.) **won't work** on unsupported/private chains
- Only raw JSON-RPC calls will work
- Transactions must be signed with `chainId: 138` (EIP-155)

## Prerequisites

1. **RPC Endpoint Access**
   - Your ChainID 138 RPC node must be accessible
   - HTTP RPC at port 8545
   - WebSocket RPC at port 8546 (optional)

2. **Node.js Environment**
   - Node.js 18+ recommended
   - npm or yarn package manager

3. **Network Configuration**
   - ChainID 138 configured in genesis
   - RPC nodes deployed and running
   - Network connectivity verified

## Installation

### 1. Install Dependencies

```bash
cd sdk
npm install
```

### 2. Configure Environment

```bash
cp .env.example .env
```

Update `.env` with your RPC endpoint:

```env
RPC_URL=https://rpc.d-bis.org
WS_URL=wss://rpc.d-bis.org
EXPLORER_URL=https://explorer.d-bis.org
PRIVATE_KEY=your-private-key-here
```

## Basic Usage

### Initialize Tatum SDK

```typescript
import { initTatumSDK, verifyConnection } from './tatum-client';

// Initialize with custom RPC URL
const tatum = await initTatumSDK({
  rpcUrl: 'https://rpc.d-bis.org',
  verbose: true,
});

// Verify connection and chain ID
const connectionInfo = await verifyConnection(tatum);
console.log('Chain ID:', connectionInfo.chainId); // Should be 138
console.log('Current Block:', connectionInfo.blockNumber);
```

### Make RPC Calls

```typescript
// Get block number
const blockNumber = await tatum.rpc.request('eth_blockNumber', []);

// Get chain ID
const chainId = await tatum.rpc.request('eth_chainId', []);

// Get gas price
const gasPrice = await tatum.rpc.request('eth_gasPrice', []);

// Get balance
const balance = await tatum.rpc.request('eth_getBalance', [
  '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
  'latest'
]);
```

## Sending Transactions

### Using ethers.js

```typescript
import { ethers } from 'ethers';
import { CHAIN_ID, DEFAULT_RPC_URL } from './config';

// Initialize provider with ChainID 138
const provider = new ethers.JsonRpcProvider(DEFAULT_RPC_URL, {
  chainId: CHAIN_ID,
  name: 'defi-oracle-mainnet',
});

// Create wallet
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);

// Send transaction (must include chainId: 138)
const tx = await wallet.sendTransaction({
  to: '0xRecipientAddress...',
  value: ethers.parseEther('0.01'),
  chainId: CHAIN_ID, // Important: Must be 138
});

// Wait for confirmation
const receipt = await tx.wait();
console.log('Transaction confirmed:', receipt.blockNumber);
```

### Verify Chain ID in Transaction

```typescript
// Get transaction from chain
const txFromChain = await tatum.rpc.request('eth_getTransactionByHash', [tx.hash]);

// Verify chainId
if (txFromChain && typeof txFromChain === 'object' && 'chainId' in txFromChain) {
  const txChainId = parseInt(txFromChain.chainId as string, 16);
  if (txChainId === 138) {
    console.log('✓ ChainID verified');
  }
}
```

## Contract Deployment

```typescript
import { ethers } from 'ethers';
import { CHAIN_ID, DEFAULT_RPC_URL } from './config';

// Initialize provider
const provider = new ethers.JsonRpcProvider(DEFAULT_RPC_URL, {
  chainId: CHAIN_ID,
  name: 'defi-oracle-mainnet',
});

// Create wallet
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);

// Deploy contract
const factory = new ethers.ContractFactory(ABI, BYTECODE, wallet);
const contract = await factory.deploy({
  chainId: CHAIN_ID, // Important: Must be 138
});

await contract.waitForDeployment();
const contractAddress = await contract.getAddress();
console.log('Contract deployed at:', contractAddress);
```

## Testing

### Run Connection Test

```bash
npm run test
```

### Run Smoke Test

```bash
npm run smoke-test
```

### Run Examples

```bash
# Basic usage
npm run example:basic

# Send transaction
npm run example:transaction

# Deploy contract
npm run example:contract
```

## Verification Checklist

- [ ] RPC node is up and accessible
- [ ] ChainID is 138 (0x8a in hex)
- [ ] Tatum SDK initialized with custom `rpcUrl`
- [ ] Transactions signed with `chainId: 138`
- [ ] RPC calls are working correctly
- [ ] Network connectivity verified

## Troubleshooting

### Connection Issues

**Problem**: RPC endpoint not responding

**Solutions**:
1. Verify RPC node is running: `kubectl get pods -n besu-network`
2. Check network connectivity: `curl -X POST $RPC_URL -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'`
3. Verify firewall/network settings
4. Check RPC_URL in .env file

### Chain ID Mismatch

**Problem**: Chain ID mismatch errors

**Solutions**:
1. Verify genesis file has `chainId: 138`
2. Check node configuration
3. Ensure all transactions use `chainId: 138`
4. Verify `eth_chainId` returns `0x8a` (138 in hex)

### Transaction Failures

**Problem**: Transactions failing

**Solutions**:
1. Verify `chainId: 138` is set in transaction
2. Check account has sufficient balance
3. Verify gas price and limits
4. Check transaction nonce
5. Review node logs for errors

## Limitations

As per Tatum documentation:

1. **Cloud Services**: Tatum's cloud services (Notifications, Blockchain Data, etc.) won't work with custom RPC endpoints
2. **Indexer Support**: No indexer support for private chains
3. **RPC Only**: Only raw JSON-RPC calls are available
4. **No Webhooks**: Webhook notifications won't work

## Best Practices

1. **Always set chainId**: Always include `chainId: 138` in transactions
2. **Verify connection**: Always verify connection and chain ID before making calls
3. **Error handling**: Implement proper error handling for RPC calls
4. **Rate limiting**: Be aware of RPC rate limits
5. **Gas estimation**: Always estimate gas before sending transactions

## Examples

See the `sdk/src/examples/` directory for complete examples:

- `basic-usage.ts`: Basic connection and querying
- `send-transaction.ts`: Sending transactions
- `deploy-contract.ts`: Deploying and interacting with contracts

## References

- [Tatum SDK Documentation](https://docs.tatum.io/docs/configuration-options)
- [Ethereum JSON-RPC API](https://ethereum.org/developers/docs/apis/json-rpc/)
- [EIP-155: Simple replay attack protection](https://eips.ethereum.org/EIPS/eip-155)
- [Besu JSON-RPC API](https://besu.hyperledger.org/en/stable/Reference/API-Methods/)

## Support

For issues or questions:
1. Check the troubleshooting section
2. Review the examples in `sdk/src/examples/`
3. Open an issue on the project repository
4. Contact the network operators

