npm package: @habify/pact-tndsdk
Description: Comprehensive SDK for PACT Protocol testnet blockchain development
Author: Habify Labs
Latest version: 0.1.4

# @habify/pact-tndsdk

A comprehensive TypeScript developer SDK for the PACT Protocol (Testnet) blockchain compliance layer development, owned by Habify Labs LLC.

## Installation

```bash
npm install @habify/pact-tndsdk
```

## Features

- **Complete TypeScript Support**: Full type definitions and IntelliSense support
- **Modular Architecture**: Easy integration with clean, focused modules
- **Comprehensive Contract Support**: All PACT testnet contracts and features
- **Robust Error Handling**: Detailed error messages and validation
- **Multi-Environment**: Configurable for different blockchain environments
- **Universal Compatibility**: Built for both CommonJS and ESM
- **Ethers.js v6 Ready**: Full compatibility with the latest ethers.js
- **Developer-First**: Designed specifically for seamless developer integration

## Quick Start

```typescript
import { PactTestnetSDK } from '@habify/pact-tndsdk';

// Initialize the SDK with default testnet configuration
const sdk = new PactTestnetSDK({
  network: {
    name: 'pact-testnet',
    chainId: 11155111, // Sepolia testnet
    rpcUrl: 'https://sepolia.infura.io/v3/YOUR_INFURA_KEY'
  }
});

// Connect with a private key
sdk.connect('YOUR_PRIVATE_KEY');

// Use the SDK modules
async function example() {
  // Get stake information
  const address = '0x...';
  const stakeInfo = await sdk.staking.getStake(address);
  console.log('Stake info:', stakeInfo);
  
  // Submit data to the oracle
  const receipt = await sdk.oracle.submitData('Some data');
  console.log('Transaction hash:', receipt.hash);
  
  // Get user activity
  const activity = await sdk.activity.getMyActivityFeed();
  console.log('Recent activity:', activity);
}

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

## Modules

The SDK is organized into modules, each focusing on a specific aspect of the PACT testnet:

- **Staking**: Interact with the staking contract to stake and unstake tokens
- **Oracle**: Submit and verify data through the oracle system
- **Token**: Manage token transfers, approvals, and swaps
- **Access**: Generate and manage API keys for accessing Pact services
- **Activity**: Retrieve user activity and transaction history
- **Analytics**: Get protocol analytics and statistics

## Configuration

The SDK can be configured with various options:

```typescript
const sdk = new PactTestnetSDK({
  // Network configuration
  network: {
    name: 'pact-testnet',
    chainId: 11155111, // Sepolia testnet
    rpcUrl: 'https://sepolia.infura.io/v3/YOUR_INFURA_KEY'
  },
  
  // Contract addresses (optional, defaults to deployed testnet addresses)
  contracts: {
    staking: '0x...',
    oracle: '0x...',
    oracleVerifier: '0x...',
    xHBF: '0x...',
    tokenSwap: '0x...',
    apiAccess: '0x...'
  },
  
  // Logging configuration (optional)
  logging: {
    level: 'info', // 'debug', 'info', 'warn', 'error'
    enabled: true
  }
});
```

## Examples

### Staking Tokens

```typescript
// Stake tokens
const amount = ethers.parseUnits('100', 18); // 100 tokens with 18 decimals
const receipt = await sdk.staking.stake(amount);
console.log('Stake transaction:', receipt.hash);

// Get stake information
const myAddress = await sdk.getSigner().getAddress();
const stakeInfo = await sdk.staking.getStake(myAddress);
console.log('Staked amount:', ethers.formatUnits(stakeInfo.amount, 18));
console.log('Staking tier:', stakeInfo.tier);
```

### Oracle Interactions

```typescript
// Submit data to the oracle
const data = JSON.stringify({ temperature: 25, humidity: 60 });
const receipt = await sdk.oracle.submitData(data);
console.log('Data submitted:', receipt.hash);

