@portal-hq/connect 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const react_1 = __importDefault(require("react"));
7
+ const react_native_1 = require("react-native");
8
+ const WalletScanner = () => {
9
+ return (react_1.default.createElement(react_1.default.Fragment, null,
10
+ react_1.default.createElement(react_native_1.Text, null, "Yo!")));
11
+ };
12
+ exports.default = WalletScanner;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ class PortalConnect {
13
+ constructor({ portal, websocketServer = 'connect.portalhq.io', }) {
14
+ this.portal = portal;
15
+ this.websocketServer = websocketServer;
16
+ }
17
+ /**
18
+ * Establishes a websocket connection with the Connect Proxy and dispatches the binding
19
+ * of websocket events for the newly established socket
20
+ *
21
+ * @param connectionString The URI to ask the Connect Proxy to create a websocket connection to
22
+ */
23
+ connect(uri) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ if (this.socket) {
26
+ this.socket.close();
27
+ }
28
+ this.socket = new WebSocket(`wss://${this.websocketServer}`);
29
+ this.bindToSocketEvents(this.socket, uri);
30
+ });
31
+ }
32
+ /**
33
+ * Adds event bindings to a websocket connection
34
+ * - on open, a `connect` event is dispatched via the socket to establish a bridge connection
35
+ *
36
+ * @param socket The websocket connection to bind events to
37
+ * @param uri The URI to ask the Connect Proxy to create a websocket connection to
38
+ */
39
+ bindToSocketEvents(socket, uri) {
40
+ /**
41
+ * Initial websocket handler fired when connection with the proxy server is established
42
+ * - Fires a subsequent call over the websocket to notify the proxy of the uri to connect to
43
+ */
44
+ socket.onopen = () => __awaiter(this, void 0, void 0, function* () {
45
+ const { address, chainId } = this.portal.provider;
46
+ // Tell the proxy server where to connect to downstream
47
+ socket.send(JSON.stringify({
48
+ event: 'connect',
49
+ data: {
50
+ address,
51
+ chainId,
52
+ uri,
53
+ },
54
+ }));
55
+ });
56
+ /**
57
+ * Handles all incoming messages over the websocket connection
58
+ * (inbound messages proxied via the relay)
59
+ * @param messageEvent
60
+ * @returns
61
+ */
62
+ socket.onmessage = (messageEvent) => __awaiter(this, void 0, void 0, function* () {
63
+ const message = JSON.parse(messageEvent.data);
64
+ switch (message.event) {
65
+ case 'close':
66
+ socket.close();
67
+ break;
68
+ case 'connected':
69
+ const { active } = message.data;
70
+ if (!active) {
71
+ // Proxy is not connected to the bridge
72
+ console.warn(`PortalConnect could not establish a connection to the relay.`);
73
+ return;
74
+ }
75
+ break;
76
+ case 'session_request':
77
+ const { id, params, topic } = message.data;
78
+ // Sign the transaction and get back a transaction hash
79
+ const txHash = yield this.handleProviderRequest(params.request.method, params.request.params);
80
+ // Let the server know the transaction hash
81
+ socket.send(JSON.stringify({
82
+ event: 'signatureReceived',
83
+ data: {
84
+ topic,
85
+ transactionHash: txHash,
86
+ transactionId: id,
87
+ },
88
+ }));
89
+ break;
90
+ default:
91
+ console.log(`Recieved unsupported event "${message.event}". Ignoring.`);
92
+ break;
93
+ }
94
+ });
95
+ }
96
+ /**
97
+ * Proxies inbound requests to the Portal provider
98
+ *
99
+ * @param method The method for the provider request
100
+ * @param params The params for the provider request
101
+ *
102
+ * @returns The result of the provider request
103
+ */
104
+ handleProviderRequest(method, params) {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ // Pass the request along to the provider
107
+ const result = yield this.portal.provider.request({ method, params });
108
+ return result;
109
+ });
110
+ }
111
+ }
112
+ exports.default = PortalConnect;
@@ -0,0 +1,7 @@
1
+ import React from 'react';
2
+ import { Text } from 'react-native';
3
+ const WalletScanner = () => {
4
+ return (React.createElement(React.Fragment, null,
5
+ React.createElement(Text, null, "Yo!")));
6
+ };
7
+ export default WalletScanner;
@@ -0,0 +1,110 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ class PortalConnect {
11
+ constructor({ portal, websocketServer = 'connect.portalhq.io', }) {
12
+ this.portal = portal;
13
+ this.websocketServer = websocketServer;
14
+ }
15
+ /**
16
+ * Establishes a websocket connection with the Connect Proxy and dispatches the binding
17
+ * of websocket events for the newly established socket
18
+ *
19
+ * @param connectionString The URI to ask the Connect Proxy to create a websocket connection to
20
+ */
21
+ connect(uri) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ if (this.socket) {
24
+ this.socket.close();
25
+ }
26
+ this.socket = new WebSocket(`wss://${this.websocketServer}`);
27
+ this.bindToSocketEvents(this.socket, uri);
28
+ });
29
+ }
30
+ /**
31
+ * Adds event bindings to a websocket connection
32
+ * - on open, a `connect` event is dispatched via the socket to establish a bridge connection
33
+ *
34
+ * @param socket The websocket connection to bind events to
35
+ * @param uri The URI to ask the Connect Proxy to create a websocket connection to
36
+ */
37
+ bindToSocketEvents(socket, uri) {
38
+ /**
39
+ * Initial websocket handler fired when connection with the proxy server is established
40
+ * - Fires a subsequent call over the websocket to notify the proxy of the uri to connect to
41
+ */
42
+ socket.onopen = () => __awaiter(this, void 0, void 0, function* () {
43
+ const { address, chainId } = this.portal.provider;
44
+ // Tell the proxy server where to connect to downstream
45
+ socket.send(JSON.stringify({
46
+ event: 'connect',
47
+ data: {
48
+ address,
49
+ chainId,
50
+ uri,
51
+ },
52
+ }));
53
+ });
54
+ /**
55
+ * Handles all incoming messages over the websocket connection
56
+ * (inbound messages proxied via the relay)
57
+ * @param messageEvent
58
+ * @returns
59
+ */
60
+ socket.onmessage = (messageEvent) => __awaiter(this, void 0, void 0, function* () {
61
+ const message = JSON.parse(messageEvent.data);
62
+ switch (message.event) {
63
+ case 'close':
64
+ socket.close();
65
+ break;
66
+ case 'connected':
67
+ const { active } = message.data;
68
+ if (!active) {
69
+ // Proxy is not connected to the bridge
70
+ console.warn(`PortalConnect could not establish a connection to the relay.`);
71
+ return;
72
+ }
73
+ break;
74
+ case 'session_request':
75
+ const { id, params, topic } = message.data;
76
+ // Sign the transaction and get back a transaction hash
77
+ const txHash = yield this.handleProviderRequest(params.request.method, params.request.params);
78
+ // Let the server know the transaction hash
79
+ socket.send(JSON.stringify({
80
+ event: 'signatureReceived',
81
+ data: {
82
+ topic,
83
+ transactionHash: txHash,
84
+ transactionId: id,
85
+ },
86
+ }));
87
+ break;
88
+ default:
89
+ console.log(`Recieved unsupported event "${message.event}". Ignoring.`);
90
+ break;
91
+ }
92
+ });
93
+ }
94
+ /**
95
+ * Proxies inbound requests to the Portal provider
96
+ *
97
+ * @param method The method for the provider request
98
+ * @param params The params for the provider request
99
+ *
100
+ * @returns The result of the provider request
101
+ */
102
+ handleProviderRequest(method, params) {
103
+ return __awaiter(this, void 0, void 0, function* () {
104
+ // Pass the request along to the provider
105
+ const result = yield this.portal.provider.request({ method, params });
106
+ return result;
107
+ });
108
+ }
109
+ }
110
+ export default PortalConnect;
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@portal-hq/connect",
3
+ "version": "0.3.1",
4
+ "main": "lib/commonjs/index",
5
+ "module": "lib/esm/index",
6
+ "source": "src/index",
7
+ "types": "src/index",
8
+ "license": "MIT",
9
+ "files": [
10
+ "src",
11
+ "lib",
12
+ "types.d.ts"
13
+ ],
14
+ "scripts": {
15
+ "coverage": "jest --collect-coverage",
16
+ "prepare": "yarn prepare:cjs && yarn prepare:esm",
17
+ "prepare:cjs": "tsc --outDir lib/commonjs --module commonjs",
18
+ "prepare:esm": "tsc --outDir lib/esm --module es2015 --target es2015",
19
+ "test": "jest"
20
+ },
21
+ "devDependencies": {
22
+ "@babel/preset-typescript": "^7.18.6",
23
+ "@types/jest": "^29.2.0",
24
+ "jest": "^29.2.1",
25
+ "jest-environment-jsdom": "^29.2.2",
26
+ "ts-jest": "^29.0.3",
27
+ "typescript": "^4.8.4"
28
+ },
29
+ "peerDependencies": {
30
+ "@portal-hq/core": "*",
31
+ "react": "*",
32
+ "react-native": "*"
33
+ }
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1,136 @@
1
+ import Portal from '@portal-hq/core'
2
+ import type {
3
+ ConnectResult,
4
+ PortalConnectOptions,
5
+ SessionRequest,
6
+ WebsocketMessage,
7
+ } from '../types'
8
+
9
+ class PortalConnect {
10
+ public portal: Portal
11
+ public socket?: WebSocket
12
+ public websocketServer: string
13
+
14
+ constructor({
15
+ portal,
16
+ websocketServer = 'connect.portalhq.io',
17
+ }: PortalConnectOptions) {
18
+ this.portal = portal
19
+ this.websocketServer = websocketServer
20
+ }
21
+
22
+ /**
23
+ * Establishes a websocket connection with the Connect Proxy and dispatches the binding
24
+ * of websocket events for the newly established socket
25
+ *
26
+ * @param connectionString The URI to ask the Connect Proxy to create a websocket connection to
27
+ */
28
+ public async connect(uri: string): Promise<void> {
29
+ if (this.socket) {
30
+ this.socket.close()
31
+ }
32
+
33
+ this.socket = new WebSocket(`wss://${this.websocketServer}`)
34
+ this.bindToSocketEvents(this.socket, uri)
35
+ }
36
+
37
+ /**
38
+ * Adds event bindings to a websocket connection
39
+ * - on open, a `connect` event is dispatched via the socket to establish a bridge connection
40
+ *
41
+ * @param socket The websocket connection to bind events to
42
+ * @param uri The URI to ask the Connect Proxy to create a websocket connection to
43
+ */
44
+ private bindToSocketEvents(socket: WebSocket, uri: string): void {
45
+ /**
46
+ * Initial websocket handler fired when connection with the proxy server is established
47
+ * - Fires a subsequent call over the websocket to notify the proxy of the uri to connect to
48
+ */
49
+ socket.onopen = async () => {
50
+ const { address, chainId } = this.portal.provider
51
+
52
+ // Tell the proxy server where to connect to downstream
53
+ socket.send(
54
+ JSON.stringify({
55
+ event: 'connect',
56
+ data: {
57
+ address,
58
+ chainId,
59
+ uri,
60
+ },
61
+ }),
62
+ )
63
+ }
64
+
65
+ /**
66
+ * Handles all incoming messages over the websocket connection
67
+ * (inbound messages proxied via the relay)
68
+ * @param messageEvent
69
+ * @returns
70
+ */
71
+ socket.onmessage = async (messageEvent: MessageEvent) => {
72
+ const message = JSON.parse(messageEvent.data) as WebsocketMessage
73
+
74
+ switch (message.event) {
75
+ case 'close':
76
+ socket.close()
77
+ break
78
+ case 'connected':
79
+ const { active } = message.data as ConnectResult
80
+ if (!active) {
81
+ // Proxy is not connected to the bridge
82
+ console.warn(
83
+ `PortalConnect could not establish a connection to the relay.`,
84
+ )
85
+ return
86
+ }
87
+ break
88
+ case 'session_request':
89
+ const { id, params, topic } = message.data as SessionRequest
90
+ // Sign the transaction and get back a transaction hash
91
+ const txHash = await this.handleProviderRequest(
92
+ params.request.method,
93
+ params.request.params,
94
+ )
95
+
96
+ // Let the server know the transaction hash
97
+ socket.send(
98
+ JSON.stringify({
99
+ event: 'signatureReceived',
100
+ data: {
101
+ topic,
102
+ transactionHash: txHash,
103
+ transactionId: id,
104
+ },
105
+ }),
106
+ )
107
+ break
108
+ default:
109
+ console.log(
110
+ `Recieved unsupported event "${message.event}". Ignoring.`,
111
+ )
112
+ break
113
+ }
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Proxies inbound requests to the Portal provider
119
+ *
120
+ * @param method The method for the provider request
121
+ * @param params The params for the provider request
122
+ *
123
+ * @returns The result of the provider request
124
+ */
125
+ private async handleProviderRequest(
126
+ method: string,
127
+ params: any,
128
+ ): Promise<any> {
129
+ // Pass the request along to the provider
130
+ const result = await this.portal.provider.request({ method, params })
131
+
132
+ return result
133
+ }
134
+ }
135
+
136
+ export default PortalConnect
package/types.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import Portal from '@portal-hq/core'
2
+
3
+ interface ConnectResult {
4
+ active: boolean
5
+ expiry: number
6
+ peerMetadata: PeerMetadata
7
+ relay: ProtocolOptions
8
+ topic: string
9
+ }
10
+
11
+ interface PeerMetadata {
12
+ name: string
13
+ description: string
14
+ url: string
15
+ icons: string[]
16
+ }
17
+
18
+ interface PortalConnectOptions {
19
+ portal: Portal
20
+ websocketServer?: string
21
+ }
22
+
23
+ interface ProtocolOptions {
24
+ protocol: string
25
+ data?: string
26
+ }
27
+
28
+ interface ProviderRequestPayload {
29
+ chainId: string
30
+ request: ProviderRequestData
31
+ }
32
+
33
+ interface ProviderRequestData {
34
+ method: string
35
+ params: any
36
+ }
37
+
38
+ interface SessionRequest {
39
+ id: string
40
+ params: ProviderRequestPayload
41
+ topic: string
42
+ }
43
+
44
+ interface WebsocketMessage {
45
+ event: string
46
+ data: ConnectResult | SessionRequest
47
+ }