Best Practices

Recommendations

Following these recommendations ensures reliable, efficient, and maintainable applications when working with OP_NET providers:

  1. Single Provider Instance: Reuse provider instances rather than creating new ones for each operation.
  2. Error Handling: Always wrap provider calls in try-catch-finally blocks.
  3. Connection Cleanup: Always ensure providers are properly disposed when no longer required.
    • Use the close() method for JSONRpcProvider.
    • Use the disconnect() method for WebSocketRpcProvider.
  4. Network Matching: Ensure the provider network matches your contract addresses.
  5. Timeout Configuration: Set appropriate timeouts for your use case.
Good and bad pratices:
typescript
// Good: Reuse provider
const provider = new JSONRpcProvider(url, network);
const block1 = await provider.getBlock(1);
const block2 = await provider.getBlock(2);

// Good: Cleanup
// For JSONRpcProvider
await provider.close();

// For WebSocketRpcProvider
provider.disconnect();

// Good: Use try-catch-finally block
try {
    const block = await provider.getBlockNumber();
    console.log('Block:', block);
} finally {
    await provider.close();
}

// Bad: Creating new provider each time
const block1 = await new JSONRpcProvider(url, network).getBlock(1);
const block2 = await new JSONRpcProvider(url, network).getBlock(2);