// Verify data (if you're a verifier)
const dataHash = ethers.keccak256(ethers.toUtf8Bytes(data));
await sdk.oracle.verifyData(dataHash);
```

### Token Operations

```typescript
// Get token balance
const myAddress = await sdk.getSigner().getAddress();
const balance = await sdk.token.getBalance(myAddress);
console.log('Token balance:', ethers.formatUnits(balance, 18));

// Transfer tokens
const recipient = '0x...';
const amount = ethers.parseUnits('10', 18);
await sdk.token.transfer(recipient, amount);

// Swap tokens
const swapAmount = ethers.parseUnits('5', 18);
const { receipt, swapInfo } = await sdk.token.swap(swapAmount);
console.log('Swapped:', ethers.formatUnits(swapInfo.amountIn, 18), 'for', ethers.formatUnits(swapInfo.amountOut, 18));
```

### API Access

```typescript
// Generate API key
const { apiKey } = await sdk.access.generateAPIKey();
console.log('Your API key:', apiKey);

// Validate API key
const isValid = await sdk.access.validateAPIKey(apiKey);
console.log('API key is valid:', isValid);
```

## Error Handling

The SDK provides detailed error information:

```typescript
try {
  await sdk.staking.stake(amount);
} catch (error) {
  if (error instanceof PactSDKError) {
    console.error('SDK Error:', error.message);
    console.error('Error code:', error.code);
    console.error('Error details:', error.details);
  } else {
    console.error('Unknown error:', error);
  }
}
```

## Advanced Usage

### Ethers.js v6 Compatibility

This SDK is fully compatible with ethers.js v6, which introduces several breaking changes compared to v5. The SDK handles these changes transparently, but if you're interacting directly with ethers.js, be aware of the following:

```typescript
// Import ethers.js v6
import * as ethers from 'ethers';

// Create a provider (note the new format for network)
const provider = new ethers.JsonRpcProvider('https://your-rpc.com', { chainId: 11155111 });

// Create a wallet (note the new method)
const wallet = ethers.Wallet.fromPrivateKey('0x...');

// Connect to a contract and call functions (note the getFunction pattern)
const contract = new ethers.Contract(address, abi, signer);
const result = await contract.getFunction('functionName')(arg1, arg2);

// Work with BigInt instead of BigNumber
const amount = ethers.parseEther('1.0'); // Returns BigInt
```

#### For Users of the Package

1. **SDK Usage**: The SDK can be used with ethers.js v6 without any special configuration. It works correctly in both ESM and CommonJS environments.

2. **Testing**: Users should run the ethers.js compatibility tests in their own environment to verify compatibility:
   ```bash
   npm run test:ethers:full
   ```

For more details, see the [ethers.js v6 compatibility documentation](./docs/ethers-compatibility.md).

### Custom Provider

```typescript
// Use a custom provider
import { ethers } from 'ethers';
const provider = new ethers.JsonRpcProvider('https://your-custom-rpc.com');
sdk.connectProvider(provider);
```

### Transaction Options

```typescript
// Specify transaction options
const options = {
  gasLimit: 300000,
  maxFeePerGas: ethers.parseUnits('20', 'gwei'),
  maxPriorityFeePerGas: ethers.parseUnits('2', 'gwei')
};

await sdk.staking.stake(amount, options);
```


## Testing

### Ethers.js Compatibility Testing

You can verify ethers.js v6 compatibility with:

```bash
# Basic compatibility test
npm run test:ethers

# Comprehensive compatibility test suite
npm run test:ethers:full
```

The comprehensive test suite runs all ethers.js compatibility scripts in sequence:

1. Fixes ethers.js import statements
2. Applies ethers.js v6 compatibility fixes
3. Verifies compatibility in both ESM and CommonJS environments

This ensures the SDK works correctly with ethers.js v6 in all environments and handles all the breaking changes introduced in v6.

**Important**: It's recommended that users run the compatibility tests in their own environment to verify compatibility, especially if they're using the SDK in a production environment:

```bash
npm run test:ethers:full
```

For more details on ethers.js v6 compatibility, see the [ethers-compatibility.md](./docs/ethers-compatibility.md) documentation.

## License

MIT © 2025 Habify Labs LLC