Skip to content

Fix: Web3WebSocketProvider deinitialization crash #182

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

andreichenchik
Copy link

Issue Description

When Web3WebSocketProvider fails to establish a connection during initialization (due to wrong URL or connectivity issues), it properly throws an error as expected. However, when the instance is later deallocated, it crashes with a fatal error:

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

This occurs because:

  1. The webSocket property is declared as an implicitly unwrapped optional (WebSocket!)
  2. If initialization fails before webSocket is assigned, it remains nil
  3. During deinitialization, the code unconditionally attempts to access this nil value

Fix

Added a nil check before attempting to close the WebSocket connection:

deinit {
    closed = true
    
    // Close connection if already initialized
    if let webSocket {
        _ = webSocket.close(code: .goingAway)
    }

    // As described in https://github.com/apple/swift-nio/issues/2371
    try? wsEventLoopGroup.syncShutdownGracefully()
}

This change ensures the Web3WebSocketProvider can be safely deallocated even when a connection couldn't be established, improving error handling and preventing crashes during cleanup.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant