This repository has been archived by the owner on May 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.ts
358 lines (323 loc) · 11.2 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import * as connext from "@connext/client";
import {
getRandomBytes32,
getPublicIdentifierFromPublicKey,
getPublicKeyFromPrivateKey,
} from "@connext/utils";
import { IConnextClient, ConditionalTransferTypes, PublicParams } from "@connext/types";
import { constants, utils } from "ethers";
import {
getClientBalance,
getFreeBalanceOnChain,
EventSubscriptionParams,
InitClientManagerOptions,
SubscriptionResponse,
BatchSubscriptionResponse,
GenericSuccessResponse,
RouteMethods,
getStore,
InternalConnectOptions,
} from "./helpers";
import Subscriber from "./subscriber";
import Funder from "./funder";
const { AddressZero, HashZero } = constants;
export default class Client {
public client: IConnextClient | undefined;
private logger: any;
private subscriber: Subscriber;
private connecting = false;
private logLevel: number;
private cleanUpInterval: NodeJS.Timeout | undefined;
private cleaningUp = false;
constructor(opts: InitClientManagerOptions) {
this.subscriber = new Subscriber(opts.logger, opts.store);
this.logger = opts.logger;
this.logLevel = opts.logLevel;
}
public async connect(
rootStoreDir: string,
opts: InternalConnectOptions,
): Promise<IConnextClient> {
if (this.cleaningUp) throw new Error(`Client is cleaning up`);
if (this.connecting) {
throw new Error(`Client is connecting`);
}
if (this.client) {
this.logger.info("Client is already connected - skipping connect logic");
return this.client;
}
this.connecting = true;
const publicIdentifier = getPublicIdentifierFromPublicKey(
getPublicKeyFromPrivateKey(opts.signer),
);
const store = await getStore(rootStoreDir, publicIdentifier);
const clientOpts = {
store,
signer: opts.signer,
ethProviderUrl: opts.ethProviderUrl,
nodeUrl: opts.nodeUrl,
messagingUrl: opts.messagingUrl,
logLevel: this.logLevel,
};
try {
const client = await connext.connect(clientOpts);
this.client = client;
this.logger.info("Client initialized successfully");
return client;
} finally {
this.connecting = false;
this.scheduleCleanup();
}
}
public scheduleCleanup(): void {
if (typeof this.cleanUpInterval !== "undefined") clearInterval(this.cleanUpInterval);
this.cleanUpInterval = setInterval(
this.cleanupRegistryApps,
86_400_000, // 24 hours
);
}
public async cleanupRegistryApps(): Promise<void> {
const client = this.getClient();
this.cleaningUp = true;
await (client as connext.ConnextClient).cleanupRegistryApps();
this.cleaningUp = false;
}
public getConfig(): RouteMethods.GetConfigResponse {
const client = this.getClient();
const config = {
multisigAddress: undefined,
...client.channelProvider.config,
};
if (!config.multisigAddress) {
throw new Error("Connext Client Not Yet Initialized");
}
return config;
}
public async getTransferHistory(): Promise<RouteMethods.GetTransferHistoryResponse> {
const client = this.getClient();
const transferHistory = await client.getTransferHistory();
return transferHistory;
}
public async getAppInstanceDetails(
appIdentityHash: string,
): Promise<RouteMethods.GetAppInstanceDetailsResponse> {
const client = this.getClient();
const appDetails = await client.getAppInstance(appIdentityHash);
if (typeof appDetails === "undefined") {
throw new Error(`No App Instance found with appIdentityHash: ${appIdentityHash}`);
}
const data = appDetails;
return data;
}
public rejectInstallApp(
appIdentityHash: string,
reason?: string,
): Promise<RouteMethods.PostRejectInstallResponse> {
const client = this.getClient();
return client.rejectInstallApp(appIdentityHash, reason);
}
public async hashLockTransfer(
params: RouteMethods.PostHashLockTransferRequestParams,
): Promise<RouteMethods.PostHashLockTransferResponse> {
const client = this.getClient();
if (params.assetId === AddressZero) {
delete params.assetId;
}
const response = await client.conditionalTransfer({
conditionType: ConditionalTransferTypes.HashLockTransfer,
amount: params.amount,
recipient: params.recipient,
lockHash: params.lockHash,
assetId: params.assetId && utils.getAddress(params.assetId),
meta: params.meta,
timelock: params.timelock,
} as PublicParams.ConditionalTransfer);
const appDetails = await this.getAppInstanceDetails(response.appIdentityHash);
const data = { ...response, ...appDetails };
return data;
}
public async hashLockResolve(
params: RouteMethods.PostHashLockResolveRequestParams,
): Promise<RouteMethods.PostHashLockResolveResponse> {
const client = this.getClient();
const response = await client.resolveCondition({
conditionType: ConditionalTransferTypes.HashLockTransfer,
preImage: params.preImage || HashZero,
assetId: params.assetId,
paymentId: params.paymentId,
} as PublicParams.ResolveHashLockTransfer);
return response;
}
public async hashLockStatus(
lockHash: string,
assetId: string,
): Promise<RouteMethods.GetHashLockStatusResponse> {
const client = this.getClient();
const response = await client.getHashLockTransfer(lockHash, assetId);
if (!response) {
throw new Error(
`No HashLock Transfer found for lockHash: ${lockHash} and assetId: ${assetId}`,
);
}
return { ...response, paymentId: response.meta.paymentId };
}
public async linkedStatus(paymentId: string): Promise<RouteMethods.GetLinkedStatusResponse> {
const client = this.getClient();
const response = await client.getLinkedTransfer(paymentId);
if (!response) {
throw new Error(`No Linked Transfer found for paymentId: ${paymentId}`);
}
const data = response;
return data;
}
public async linkedTransfer(
params: RouteMethods.PostLinkedTransferRequestParams,
): Promise<RouteMethods.PostLinkedTransferResponse> {
const client = this.getClient();
if (params.assetId === AddressZero) {
delete params.assetId;
}
const paymentId = params.paymentId || getRandomBytes32();
const preImage = params.preImage || getRandomBytes32();
const response = await client.conditionalTransfer({
conditionType: params.requireOnline
? ConditionalTransferTypes.OnlineTransfer
: ConditionalTransferTypes.LinkedTransfer,
amount: params.amount,
recipient: params.recipient,
preImage,
paymentId,
assetId: params.assetId,
meta: params.meta,
} as PublicParams.ConditionalTransfer);
const appDetails = await this.getAppInstanceDetails(response.appIdentityHash);
const data = { ...response, ...appDetails };
return data;
}
public async linkedResolve(
params: RouteMethods.PostLinkedResolveRequestParams,
): Promise<RouteMethods.PostLinkedResolveResponse> {
const client = this.getClient();
const response = await client.resolveCondition({
conditionType: ConditionalTransferTypes.LinkedTransfer,
preImage: params.preImage,
paymentId: params.paymentId,
} as PublicParams.ResolveLinkedTransfer);
const data = response;
return data;
}
public balance(assetId: string): Promise<RouteMethods.GetBalanceResponse> {
const client = this.getClient();
return getClientBalance(client, assetId);
}
public async fund(
amount: string,
assetId: string,
funder: Funder,
): Promise<RouteMethods.PostFundResponse> {
const client = this.getClient();
funder.setProvider(client.ethProvider);
await client.requestDepositRights({ assetId });
const txhash = await funder.fund(client.multisigAddress, amount, assetId);
await client.rescindDepositRights({ assetId });
return { txhash };
}
public async deposit(
params: RouteMethods.PostDepositRequestParams,
): Promise<RouteMethods.PostDepositResponse> {
const client = this.getClient();
if (params.assetId === AddressZero) {
delete params.assetId;
}
const response = await client.deposit(params);
return { txhash: response.transaction.hash };
}
public async requestDepositRights(
params: RouteMethods.PostRequestDepositRightsRequestParams,
): Promise<RouteMethods.PostRequestDepositRightsResponse> {
const client = this.getClient();
if (params.assetId === AddressZero) {
delete params.assetId;
}
const response = await client.requestDepositRights(params);
return response;
}
public async rescindDepositRights(
params: RouteMethods.PostRescindDepositRightsRequestParams,
): Promise<RouteMethods.PostRescindDepositRightsResponse> {
const client = this.getClient();
if (params.assetId === AddressZero) {
delete params.assetId;
}
const response = await client.rescindDepositRights(params);
return { freeBalance: response.freeBalance[client.signerAddress].toString() };
}
public async requestCollateral(
params: RouteMethods.PostRequestCollateralRequestParams,
): Promise<void> {
const client = this.getClient();
await client.requestCollateral(params.assetId, params.amount);
}
public async swap(
params: RouteMethods.PostSwapRequestParams,
): Promise<RouteMethods.PostSwapResponse> {
const client = this.getClient();
await client.swap(params);
return {
fromAssetIdBalance: await getFreeBalanceOnChain(
client.signerAddress,
client.ethProvider,
params.fromAssetId,
),
toAssetIdBalance: await getFreeBalanceOnChain(
client.signerAddress,
client.ethProvider,
params.toAssetId,
),
};
}
public async withdraw(
params: RouteMethods.PostWithdrawRequestParams,
): Promise<RouteMethods.PostWithdrawResponse> {
const client = this.getClient();
if (params.assetId === AddressZero) {
delete params.assetId;
}
const response = await client.withdraw(params);
return { txhash: response.transaction.hash };
}
public async subscribe(params: EventSubscriptionParams): Promise<SubscriptionResponse> {
const client = this.getClient();
const subscription = await this.subscriber.subscribe(client, params);
return { id: subscription.id };
}
public async subscribeBatch(
paramsArr: EventSubscriptionParams[],
): Promise<BatchSubscriptionResponse> {
const client = this.getClient();
const subscriptions = await this.subscriber.batchSubscribe(client, paramsArr);
return { subscriptions };
}
public async unsubscribe(id: string): Promise<GenericSuccessResponse> {
const client = this.getClient();
await this.subscriber.unsubscribe(client, id);
return { success: true };
}
public async unsubscribeBatch(idsArr: string[]): Promise<GenericSuccessResponse> {
const client = this.getClient();
await this.subscriber.batchUnsubscribe(client, idsArr);
return { success: true };
}
public async unsubscribeAll(): Promise<GenericSuccessResponse> {
const client = this.getClient();
await this.subscriber.clearAllSubscriptions(client);
return { success: true };
}
public getClient(): IConnextClient {
if (!this.client) {
throw new Error("Client is not initialized");
}
if (this.cleaningUp) throw new Error(`Client is cleanning up`);
return this.client;
}
}