-
Notifications
You must be signed in to change notification settings - Fork 29
/
raiden.ts
1378 lines (1268 loc) · 53.5 KB
/
raiden.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import './polyfills';
import { Signer } from 'ethers/abstract-signer';
import { AsyncSendable, Web3Provider, JsonRpcProvider } from 'ethers/providers';
import { Network, BigNumber, BigNumberish, bigNumberify } from 'ethers/utils';
import { Zero, AddressZero, MaxUint256 } from 'ethers/constants';
import { MatrixClient } from 'matrix-js-sdk';
import { applyMiddleware, createStore, Store } from 'redux';
import { createEpicMiddleware, EpicMiddleware } from 'redux-observable';
import { createLogger } from 'redux-logger';
import constant from 'lodash/constant';
import memoize from 'lodash/memoize';
import { Observable, AsyncSubject, merge, defer, EMPTY, ReplaySubject, of } from 'rxjs';
import { first, filter, map, mergeMap, skip, pluck } from 'rxjs/operators';
import logging from 'loglevel';
import { TokenNetworkRegistryFactory } from './contracts/TokenNetworkRegistryFactory';
import { TokenNetworkFactory } from './contracts/TokenNetworkFactory';
import { HumanStandardTokenFactory } from './contracts/HumanStandardTokenFactory';
import { ServiceRegistryFactory } from './contracts/ServiceRegistryFactory';
import { CustomTokenFactory } from './contracts/CustomTokenFactory';
import { UserDepositFactory } from './contracts/UserDepositFactory';
import { SecretRegistryFactory } from './contracts/SecretRegistryFactory';
import { MonitoringServiceFactory } from './contracts/MonitoringServiceFactory';
import versions from './versions.json';
import { ContractsInfo, EventTypes, OnChange, RaidenEpicDeps, Latest } from './types';
import { ShutdownReason } from './constants';
import { RaidenState } from './state';
import { RaidenConfig, PartialRaidenConfig, makeDefaultConfig } from './config';
import { RaidenChannels, ChannelState } from './channels/state';
import { RaidenTransfer, Direction, TransferState } from './transfers/state';
import { raidenReducer } from './reducer';
import { raidenRootEpic, getLatest$ } from './epics';
import {
RaidenAction,
RaidenEvents,
RaidenEvent,
raidenShutdown,
raidenConfigUpdate,
} from './actions';
import { assert } from './utils';
import {
channelOpen,
channelDeposit,
channelClose,
channelSettle,
tokenMonitored,
} from './channels/actions';
import { channelKey, channelAmounts } from './channels/utils';
import { matrixPresence } from './transport/actions';
import { transfer, transferSigned, withdraw } from './transfers/actions';
import {
makeSecret,
getSecrethash,
makePaymentId,
raidenTransfer,
transferKey,
transferKeyToMeta,
} from './transfers/utils';
import { pathFind, udcWithdraw, udcDeposit } from './services/actions';
import { Paths, RaidenPaths, PFS, RaidenPFS, IOU } from './services/types';
import { pfsListInfo } from './services/utils';
import { Address, Secret, Storage, Hash, UInt, decode } from './utils/types';
import { isActionOf, asyncActionToPromise, isResponseOf } from './utils/actions';
import { patchSignSend } from './utils/ethers';
import { pluckDistinct } from './utils/rx';
import {
getContracts,
getSigner,
initTransfers$,
mapRaidenChannels,
chooseOnchainAccount,
getContractWithSigner,
waitConfirmation,
callAndWaitMined,
fetchContractsInfo,
getUdcBalance,
getState,
} from './helpers';
import { RaidenError, ErrorCodes } from './utils/error';
import { RaidenDatabase } from './db/types';
import { dumpDatabaseToArray } from './db/utils';
import { createPersisterMiddleware } from './persister';
export class Raiden {
private readonly store: Store<RaidenState, RaidenAction>;
private readonly deps: RaidenEpicDeps;
/**
* action$ exposes the internal events pipeline. It's intended for debugging, and its interface
* must not be relied on, as its actions interfaces and structures can change without warning.
*/
public readonly action$: Observable<RaidenAction>;
/**
* state$ is exposed only so user can listen to state changes and persist them somewhere else.
* Format/content of the emitted objects are subject to changes and not part of the public API
*/
public readonly state$: Observable<RaidenState>;
/**
* channels$ is public interface, exposing a view of the currently known channels
* Its format is expected to be kept backwards-compatible, and may be relied on
*/
public readonly channels$: Observable<RaidenChannels>;
/**
* A subset ot RaidenActions exposed as public events.
* The interface of the objects emitted by this Observable are expected not to change internally,
* but more/new events may be added over time.
*/
public readonly events$: Observable<RaidenEvent>;
/**
* Observable of completed and pending transfers
* Every time a transfer state is updated, it's emitted here. 'key' property is unique and
* may be used as identifier to know which transfer got updated.
*/
public readonly transfers$: Observable<RaidenTransfer>;
/** RaidenConfig object */
public config!: RaidenConfig;
/** RaidenConfig observable (for reactive use) */
public config$: Observable<RaidenConfig>;
/**
* Expose ether's Provider.resolveName for ENS support
*/
public readonly resolveName: (name: string) => Promise<Address>;
/**
* The address of the token that is used to pay the services.
*/
public userDepositTokenAddress: () => Promise<Address>;
/**
* Get constant token details from token contract, caches it.
* Rejects only if 'token' contract doesn't define totalSupply and decimals methods.
* name and symbol may be undefined, as they aren't actually part of ERC20 standard, although
* very common and defined on most token contracts.
*
* @param token - address to fetch info from
* @returns token info
*/
public getTokenInfo: (
this: Raiden,
token: string,
) => Promise<{
totalSupply: BigNumber;
decimals: number;
name?: string;
symbol?: string;
}>;
private epicMiddleware?: EpicMiddleware<
RaidenAction,
RaidenAction,
RaidenState,
RaidenEpicDeps
> | null;
/** Instance's Logger, compatible with console's API */
private readonly log: logging.Logger;
public constructor(
provider: JsonRpcProvider,
network: Network,
signer: Signer,
contractsInfo: ContractsInfo,
{
db,
state,
config,
}: { state: RaidenState; db: RaidenDatabase; config?: PartialRaidenConfig },
main?: { address: Address; signer: Signer },
) {
const address = state.address;
this.resolveName = provider.resolveName.bind(provider) as (name: string) => Promise<Address>;
this.log = logging.getLogger(`raiden:${address}`);
const defaultConfig = makeDefaultConfig(
{ network },
config && decode(PartialRaidenConfig, config),
);
// use next from latest known blockNumber as start block when polling
provider.resetEventsBlock(state.blockNumber + 1);
const latest$ = new ReplaySubject<Latest>(1);
// pipe cached state
this.state$ = latest$.pipe(pluckDistinct('state'));
// pipe action, skipping cached
this.action$ = latest$.pipe(pluckDistinct('action'), skip(1));
this.channels$ = this.state$.pipe(pluckDistinct('channels'), map(mapRaidenChannels));
this.transfers$ = initTransfers$(this.state$, db);
this.events$ = this.action$.pipe(filter(isActionOf(RaidenEvents)));
this.getTokenInfo = memoize(async function (this: Raiden, token: string) {
assert(Address.is(token), [ErrorCodes.DTA_INVALID_ADDRESS, { token }], this.log.info);
const tokenContract = this.deps.getTokenContract(token);
const [totalSupply, decimals, name, symbol] = await Promise.all([
tokenContract.functions.totalSupply(),
tokenContract.functions.decimals(),
tokenContract.functions.name().catch(constant(undefined)),
tokenContract.functions.symbol().catch(constant(undefined)),
]);
// workaround for https://github.com/microsoft/TypeScript/issues/33752
assert(totalSupply && decimals != null, ErrorCodes.RDN_NOT_A_TOKEN, this.log.info);
return { totalSupply, decimals, name, symbol };
});
this.deps = {
latest$,
config$: latest$.pipe(pluckDistinct('config')),
matrix$: new AsyncSubject<MatrixClient>(),
provider,
network,
signer,
address,
log: this.log,
defaultConfig,
contractsInfo,
registryContract: TokenNetworkRegistryFactory.connect(
contractsInfo.TokenNetworkRegistry.address,
main?.signer ?? signer,
),
getTokenNetworkContract: memoize((address: Address) =>
TokenNetworkFactory.connect(address, main?.signer ?? signer),
),
getTokenContract: memoize((address: Address) =>
HumanStandardTokenFactory.connect(address, main?.signer ?? signer),
),
serviceRegistryContract: ServiceRegistryFactory.connect(
contractsInfo.ServiceRegistry.address,
main?.signer ?? signer,
),
userDepositContract: UserDepositFactory.connect(
contractsInfo.UserDeposit.address,
main?.signer ?? signer,
),
secretRegistryContract: SecretRegistryFactory.connect(
contractsInfo.SecretRegistry.address,
main?.signer ?? signer,
),
monitoringServiceContract: MonitoringServiceFactory.connect(
contractsInfo.MonitoringService.address,
main?.signer ?? signer,
),
main,
db,
};
this.userDepositTokenAddress = memoize(
async () => (await this.deps.userDepositContract.functions.token()) as Address,
);
const loggerMiddleware = createLogger({
predicate: () => this.log.getLevel() <= logging.levels.INFO,
logger: this.log,
level: {
prevState: false,
action: 'info',
error: 'error',
nextState: 'debug',
},
});
this.config$ = this.deps.config$;
this.config$.subscribe((config) => (this.config = config));
// minimum blockNumber of contracts deployment as start scan block
this.epicMiddleware = createEpicMiddleware<
RaidenAction,
RaidenAction,
RaidenState,
RaidenEpicDeps
>({ dependencies: this.deps });
const persisterMiddleware = createPersisterMiddleware(db);
this.store = createStore(
raidenReducer,
// workaround for redux's PreloadedState issues with branded values
state as any, // eslint-disable-line @typescript-eslint/no-explicit-any
applyMiddleware(loggerMiddleware, persisterMiddleware, this.epicMiddleware),
);
// populate deps.latest$, to ensure config, logger && pollingInterval are setup before start
getLatest$(
of(raidenConfigUpdate({})),
of(this.store.getState()),
this.deps,
).subscribe((latest) => this.deps.latest$.next(latest));
}
/**
* Async helper factory to make a Raiden instance from more common parameters.
*
* An async factory is needed so we can do the needed async requests to construct the required
* parameters ahead of construction time, and avoid partial initialization then
*
* @param this - Raiden class or subclass
* @param connection - A URL or provider to connect to, one of:
* <ul>
* <li>JsonRpcProvider instance,</li>
* <li>a Metamask's web3.currentProvider object or,</li>
* <li>a hostname or remote json-rpc connection string</li>
* </ul>
* @param account - An account to use as main account, one of:
* <ul>
* <li>Signer instance (e.g. Wallet) loadded with account/private key or</li>
* <li>hex-encoded string address of a remote account in provider or</li>
* <li>hex-encoded string local private key or</li>
* <li>number index of a remote account loaded in provider
* (e.g. 0 for Metamask's loaded account)</li>
* </ul>
* @param storage - Storage/localStorage-like object from where to load and store current
* state, initial RaidenState-like object, or a { storage; state? } object containing both.
* If a storage isn't provided, user must listen state$ changes on ensure it's persisted.
* @param storage.state - State uploaded by user; should be decodable by RaidenState;
* it is auto-migrated
* @param storage.storage - Legacy localStorage; will load states from there if matching
* @param storage.adapter - PouchDB adapter; default to 'indexeddb' on browsers and 'leveldb' on
* node. If you provide a custom one, ensure you call PouchDB.plugin on it.
* @param storage.prefix - Database name prefix; use to set a directory to store leveldown db;
* @param contractsOrUDCAddress - Contracts deployment info, or UserDeposit contract address
* @param config - Raiden configuration
* @param subkey - Whether to use a derived subkey or not
* @returns Promise to Raiden SDK client instance
*/
public static async create<R extends typeof Raiden>(
this: R,
connection: JsonRpcProvider | AsyncSendable | string,
account: Signer | string | number,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
storage?: { state?: any; storage?: Storage; adapter?: any; prefix?: string },
contractsOrUDCAddress?: ContractsInfo | string,
config?: PartialRaidenConfig,
subkey?: true,
): Promise<InstanceType<R>> {
let provider: JsonRpcProvider;
if (typeof connection === 'string') {
provider = new JsonRpcProvider(connection);
} else if (connection instanceof JsonRpcProvider) {
provider = connection;
} else {
provider = new Web3Provider(connection);
}
// Patch provider's sign method (https://github.com/raiden-network/light-client/issues/223)
patchSignSend(provider);
const network = await provider.getNetwork();
// if no ContractsInfo, try to populate from defaults
let contractsInfo;
if (!contractsOrUDCAddress) {
contractsInfo = getContracts(network);
} else if (typeof contractsOrUDCAddress === 'string') {
// if an Address is provided, use it as UserDeposit contract address entrypoint and fetch
// all contracts from there
assert(Address.is(contractsOrUDCAddress), [
ErrorCodes.DTA_INVALID_ADDRESS,
{ contractsOrUserDepositAddress: contractsOrUDCAddress },
]);
contractsInfo = await fetchContractsInfo(provider, contractsOrUDCAddress);
} else {
contractsInfo = contractsOrUDCAddress;
}
const { signer, address, main } = await getSigner(account, provider, subkey);
// Build initial state or parse from database
const { state, db } = await getState(
{ network, contractsInfo, address, log: logging.getLogger(`raiden:${address}`) },
storage,
);
assert(address === state.address, [
ErrorCodes.RDN_STATE_ADDRESS_MISMATCH,
{
account: address,
state: state.address,
},
]);
assert(
network.chainId === state.chainId &&
contractsInfo.TokenNetworkRegistry.address === state.registry,
[
ErrorCodes.RDN_STATE_NETWORK_MISMATCH,
{
network: network.chainId,
contracts: contractsInfo.TokenNetworkRegistry.address,
stateNetwork: state.chainId,
stateRegistry: state.registry,
},
],
);
return new this(
provider,
network,
signer,
contractsInfo,
{ db, state, config },
main,
) as InstanceType<R>;
}
/**
* Starts redux/observables by subscribing to all epics and emitting initial state and action
*
* No event should be emitted before start is called
*/
public start(): void {
assert(this.epicMiddleware, ErrorCodes.RDN_ALREADY_STARTED, this.log.info);
this.log.info('Starting Raiden Light-Client', {
prevBlockNumber: this.state.blockNumber,
address: this.address,
TokenNetworkRegistry: this.deps.contractsInfo.TokenNetworkRegistry.address,
network: { name: this.deps.network.name, chainId: this.deps.network.chainId },
'raiden-ts': Raiden.version,
'raiden-contracts': Raiden.contractVersion,
config: this.config,
});
// Set `epicMiddleware` to `null`, this indicates the instance is not running.
const observerComplete = {
complete: () => (this.epicMiddleware = null),
};
this.deps.latest$.subscribe(observerComplete);
this.epicMiddleware.run(raidenRootEpic);
// prevent start from being called again, turns this.started to true
this.epicMiddleware = undefined;
// dispatch a first, noop action, to next first state$ as current/initial state
this.store.dispatch(raidenConfigUpdate({}));
}
/**
* Gets the running state of the instance
*
* @returns undefined if not yet started, true if running, false if already stopped
*/
public get started(): boolean | undefined {
// !epicMiddleware -> undefined | null -> undefined ? true/started : null/stopped;
if (!this.epicMiddleware) return this.epicMiddleware === undefined;
// else -> !!epicMiddleware -> not yet started -> returns undefined
}
/**
* Triggers all epics to be unsubscribed
*/
public stop(): void {
// start still can't be called again, but turns this.started to false
// this.epicMiddleware is set to null by latest$'s complete callback
if (this.started) this.store.dispatch(raidenShutdown({ reason: ShutdownReason.STOP }));
}
/**
* Get current RaidenState object. Can be serialized safely with [[encodeRaidenState]]
*
* @returns Current Raiden state
*/
public get state(): RaidenState {
return this.store.getState();
}
/**
* Get current account address (subkey's address, if subkey is being used)
*
* @returns Instance address
*/
public get address(): Address {
return this.deps.address;
}
/**
* Get main account address (if subkey is being used, undefined otherwise)
*
* @returns Main account address
*/
public get mainAddress(): Address | undefined {
return this.deps.main?.address;
}
/**
* Get current network from provider
*
* @returns Network object containing blockchain's name & chainId
*/
public get network(): Network {
return this.deps.network;
}
/**
* Returns a promise to current block number, as seen in provider and state
*
* @returns Promise to current block number
*/
public async getBlockNumber(): Promise<number> {
return this.deps.provider.blockNumber || (await this.deps.provider.getBlockNumber());
}
/**
* Returns the currently used SDK version.
*
* @returns SDK version
*/
static get version(): string {
return versions.sdk;
}
/**
* Returns the version of the used Smart Contracts.
*
* @returns Smart Contract version
*/
static get contractVersion(): string {
return versions.contracts;
}
/**
* Returns the Smart Contracts addresses and deployment blocks
*
* @returns Smart Contracts info
*/
get contractsInfo(): ContractsInfo {
return this.deps.contractsInfo;
}
/**
* Update Raiden Config with a partial (shallow) object
*
* @param config - Partial object containing keys and values to update in config
*/
public updateConfig(config: PartialRaidenConfig) {
this.store.dispatch(raidenConfigUpdate(decode(PartialRaidenConfig, config)));
}
/**
* Dumps database content for backup
*
* @returns JSON object or array containing database content
*/
public async dumpDatabase() {
// only wait for db to be closed if it was started
if (this.started !== undefined) await this.deps.db.busy$.toPromise();
return dumpDatabaseToArray(this.deps.db);
}
/**
* Get ETH balance for given address or self
*
* @param address - Optional target address. If omitted, gets own balance
* @returns BigNumber of ETH balance
*/
public getBalance(address?: string): Promise<BigNumber> {
address = address ?? chooseOnchainAccount(this.deps, this.config.subkey).address;
assert(Address.is(address), [ErrorCodes.DTA_INVALID_ADDRESS, { address }], this.log.info);
return this.deps.provider.getBalance(address);
}
/**
* Get token balance and token decimals for given address or self
*
* @param token - Token address to fetch balance. Must be one of the monitored tokens.
* @param address - Optional target address. If omitted, gets own balance
* @returns BigNumber containing address's token balance
*/
public async getTokenBalance(token: string, address?: string): Promise<BigNumber> {
address = address ?? chooseOnchainAccount(this.deps, this.config.subkey).address;
assert(Address.is(address), [ErrorCodes.DTA_INVALID_ADDRESS, { address }], this.log.info);
assert(Address.is(token), [ErrorCodes.DTA_INVALID_ADDRESS, { token }], this.log.info);
const tokenContract = this.deps.getTokenContract(token);
return tokenContract.functions.balanceOf(address);
}
/**
* Returns a list of all token addresses registered as token networks in registry
*
* @returns Promise to list of token addresses
*/
public async getTokenList(): Promise<Address[]> {
return this.deps.provider
.getLogs({
...this.deps.registryContract.filters.TokenNetworkCreated(null, null),
fromBlock: this.deps.contractsInfo.TokenNetworkRegistry.block_number,
toBlock: 'latest',
})
.then((logs) =>
logs
.map((log) => this.deps.registryContract.interface.parseLog(log))
.filter((parsed) => !!parsed.values?.token_address)
.map((parsed) => parsed.values.token_address as Address),
);
}
/**
* Scans initially and start monitoring a token for channels with us, returning its Tokennetwork
* address
*
* Throws an exception if token isn't registered in current registry
*
* @param token - token address to monitor, must be registered in current token network registry
* @returns Address of TokenNetwork contract
*/
public async monitorToken(token: string): Promise<Address> {
assert(Address.is(token), [ErrorCodes.DTA_INVALID_ADDRESS, { token }], this.log.info);
let tokenNetwork = this.state.tokens[token];
if (tokenNetwork) return tokenNetwork;
tokenNetwork = (await this.deps.registryContract.token_to_token_networks(token)) as Address;
assert(
tokenNetwork && tokenNetwork !== AddressZero,
ErrorCodes.RDN_UNKNOWN_TOKEN_NETWORK,
this.log.info,
);
this.store.dispatch(
tokenMonitored({
token,
tokenNetwork,
fromBlock: this.deps.contractsInfo.TokenNetworkRegistry.block_number,
}),
);
return tokenNetwork;
}
/**
* Open a channel on the tokenNetwork for given token address with partner
*
* If token isn't yet monitored, starts monitoring it
*
* @param token - Token address on currently configured token network registry
* @param partner - Partner address
* @param options - (optional) option parameter
* @param options.settleTimeout - Custom, one-time settle timeout
* @param options.subkey - Whether to use the subkey for on-chain tx or main account (default)
* @param options.deposit - Deposit to perform in parallel with channel opening
* @param onChange - Optional callback for status change notification
* @returns txHash of channelOpen call, iff it succeeded
*/
public async openChannel(
token: string,
partner: string,
options: { settleTimeout?: number; subkey?: boolean; deposit?: BigNumberish } = {},
onChange?: OnChange<EventTypes, { txHash: string }>,
): Promise<Hash> {
assert(Address.is(token), [ErrorCodes.DTA_INVALID_ADDRESS, { token }], this.log.info);
assert(Address.is(partner), [ErrorCodes.DTA_INVALID_ADDRESS, { partner }], this.log.info);
const tokenNetwork = await this.monitorToken(token);
assert(!options.subkey || this.deps.main, ErrorCodes.RDN_SUBKEY_NOT_SET, this.log.info);
// Note that we use the advantage of the UInt decoding here, but immediately
// convert it to a plain number again.
const settleTimeout = !options.settleTimeout
? undefined
: decode(
UInt(4),
options.settleTimeout,
ErrorCodes.DTA_INVALID_TIMEOUT,
this.log.info,
).toNumber();
const deposit = !options.deposit
? undefined
: decode(UInt(32), options.deposit, ErrorCodes.DTA_INVALID_DEPOSIT, this.log.info);
const meta = { tokenNetwork, partner };
// wait for confirmation
const openPromise = asyncActionToPromise(channelOpen, meta, this.action$, true).then(
({ txHash }) => txHash, // pluck txHash
);
let depositPromise;
if (deposit?.gt(0)) {
depositPromise = asyncActionToPromise(channelDeposit, meta, this.action$, true).then(
({ txHash }) => txHash, // pluck txHash
);
}
this.store.dispatch(channelOpen.request({ ...options, settleTimeout, deposit }, meta));
const openTxHash = await openPromise;
onChange?.({ type: EventTypes.OPENED, payload: { txHash: openTxHash } });
await this.state$
.pipe(
pluckDistinct('channels', channelKey({ tokenNetwork, partner }), 'state'),
first((state) => state === ChannelState.open),
)
.toPromise();
onChange?.({ type: EventTypes.CONFIRMED, payload: { txHash: openTxHash } });
if (depositPromise) {
const depositTx = await depositPromise;
onChange?.({ type: EventTypes.DEPOSITED, payload: { txHash: depositTx } });
}
return openTxHash;
}
/**
* Deposit tokens on channel between us and partner on tokenNetwork for token
*
* @param token - Token address on currently configured token network registry
* @param partner - Partner address
* @param amount - Number of tokens to deposit on channel
* @param options - tx options
* @param options.subkey - By default, if using subkey, main account is used to send transactions
* (and is also the account used as source of the deposit tokens).
* Set this to true if one wants to force sending the transaction with the subkey, and using
* tokens held in the subkey.
* @returns txHash of setTotalDeposit call, iff it succeeded
*/
public async depositChannel(
token: string,
partner: string,
amount: BigNumberish,
{ subkey }: { subkey?: boolean } = {},
): Promise<Hash> {
assert(Address.is(token), [ErrorCodes.DTA_INVALID_ADDRESS, { token }], this.log.info);
assert(Address.is(partner), [ErrorCodes.DTA_INVALID_ADDRESS, { partner }], this.log.info);
const state = this.state;
const tokenNetwork = state.tokens[token];
assert(tokenNetwork, ErrorCodes.RDN_UNKNOWN_TOKEN_NETWORK, this.log.info);
assert(!subkey || this.deps.main, ErrorCodes.RDN_SUBKEY_NOT_SET, this.log.info);
const deposit = decode(UInt(32), amount, ErrorCodes.DTA_INVALID_DEPOSIT, this.log.info);
const meta = { tokenNetwork, partner };
const promise = asyncActionToPromise(channelDeposit, meta, this.action$, true).then(
({ txHash }) => txHash,
);
this.store.dispatch(channelDeposit.request({ deposit, subkey }, meta));
return promise;
}
/**
* Close channel between us and partner on tokenNetwork for token
* This method will fail if called on a channel not in 'opened' or 'closing' state.
* When calling this method on an 'opened' channel, its state becomes 'closing', and from there
* on, no payments can be performed on the channel. If for any reason the closeChannel
* transaction fails, channel's state stays as 'closing', and this method can be called again
* to retry sending 'closeChannel' transaction. After it's successful, channel becomes 'closed',
* and can be settled after 'settleTimeout' blocks (when it then becomes 'settleable').
*
* @param token - Token address on currently configured token network registry
* @param partner - Partner address
* @param options - tx options
* @param options.subkey - By default, if using subkey, main account is used to send transactions
* Set this to true if one wants to force sending the transaction with the subkey
* @returns txHash of closeChannel call, iff it succeeded
*/
public async closeChannel(
token: string,
partner: string,
{ subkey }: { subkey?: boolean } = {},
): Promise<Hash> {
assert(Address.is(token), [ErrorCodes.DTA_INVALID_ADDRESS, { token }], this.log.info);
assert(Address.is(partner), [ErrorCodes.DTA_INVALID_ADDRESS, { partner }], this.log.info);
const state = this.state;
const tokenNetwork = state.tokens[token];
assert(tokenNetwork, ErrorCodes.RDN_UNKNOWN_TOKEN_NETWORK, this.log.info);
assert(!subkey || this.deps.main, ErrorCodes.RDN_SUBKEY_NOT_SET, this.log.info);
const meta = { tokenNetwork, partner };
const promise = asyncActionToPromise(channelClose, meta, this.action$, true).then(
({ txHash }) => txHash,
);
this.store.dispatch(channelClose.request(subkey ? { subkey } : undefined, meta));
return promise;
}
/**
* Settle channel between us and partner on tokenNetwork for token
* This method will fail if called on a channel not in 'settleable' or 'settling' state.
* Channel becomes 'settleable' settleTimeout blocks after closed (detected automatically
* while Raiden Light Client is running or later on restart). When calling it, channel state
* becomes 'settling'. If for any reason transaction fails, it'll stay on this state, and this
* method can be called again to re-send a settleChannel transaction.
*
* @param token - Token address on currently configured token network registry
* @param partner - Partner address
* @param options - tx options
* @param options.subkey - By default, if using subkey, main account is used to send transactions
* Set this to true if one wants to force sending the transaction with the subkey
* @returns txHash of settleChannel call, iff it succeeded
*/
public async settleChannel(
token: string,
partner: string,
{ subkey }: { subkey?: boolean } = {},
): Promise<Hash> {
assert(Address.is(token), [ErrorCodes.DTA_INVALID_ADDRESS, { token }], this.log.info);
assert(Address.is(partner), [ErrorCodes.DTA_INVALID_ADDRESS, { partner }], this.log.info);
const state = this.state;
const tokenNetwork = state.tokens[token];
assert(tokenNetwork, ErrorCodes.RDN_UNKNOWN_TOKEN_NETWORK, this.log.info);
assert(!subkey || this.deps.main, ErrorCodes.RDN_SUBKEY_NOT_SET, this.log.info);
// wait for the corresponding success or error action
const meta = { tokenNetwork, partner };
const promise = asyncActionToPromise(channelSettle, meta, this.action$, true).then(
({ txHash }) => txHash,
);
this.store.dispatch(channelSettle.request(subkey ? { subkey } : undefined, meta));
return promise;
}
/**
* Returns object describing address's users availability on transport
* After calling this method, any further presence update to valid transport peers of this
* address will trigger a corresponding MatrixPresenceUpdateAction on events$
*
* @param address - checksummed address to be monitored
* @returns Promise to object describing availability and last event timestamp
*/
public async getAvailability(
address: string,
): Promise<{ userId: string; available: boolean; ts: number }> {
assert(Address.is(address), [ErrorCodes.DTA_INVALID_ADDRESS, { address }], this.log.info);
const meta = { address };
const promise = asyncActionToPromise(matrixPresence, meta, this.action$);
this.store.dispatch(matrixPresence.request(undefined, meta));
return promise;
}
/**
* Send a Locked Transfer!
* This will reject if LockedTransfer signature prompt is canceled/signature fails, or be
* resolved to the transfer unique identifier (secrethash) otherwise, and transfer status can be
* queried with this id on this.transfers$ observable, which will just have emitted the 'pending'
* transfer. Any following transfer state change will be notified through this observable.
*
* @param token - Token address on currently configured token network registry
* @param target - Target address
* @param value - Amount to try to transfer
* @param options - Optional parameters for transfer:
* @param options.paymentId - payment identifier, a random one will be generated if missing</li>
* @param options.secret - Secret to register, a random one will be generated if missing</li>
* @param options.secrethash - Must match secret, if both provided, or else, secret must be
* informed to target by other means, and reveal can't be performed</li>
* @param options.paths - Used to specify possible routes & fees instead of querying PFS.</li>
* @param options.pfs - Use this PFS instead of configured or automatically choosen ones.
* Is ignored if paths were already provided. If neither are set and config.pfs is not
* disabled (null), use it if set or if undefined (auto mode), fetches the best
* PFS from ServiceRegistry and automatically fetch routes from it.</li>
* @param options.lockTimeout - Specify a lock timeout for transfer; default is 2 * revealTimeout
* @returns A promise to transfer's unique key (id) when it's accepted
*/
public async transfer(
token: string,
target: string,
value: BigNumberish,
options: {
paymentId?: BigNumberish;
secret?: string;
secrethash?: string;
paths?: RaidenPaths;
pfs?: RaidenPFS;
lockTimeout?: number;
} = {},
): Promise<string> {
assert(Address.is(token), [ErrorCodes.DTA_INVALID_ADDRESS, { token }], this.log.info);
assert(Address.is(target), [ErrorCodes.DTA_INVALID_ADDRESS, { target }], this.log.info);
const tokenNetwork = this.state.tokens[token];
assert(tokenNetwork, ErrorCodes.RDN_UNKNOWN_TOKEN_NETWORK, this.log.info);
const decodedValue = decode(UInt(32), value, ErrorCodes.DTA_INVALID_AMOUNT, this.log.info);
const paymentId =
options.paymentId !== undefined
? decode(UInt(8), options.paymentId, ErrorCodes.DTA_INVALID_PAYMENT_ID, this.log.info)
: makePaymentId();
const paths = !options.paths
? undefined
: decode(Paths, options.paths, ErrorCodes.DTA_INVALID_PATH, this.log.info);
const pfs = !options.pfs
? undefined
: decode(PFS, options.pfs, ErrorCodes.DTA_INVALID_PFS, this.log.info);
// if undefined, default expiration is calculated at locked's [[makeAndSignTransfer$]]
const expiration = !options.lockTimeout
? undefined
: this.state.blockNumber + options.lockTimeout;
assert(
options.secret === undefined || Secret.is(options.secret),
ErrorCodes.RDN_INVALID_SECRET,
this.log.info,
);
assert(
options.secrethash === undefined || Hash.is(options.secrethash),
ErrorCodes.RDN_INVALID_SECRETHASH,
this.log.info,
);
// use provided secret or create one if no secrethash was provided
const secret = options.secret
? options.secret
: !options.secrethash
? makeSecret()
: undefined;
const secrethash = options.secrethash || getSecrethash(secret!);
assert(
!secret || getSecrethash(secret) === secrethash,
ErrorCodes.RDN_SECRET_SECRETHASH_MISMATCH,
this.log.info,
);
const pathFindMeta = { tokenNetwork, target, value: decodedValue };
return merge(
// wait for pathFind response
this.action$.pipe(
first(isResponseOf(pathFind, pathFindMeta)),
map((action) => {
if (pathFind.failure.is(action)) throw action.payload;
return action.payload.paths;
}),
),
// request pathFind; even if paths were provided, send it again for validation
// this is done at 'merge' subscription time (i.e. when above action filter is subscribed)
defer(() => {
this.store.dispatch(pathFind.request({ paths, pfs }, pathFindMeta));
return EMPTY;
}),
)
.pipe(
mergeMap((paths) =>
merge(
// wait for transfer response
this.action$.pipe(
filter(isActionOf([transferSigned, transfer.failure])),
first(
(action) =>
action.meta.direction === Direction.SENT &&
action.meta.secrethash === secrethash,
),
map((action) => {
if (transfer.failure.is(action)) throw action.payload;
return transferKey(action.meta);
}),
),
// request transfer with returned/validated paths at 'merge' subscription time
defer(() => {
this.store.dispatch(
transfer.request(
{
tokenNetwork,
target,
value: decodedValue,
paths,
paymentId,
secret,
expiration,
},
{ secrethash, direction: Direction.SENT },
),
);
return EMPTY;
}),
),
),
)
.toPromise();
}
/**
* Waits for the transfer identified by a secrethash to fail or complete
* The returned promise will resolve with the final transfer state, or reject if anything fails
*
* @param transferKey - Transfer identifier as returned by [[transfer]]
* @returns Promise to final RaidenTransfer
*/
public async waitTransfer(transferKey: string): Promise<RaidenTransfer> {
const { direction, secrethash } = transferKeyToMeta(transferKey);
let transferState = this.state.transfers[transferKey];
if (!transferState)
try {
transferState = decode(TransferState, await this.deps.db.get(transferKey));
} catch (e) {}
assert(transferState, ErrorCodes.RDN_UNKNOWN_TRANSFER, this.log.info);
const raidenTransf = raidenTransfer(transferState);
// already completed/past transfer
if (raidenTransf.completed) {
if (raidenTransf.success) return raidenTransf;
else
throw new RaidenError(ErrorCodes.XFER_ALREADY_COMPLETED, { status: raidenTransf.status });
}
// throws/rejects if a failure occurs
await asyncActionToPromise(transfer, { secrethash, direction }, this.action$);
const finalState = await this.state$
.pipe(
pluck('transfers', transferKey),
first((transferState) => !!transferState.unlockProcessed),
)
.toPromise();
this.log.info('Transfer successful', {
key: transferKey,
partner: finalState.partner,
initiator: finalState.transfer.initiator,
target: finalState.transfer.target,
fee: finalState.fee.toString(),