Skip to content

Commit

Permalink
Event subscription (TS sdk) (#4249)
Browse files Browse the repository at this point in the history
* add subscribeEvent stub

* add onMessage callback to subscribeEvent

* add json rpc version of subscribeEvent

* add subscribeEvent to void provider

* refine types for event sub, add websocket client instance

* support insecure websocket

* rename subscribeEvent parameter

* update generated type guards

* add debug logs to getWebsocketUrl

* add SuiEventEnvelope typescript type

* remove unused import, update type guards

* {} to void return for subscribeevent

* add basic event subscription test box

* TEMPORARILY add eventsubscription to home page

* remove broken checkbox select

* add basic Event Filter Type element

* lint changes

* working objectId filter

* lint changes

* remove select form from event tester

* remove jayson WebsocketClient

* remove excess whitespace

* add Subscription tracking

* Update index.guard.ts

* add unsubscribeEvent

* remove console logs, add comments

* style / organization changes in ts sdk

* don't re-create websocket client

* only create one default rpc client per network

* lint changes

* add on socket error

* fix message subscription

* add unsubscribe rpc call

* allow timestamp as number in SuiEventEnvelope

* remove LossLessJSON from event parsing

* Update index.guard.ts

* move socket event setup to method

* add check for method id

* remove explorer eventSubscription

* make websocket rpc client not auto connection

* bring back explorer test page for event sub

* remove heartbeat

* improve comment for socket type cast

* improve timeout handling for websocket connection

* add FilterSubHandler type

* delete from active subs on remove

* shorten lazy connect comment

* use one single map to track subscription data

* use .values() instead of entries() in sub refresh

* improve comment about subscription refresh

* Delete yarn.lock

* remove explorer home changes for testing

* use shorter console error

* fix provider subscribe return value

* fix doc comment on unsubscribe event

* remove console.log

* use jsdoc comment style

* change EventType discriminator enum

* make timestamp only a number

* replace string manipulation with url object

* update onMessage return types

* change to doing socket setup in connect

* add timeout error

* shorten usage of reject

* const instead of let for two vars

* if spacing change

* remove calbackwithType

* Update client.ts

* Update client.ts

* move websocket client into its own class

* Revert "remove explorer home changes for testing"

This reverts commit a071c94.

* rename most websocket client symbols

* Revert "Revert "remove explorer home changes for testing""

This reverts commit ad1f441.

* validate minimum data with validation off

* Update websocket-client.ts

* add else if in socket message handler

* activeSubs -> eventSubs

* wsProvider -> wsClient

* move websocket client into rpc folder

* better styling for default websocket options

* add maxReconnects option to websockets

* Revert "Revert "Revert "remove explorer home changes for testing"""

This reverts commit cce81e3.

* remove old todo

* Update sdk/typescript/src/providers/void-provider.ts

Co-authored-by: Chris Li <76067158+666lcz@users.noreply.github.com>

* add better usage comments for event subscription

* Revert "Revert "Revert "Revert "remove explorer home changes for testing""""

This reverts commit d828f19.

* minor formatting change in provider

* fix type guard import

* Update pnpm-lock.yaml

* fix capitalization on event filters

* Update sdk/typescript/src/rpc/websocket-client.ts

Co-authored-by: Chris Li <76067158+666lcz@users.noreply.github.com>

* add websocket config jsdoc

* add jsdoc for websocket client

* update type guard

* handle case of currently-connecting when calling connect

Co-authored-by: Chris Li <76067158+666lcz@users.noreply.github.com>
  • Loading branch information
Stella Cannefax and 666lcz committed Sep 8, 2022
1 parent ee77d8a commit e046e01
Show file tree
Hide file tree
Showing 9 changed files with 572 additions and 10 deletions.
11 changes: 9 additions & 2 deletions explorer/client/src/utils/api/DefaultRpcClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,12 @@ import { getEndpoint, Network } from './rpcSetting';

export { Network, getEndpoint };

export const DefaultRpcClient = (network: Network | string) =>
new JsonRpcProvider(getEndpoint(network));
const defaultRpcMap: Map<Network | string, JsonRpcProvider> = new Map();
export const DefaultRpcClient = (network: Network | string) => {
const existingClient = defaultRpcMap.get(network);
if (existingClient) return existingClient;

const provider = new JsonRpcProvider(getEndpoint(network));
defaultRpcMap.set(network, provider);
return provider;
};
81 changes: 79 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions sdk/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
"buffer": "^6.0.3",
"cross-fetch": "^3.1.5",
"jayson": "^3.6.6",
"rpc-websockets": "^7.5.0",
"js-sha3": "^0.8.0",
"lossless-json": "^1.0.5",
"tweetnacl": "^1.0.3"
Expand Down
22 changes: 21 additions & 1 deletion sdk/typescript/src/providers/json-rpc-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,22 @@ import {
SuiObjectRef,
getObjectReference,
Coin,
SuiEventFilter,
SuiEventEnvelope,
SubscriptionId,
ExecuteTransactionRequestType,
SuiExecuteTransactionResponse,
} from '../types';
import { SignatureScheme } from '../cryptography/publickey';
import { DEFAULT_CLIENT_OPTIONS, WebsocketClient, WebsocketClientOptions } from '../rpc/websocket-client';

const isNumber = (val: any): val is number => typeof val === 'number';
const isAny = (_val: any): _val is any => true;


export class JsonRpcProvider extends Provider {
protected client: JsonRpcClient;
protected wsClient: WebsocketClient;
/**
* Establish a connection to a Sui RPC endpoint
*
Expand All @@ -54,10 +60,13 @@ export class JsonRpcProvider extends Provider {
*/
constructor(
public endpoint: string,
public skipDataValidation: boolean = false
public skipDataValidation: boolean = false,
public socketOptions: WebsocketClientOptions = DEFAULT_CLIENT_OPTIONS
) {
super();

this.client = new JsonRpcClient(endpoint);
this.wsClient = new WebsocketClient(endpoint, skipDataValidation, socketOptions);
}

// Move info
Expand Down Expand Up @@ -421,4 +430,15 @@ export class JsonRpcProvider extends Provider {
);
}
}

async subscribeEvent(
filter: SuiEventFilter,
onMessage: (event: SuiEventEnvelope) => void
): Promise<SubscriptionId> {
return this.wsClient.subscribeEvent(filter, onMessage);
}

async unsubscribeEvent(id: SubscriptionId): Promise<boolean> {
return this.wsClient.unsubscribeEvent(id);
}
}
19 changes: 19 additions & 0 deletions sdk/typescript/src/providers/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import {
SuiMoveNormalizedStruct,
SuiMoveNormalizedModule,
SuiMoveNormalizedModules,
SuiEventFilter,
SuiEventEnvelope,
SubscriptionId,
ExecuteTransactionRequestType,
SuiExecuteTransactionResponse,
} from '../types';
Expand Down Expand Up @@ -136,5 +139,21 @@ export abstract class Provider {
): Promise<SuiMoveNormalizedStruct>;

abstract syncAccountState(address: string): Promise<any>;

/**
* Subscribe to get notifications whenever an event matching the filter occurs
* @param filter - filter describing the subset of events to follow
* @param onMessage - function to run when we receive a notification of a new event matching the filter
*/
abstract subscribeEvent(
filter: SuiEventFilter,
onMessage: (event: SuiEventEnvelope) => void
): Promise<SubscriptionId>;

/**
* Unsubscribe from an event subscription
* @param id - subscription id to unsubscribe from (previously received from subscribeEvent)
*/
abstract unsubscribeEvent(id: SubscriptionId): Promise<boolean>;
// TODO: add more interface methods
}
14 changes: 14 additions & 0 deletions sdk/typescript/src/providers/void-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ import {
SuiMoveNormalizedStruct,
SuiMoveNormalizedModule,
SuiMoveNormalizedModules,
SuiEventFilter,
SuiEventEnvelope,
SubscriptionId,
ExecuteTransactionRequestType,
SuiExecuteTransactionResponse,
} from '../types';
Expand Down Expand Up @@ -123,6 +126,17 @@ export class VoidProvider extends Provider {
throw this.newError('syncAccountState');
}

async subscribeEvent(
_filter: SuiEventFilter,
_onMessage: (event: SuiEventEnvelope) => void
): Promise<SubscriptionId> {
throw this.newError('subscribeEvent');
}

async unsubscribeEvent(_id: SubscriptionId): Promise<boolean> {
throw this.newError('unsubscribeEvent');
}

private newError(operation: string): Error {
return new Error(`Please use a valid provider for ${operation}`);
}
Expand Down
Loading

0 comments on commit e046e01

Please sign in to comment.