Solana has created a built-in method that we can use to unsubscribe from our Account Change listener, removeAccountChangeListener. The method accepts a valid subscriptionId (number) as its only parameter. Inside your async block, add another sleep after your airdrop to allow time for the transaction to process and then call removeAccountChangeListener:
unsubscribe from account change listener
await sleep(10000); //Wait 10 for Socket Testing
await solanaConnection.removeAccountChangeListener(subscriptionId);
console.log(`Websocket ID: ${subscriptionId} closed.`);
await sleep(10000); //Wait 10 for Socket Testing
await solanaConnection.removeAccountChangeListener(subscriptionId);
console.log(`Websocket ID: ${subscriptionId} closed.`);
await sleep(10000); //Wait 10 for Socket Testing
await solanaConnection.removeAccountChangeListener(subscriptionId);
console.log(`Websocket ID: ${subscriptionId} closed.`);
Now run your code again, and you should see the same sequence followed by the closing of the Websocket:
unsubscribe from account change listener
solana-subscriptions % ts-node app.ts
Starting web socket, subscription ID: 0
---Event Notification for vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36NKPTg---
New Account Balance: 88791.51694709 SOL
Websocket ID: 0 closed.
solana-subscriptions % ts-node app.ts
Starting web socket, subscription ID: 0
---Event Notification for vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36NKPTg---
New Account Balance: 88791.51694709 SOL
Websocket ID: 0 closed.
solana-subscriptions % ts-node app.ts
Starting web socket, subscription ID: 0
---Event Notification for vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36NKPTg---
New Account Balance: 88791.51694709 SOL
Websocket ID: 0 closed.
Nice job! As you can see, this can be useful if you want to disable a listener after something has happened (e.g., time elapsed, certain threshold realized, number of notifications, etc.).
We've published the final code for this script to
our Github repo for your reference.