Skip to content

Token Operations

Manage PRIV tokens: transfers, balances, approvals, and more.

Prerequisites

Ensure you have:

  • SDK installed and configured
  • Wallet connected
  • SOL for transaction fees (~0.001 SOL per tx)

Balance Operations

Get PRIV Balance

typescript
// Get connected wallet balance
const balance = await privchain.getBalance();
console.log(`Balance: ${balance} PRIV`);

// Get specific address balance
const otherBalance = await privchain.getBalance('SomeAddressHere...');
console.log(`Other balance: ${otherBalance} PRIV`);

// Get balance with decimals info
const balanceInfo = await privchain.getBalanceInfo();
console.log(balanceInfo);
// { balance: 1000, decimals: 9, raw: 1000000000000n }

Get All Balances

typescript
const balances = await privchain.getAllBalances();
console.log(balances);
// {
//   priv: 1000,
//   sol: 0.5,
//   privUsd: 50.00,  // If price available
//   solUsd: 75.00
// }

Transfers

Simple Transfer

typescript
// Transfer PRIV to another address
const signature = await privchain.transfer({
  to: 'RecipientAddress...',
  amount: 100
});

console.log(`Transfer complete: ${signature}`);
console.log(`Explorer: https://solscan.io/tx/${signature}`);

Transfer with Options

typescript
const signature = await privchain.transfer({
  to: 'RecipientAddress...',
  amount: 100,
  
  // Optional parameters
  memo: 'Payment for services',      // On-chain memo
  priorityFee: 10000,                // Extra fee for priority
  skipPreflight: false,              // Skip simulation
  maxRetries: 3                      // Retry on failure
});

Batch Transfers

typescript
// Send to multiple recipients in one transaction
const signatures = await privchain.batchTransfer([
  { to: 'Address1...', amount: 50 },
  { to: 'Address2...', amount: 75 },
  { to: 'Address3...', amount: 25 }
]);

console.log(`Completed ${signatures.length} transfers`);

Transfer All

typescript
// Transfer entire balance (minus fees)
const signature = await privchain.transferAll({
  to: 'RecipientAddress...',
  keepMinimum: 1 // Keep 1 PRIV for future fees
});

Transaction Monitoring

Wait for Confirmation

typescript
const signature = await privchain.transfer({
  to: 'RecipientAddress...',
  amount: 100
});

// Wait for confirmation (default: confirmed)
const result = await privchain.waitForConfirmation(signature);
console.log('Confirmed at slot:', result.slot);

// Wait for finalization
const final = await privchain.waitForConfirmation(signature, 'finalized');
console.log('Finalized at slot:', final.slot);

Get Transaction Status

typescript
const status = await privchain.getTransactionStatus(signature);
console.log(status);
// {
//   status: 'confirmed',
//   slot: 123456789,
//   confirmations: 32,
//   fee: 5000,
//   error: null
// }

Transaction History

typescript
// Get recent transactions
const history = await privchain.getTransactionHistory({
  limit: 10,
  before: lastSignature // Optional: pagination
});

for (const tx of history) {
  console.log(`${tx.type}: ${tx.amount} PRIV → ${tx.to}`);
  console.log(`  Status: ${tx.status}, Time: ${tx.timestamp}`);
}

Token Account Management

Create Token Account

Token accounts are created automatically on first receive, but you can create them explicitly:

typescript
// Create token account for an address
const account = await privchain.createTokenAccount(recipientPublicKey);
console.log('Token account:', account.toBase58());

Close Token Account

typescript
// Close empty token account (recovers rent SOL)
const signature = await privchain.closeTokenAccount();
console.log('Account closed, rent recovered');

Token Information

Get Token Metadata

typescript
const tokenInfo = await privchain.getTokenInfo();
console.log(tokenInfo);
// {
//   name: 'PrivChain',
//   symbol: 'PRIV',
//   decimals: 9,
//   totalSupply: 1000000000,
//   mintAddress: 'EFy9cEMheBYyrH1HYNonDnKgNzU9tkwiMUMfGNqK4Jua',
//   currentSupply: 1000000000,
//   holders: 5432
// }

Get Current Price

typescript
const price = await privchain.getPrice();
console.log(price);
// {
//   usd: 0.05,
//   sol: 0.0005,
//   change24h: 2.5,
//   volume24h: 150000
// }

Advanced Operations

Estimate Fees

typescript
// Estimate transaction fee
const fee = await privchain.estimateFee({
  to: 'RecipientAddress...',
  amount: 100
});

console.log(`Estimated fee: ${fee.sol} SOL (${fee.usd} USD)`);

Simulate Transaction

typescript
// Simulate without sending
const simulation = await privchain.simulate({
  to: 'RecipientAddress...',
  amount: 100
});

if (simulation.success) {
  console.log('Simulation passed, units:', simulation.unitsConsumed);
} else {
  console.error('Simulation failed:', simulation.error);
}

Raw Transaction Building

typescript
// Build transaction manually
const tx = await privchain.buildTransferTransaction({
  to: 'RecipientAddress...',
  amount: 100
});

// Add custom instructions
tx.add(myCustomInstruction);

// Sign and send
const signature = await privchain.sendTransaction(tx);

Error Handling

typescript
import { 
  InsufficientFundsError, 
  TransactionError,
  NetworkError 
} from '@privchain/sdk';

try {
  await privchain.transfer({ to: '...', amount: 1000000 });
} catch (error) {
  if (error instanceof InsufficientFundsError) {
    console.error(`Insufficient funds. Have: ${error.balance}, Need: ${error.required}`);
  } else if (error instanceof TransactionError) {
    console.error('Transaction failed:', error.logs);
  } else if (error instanceof NetworkError) {
    console.error('Network error, retrying...');
  }
}

Usage Examples

Payment Agent

typescript
class PaymentAgent {
  constructor(private privchain: PrivChain) {}
  
  async payForService(provider: string, amount: number): Promise<string> {
    // Check balance
    const balance = await this.privchain.getBalance();
    if (balance < amount) {
      throw new Error(`Insufficient balance: ${balance} < ${amount}`);
    }
    
    // Execute payment
    const signature = await this.privchain.transfer({
      to: provider,
      amount,
      memo: `Service payment ${Date.now()}`
    });
    
    // Wait for confirmation
    await this.privchain.waitForConfirmation(signature);
    
    return signature;
  }
}

Automated Distribution

typescript
async function distributeRewards(
  recipients: Array<{ address: string; amount: number }>
) {
  // Batch for efficiency
  const batches = chunk(recipients, 5); // 5 per transaction
  
  const results = [];
  for (const batch of batches) {
    const signatures = await privchain.batchTransfer(
      batch.map(r => ({ to: r.address, amount: r.amount }))
    );
    results.push(...signatures);
  }
  
  return results;
}

Rate Limits

The SDK handles rate limiting automatically:

OperationRate Limit
Balance queries100/second
Transfers10/second
History queries20/second

For higher limits, use a dedicated RPC endpoint.

Next Steps

Built for the autonomous agent economy.