Skip to content
This repository was archived by the owner on Dec 21, 2021. It is now read-only.

Commit 852973d

Browse files
committed
Type definitions
1 parent afdd50d commit 852973d

File tree

12 files changed

+333
-201
lines changed

12 files changed

+333
-201
lines changed

src/Config.js renamed to src/Config.ts

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
import qs from 'qs'
2+
// @ts-expect-error
23
import { ControlLayer, MessageLayer } from 'streamr-client-protocol'
34
import Debug from 'debug'
45

56
import { getVersionString, counterId } from './utils'
7+
import { StreamrClientOptions } from './StreamrClient'
68

79
const { ControlMessage } = ControlLayer
810
const { StreamMessage } = MessageLayer
911

10-
export default function ClientConfig(opts = {}) {
12+
export default function ClientConfig(opts: StreamrClientOptions = {}) {
1113
const { id = counterId('StreamrClient') } = opts
1214

13-
const options = {
15+
const options: StreamrClientOptions = {
1416
debug: Debug(id),
1517
// Authentication: identity used by this StreamrClient instance
1618
auth: {}, // can contain member privateKey or (window.)ethereum
@@ -39,15 +41,20 @@ export default function ClientConfig(opts = {}) {
3941
// For ethers.js provider params, see https://docs.ethers.io/ethers.js/v5-beta/api-providers.html#provider
4042
mainnet: null, // Default to ethers.js default provider settings
4143
sidechain: {
44+
// @ts-expect-error
4245
url: null, // TODO: add our default public service sidechain node, also find good PoA params below
4346
// timeout:
4447
// pollingInterval:
4548
},
49+
// @ts-expect-error
4650
dataUnion: null, // Give a "default target" of all data union endpoint operations (no need to pass argument every time)
4751
tokenAddress: '0x0Cf0Ee63788A0849fE5297F3407f701E122cC023',
4852
minimumWithdrawTokenWei: '1000000', // Threshold value set in AMB configs, smallest token amount to pass over the bridge
53+
// @ts-expect-error
4954
sidechainTokenAddress: null, // TODO // sidechain token
55+
// @ts-expect-error
5056
factoryMainnetAddress: null, // TODO // Data Union factory that creates a new Data Union
57+
// @ts-expect-error
5158
sidechainAmbAddress: null, // Arbitrary Message-passing Bridge (AMB), see https://github.com/poanetwork/tokenbridge
5259
payForSignatureTransport: true, // someone must pay for transporting the withdraw tx to mainnet, either us or bridge operator
5360
...opts,
@@ -58,7 +65,7 @@ export default function ClientConfig(opts = {}) {
5865
}
5966
}
6067

61-
const parts = options.url.split('?')
68+
const parts = options.url!.split('?')
6269
if (parts.length === 1) { // there is no query string
6370
const controlLayer = `controlLayerVersion=${ControlMessage.LATEST_VERSION}`
6471
const messageLayer = `messageLayerVersion=${StreamMessage.LATEST_VERSION}`
@@ -78,16 +85,20 @@ export default function ClientConfig(opts = {}) {
7885
options.url = `${options.url}&streamrClient=${getVersionString()}`
7986

8087
// Backwards compatibility for option 'authKey' => 'apiKey'
88+
// @ts-expect-error
8189
if (options.authKey && !options.apiKey) {
90+
// @ts-expect-error
8291
options.apiKey = options.authKey
8392
}
8493

94+
// @ts-expect-error
8595
if (options.apiKey) {
96+
// @ts-expect-error
8697
options.auth.apiKey = options.apiKey
8798
}
8899

89-
if (options.auth.privateKey && !options.auth.privateKey.startsWith('0x')) {
90-
options.auth.privateKey = `0x${options.auth.privateKey}`
100+
if (options.auth!.privateKey && !options.auth!.privateKey.startsWith('0x')) {
101+
options.auth!.privateKey = `0x${options.auth!.privateKey}`
91102
}
92103

93104
return options

src/Session.js renamed to src/Session.ts

Lines changed: 52 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,58 @@
11
import EventEmitter from 'eventemitter3'
22
import { Wallet } from '@ethersproject/wallet'
3-
import { Web3Provider } from '@ethersproject/providers'
3+
import { ExternalProvider, JsonRpcFetchFunc, Web3Provider } from '@ethersproject/providers'
4+
import StreamrClient from './StreamrClient'
5+
6+
enum State {
7+
LOGGING_OUT = 'logging out',
8+
LOGGED_OUT = 'logged out',
9+
LOGGING_IN ='logging in',
10+
LOGGED_IN = 'logged in',
11+
}
12+
13+
export interface SessionOptions {
14+
privateKey?: string
15+
ethereum?: ExternalProvider|JsonRpcFetchFunc
16+
apiKey?: string
17+
username?: string
18+
password?: string
19+
sessionToken?: string
20+
unauthenticated?: boolean
21+
}
22+
23+
export interface TokenObject {
24+
token: string
25+
}
426

527
export default class Session extends EventEmitter {
6-
constructor(client, options = {}) {
28+
29+
_client: StreamrClient
30+
options: SessionOptions
31+
state: State
32+
loginFunction: () => Promise<TokenObject>
33+
sessionTokenPromise?: Promise<string|undefined>
34+
35+
constructor(client: StreamrClient, options: SessionOptions = {}) {
736
super()
837
this._client = client
938
this.options = {
1039
...options
1140
}
1241

13-
this.state = Session.State.LOGGED_OUT
42+
this.state = State.LOGGED_OUT
1443

1544
// TODO: move loginFunction to StreamrClient constructor where "auth type" is checked
1645
if (typeof this.options.privateKey !== 'undefined') {
1746
const wallet = new Wallet(this.options.privateKey)
18-
this.loginFunction = async () => this._client.loginWithChallengeResponse((d) => wallet.signMessage(d), wallet.address)
47+
this.loginFunction = async () => this._client.loginEndpoints.loginWithChallengeResponse((d: string) => wallet.signMessage(d), wallet.address)
1948
} else if (typeof this.options.ethereum !== 'undefined') {
2049
const provider = new Web3Provider(this.options.ethereum)
2150
const signer = provider.getSigner()
22-
this.loginFunction = async () => this._client.loginWithChallengeResponse((d) => signer.signMessage(d), await signer.getAddress())
51+
this.loginFunction = async () => this._client.loginEndpoints.loginWithChallengeResponse((d: string) => signer.signMessage(d), await signer.getAddress())
2352
} else if (typeof this.options.apiKey !== 'undefined') {
24-
this.loginFunction = async () => this._client.loginWithApiKey(this.options.apiKey)
53+
this.loginFunction = async () => this._client.loginEndpoints.loginWithApiKey(this.options.apiKey!)
2554
} else if (typeof this.options.username !== 'undefined' && typeof this.options.password !== 'undefined') {
26-
this.loginFunction = async () => this._client.loginWithUsernamePassword(this.options.username, this.options.password)
55+
this.loginFunction = async () => this._client.loginEndpoints.loginWithUsernamePassword(this.options.username!, this.options.password!)
2756
} else {
2857
if (!this.options.sessionToken) {
2958
this.options.unauthenticated = true
@@ -38,7 +67,7 @@ export default class Session extends EventEmitter {
3867
return this.options.unauthenticated
3968
}
4069

41-
updateState(newState) {
70+
updateState(newState: State) {
4271
this.state = newState
4372
this.emit(newState)
4473
}
@@ -52,19 +81,19 @@ export default class Session extends EventEmitter {
5281
return undefined
5382
}
5483

55-
if (this.state !== Session.State.LOGGING_IN) {
56-
if (this.state === Session.State.LOGGING_OUT) {
84+
if (this.state !== State.LOGGING_IN) {
85+
if (this.state === State.LOGGING_OUT) {
5786
this.sessionTokenPromise = new Promise((resolve) => {
58-
this.once(Session.State.LOGGED_OUT, () => resolve(this.getSessionToken(requireNewToken)))
87+
this.once(State.LOGGED_OUT, () => resolve(this.getSessionToken(requireNewToken)))
5988
})
6089
} else {
61-
this.updateState(Session.State.LOGGING_IN)
62-
this.sessionTokenPromise = this.loginFunction().then((tokenObj) => {
90+
this.updateState(State.LOGGING_IN)
91+
this.sessionTokenPromise = this.loginFunction().then((tokenObj: TokenObject) => {
6392
this.options.sessionToken = tokenObj.token
64-
this.updateState(Session.State.LOGGED_IN)
93+
this.updateState(State.LOGGED_IN)
6594
return tokenObj.token
66-
}, (err) => {
67-
this.updateState(Session.State.LOGGED_OUT)
95+
}, (err: Error) => {
96+
this.updateState(State.LOGGED_OUT)
6897
throw err
6998
})
7099
}
@@ -73,31 +102,24 @@ export default class Session extends EventEmitter {
73102
}
74103

75104
async logout() {
76-
if (this.state === Session.State.LOGGED_OUT) {
105+
if (this.state === State.LOGGED_OUT) {
77106
throw new Error('Already logged out!')
78107
}
79108

80-
if (this.state === Session.State.LOGGING_OUT) {
109+
if (this.state === State.LOGGING_OUT) {
81110
throw new Error('Already logging out!')
82111
}
83112

84-
if (this.state === Session.State.LOGGING_IN) {
113+
if (this.state === State.LOGGING_IN) {
85114
await new Promise((resolve) => {
86-
this.once(Session.State.LOGGED_IN, () => resolve(this.logout()))
115+
this.once(State.LOGGED_IN, () => resolve(this.logout()))
87116
})
88117
return
89118
}
90119

91-
this.updateState(Session.State.LOGGING_OUT)
92-
await this._client.logoutEndpoint()
120+
this.updateState(State.LOGGING_OUT)
121+
await this._client.loginEndpoints.logoutEndpoint()
93122
this.options.sessionToken = undefined
94-
this.updateState(Session.State.LOGGED_OUT)
123+
this.updateState(State.LOGGED_OUT)
95124
}
96125
}
97-
98-
Session.State = {
99-
LOGGING_OUT: 'logging out',
100-
LOGGED_OUT: 'logged out',
101-
LOGGING_IN: 'logging in',
102-
LOGGED_IN: 'logged in',
103-
}

0 commit comments

Comments
 (0)