@audius/sdk 0.0.0 → 0.0.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,2431 @@
1
+ import * as axios from 'axios';
2
+ import { AxiosResponse, AxiosRequestConfig, Method, AxiosError } from 'axios';
3
+ import { PathArg } from 'proper-url-join';
4
+ import * as BN from 'bn.js';
5
+ import BN__default from 'bn.js';
6
+ import * as Web3 from 'web3';
7
+ import Web3__default from 'web3';
8
+ import { AbiItem } from 'web3-utils';
9
+ import * as web3_core from 'web3-core';
10
+ import { Log, TransactionReceipt, HttpProvider, EventLog } from 'web3-core';
11
+ import Wallet from 'ethereumjs-wallet';
12
+ import abiDecoder from 'abi-decoder';
13
+ import { Hedgehog } from '@audius/hedgehog';
14
+ import { EIP712TypedData } from 'eth-sig-util';
15
+ import * as web3_eth_contract from 'web3-eth-contract';
16
+ import { Contract } from 'web3-eth-contract';
17
+ import { UserImporterOptions, ImportCandidate } from 'ipfs-unixfs-importer';
18
+ import * as ipfs_unixfs_importer_types_src_types from 'ipfs-unixfs-importer/types/src/types';
19
+ import FormData from 'form-data';
20
+
21
+ declare type Content = ReadableStream | Buffer | string;
22
+ interface ImageHasher {
23
+ options: UserImporterOptions;
24
+ content: ImportCandidate;
25
+ }
26
+ interface NonImageHasher {
27
+ options: UserImporterOptions;
28
+ content: Uint8Array;
29
+ }
30
+ interface HashedImage {
31
+ path: string | undefined;
32
+ cid: string;
33
+ size: number;
34
+ }
35
+
36
+ type ContractABI = {
37
+ abi: AbiItem[]
38
+ contractName: string
39
+ }
40
+
41
+ declare class Utils {
42
+ static importDataContractABI(pathStr: string): ContractABI;
43
+ static importEthContractABI(pathStr: string): ContractABI;
44
+ static utf8ToHex(utf8Str: string): string;
45
+ static padRight(hexStr: string, size: number): string;
46
+ static hexToUtf8(hexStr: string): string;
47
+ static keccak256(utf8Str: string): string;
48
+ static isBN(number: number | string): boolean;
49
+ static toBN(number: number, base?: number): BN;
50
+ static BN(): typeof BN;
51
+ static checkStrLen(str: string, maxLen: number, minLen?: number): void;
52
+ static wait(milliseconds: number): Promise<void>;
53
+ static isFQDN(url: string): boolean;
54
+ static isHttps(url: string): boolean;
55
+ static isHealthy(url: string): Promise<any>;
56
+ static formatOptionalMultihash(multihash: string): string;
57
+ static decodeMultihash(multihash: string): {
58
+ digest: string;
59
+ hashFn: number;
60
+ size: number;
61
+ };
62
+ /**
63
+ * Given a digest value (written on chain, obtained through AudiusABIDecoder.decodeMethod),
64
+ * convert back to a IFPS CIDv0
65
+ * @param multihashDigest digest value from decodeMultihash
66
+ * @returns String CID value
67
+ */
68
+ static encodeMultihash(multihashDigest: string): string;
69
+ static parseDataFromResponse(response: AxiosResponse): any;
70
+ static configureWeb3(web3Provider: string, chainNetworkId: string, requiresAccount?: boolean): Promise<false | Web3.default>;
71
+ static get zeroAddress(): string;
72
+ static isZeroAddress(address: string): boolean;
73
+ static makeUuid(): string;
74
+ /**
75
+ * Decodes a string id into an int. Returns null if an invalid ID.
76
+ */
77
+ static decodeHashId(id: string): number | null;
78
+ /**
79
+ * Encodes an int to a string based hashid
80
+ */
81
+ static encodeHashId(id: number | null): string | null;
82
+ /**
83
+ * If `promise` responds before `timeoutMs`,
84
+ * this function returns its response; else rejects with `timeoutMessage`
85
+ */
86
+ static racePromiseWithTimeout(promise: Promise<void>, timeoutMs: number, timeoutMessage: string): Promise<unknown>;
87
+ static fileHasher: {
88
+ convertNanosToMillis(nanoSeconds: bigint): bigint;
89
+ initImageHasher(content: ipfs_unixfs_importer_types_src_types.ImportCandidate, options: ipfs_unixfs_importer_types_src_types.UserImporterOptions): ImageHasher;
90
+ initNonImageHasher(content: Uint8Array, options: ipfs_unixfs_importer_types_src_types.UserImporterOptions): NonImageHasher;
91
+ convertToBuffer(content: Content, logger: any): Promise<Buffer>;
92
+ hashNonImages(content: Uint8Array, options?: ipfs_unixfs_importer_types_src_types.UserImporterOptions): Promise<string>;
93
+ hashImages(content: ipfs_unixfs_importer_types_src_types.ImportCandidate, options?: ipfs_unixfs_importer_types_src_types.UserImporterOptions): Promise<HashedImage[]>;
94
+ generateNonImageCid(content: Content, logger?: any): Promise<string>;
95
+ generateImageCids(content: ipfs_unixfs_importer_types_src_types.ImportCandidate, logger?: any): Promise<HashedImage[]>;
96
+ };
97
+ }
98
+
99
+ declare global {
100
+ interface Window {
101
+ grecaptcha: {
102
+ ready: (callback: () => void) => Promise<void>;
103
+ execute: (siteKey: string, config: {
104
+ action: string;
105
+ }) => Promise<string>;
106
+ };
107
+ }
108
+ }
109
+ interface CaptchaConfig {
110
+ siteKey: string;
111
+ serviceKey: string;
112
+ }
113
+ declare class Captcha {
114
+ siteKey: string;
115
+ serviceKey: string;
116
+ constructor({ siteKey, serviceKey }: CaptchaConfig);
117
+ /**
118
+ * Intended to be called by clients. Will generate a token used to calculate recaptcha score.
119
+ * @param action name for this "action" for grouping
120
+ */
121
+ generate(action: string): Promise<string>;
122
+ /**
123
+ * Intended to be called by services. According to recaptcha v3 docs:
124
+ * A score of 1.0 is very likely a good interaction, 0.0 is very likely a bot
125
+ * @param token
126
+ * @param minScore score must be >= minScore to be ok
127
+ * @returns
128
+ * {boolean | null} ok - whether score > minScore (false if something went wrong)
129
+ * {number | null} score - the raw score [0, 1] (or null if a score was not computed)
130
+ */
131
+ verify(token: string, minScore?: number): Promise<{
132
+ score: any;
133
+ ok: boolean;
134
+ hostname: any;
135
+ }>;
136
+ }
137
+
138
+ interface ContractMethod {
139
+ arguments: string[];
140
+ estimateGas: (config: {
141
+ from: Wallet | string | undefined;
142
+ gas: number | undefined;
143
+ }) => Promise<number>;
144
+ _method: {
145
+ name: string;
146
+ inputs: Array<{
147
+ type: string;
148
+ }>;
149
+ };
150
+ encodeABI: () => string;
151
+ send: <Tx>(config: {
152
+ from: Wallet | string | undefined;
153
+ gas: number;
154
+ gasPrice?: number;
155
+ }) => Tx;
156
+ }
157
+
158
+ declare type ServiceName = string;
159
+ interface ServiceWithEndpoint {
160
+ endpoint: string;
161
+ spID?: string;
162
+ }
163
+ declare type Service = ServiceName | ServiceWithEndpoint;
164
+
165
+ declare type Maybe<T> = T | undefined;
166
+ declare type Nullable<T> = T | null;
167
+ interface Logger {
168
+ /**
169
+ * Write a 'log' level log.
170
+ */
171
+ log: (message: any, ...optionalParams: any[]) => any;
172
+ /**
173
+ * Write a 'info' level log.
174
+ */
175
+ info: (message: any, ...optionalParams: any[]) => any;
176
+ /**
177
+ * Write an 'error' level log.
178
+ */
179
+ error: (message: any, ...optionalParams: any[]) => any;
180
+ /**
181
+ * Write a 'warn' level log.
182
+ */
183
+ warn: (message: any, ...optionalParams: any[]) => any;
184
+ /**
185
+ * Write a 'debug' level log.
186
+ */
187
+ debug?: (message: any, ...optionalParams: any[]) => any;
188
+ /**
189
+ * Write a 'verbose' level log.
190
+ */
191
+ verbose?: (message: any, ...optionalParams: any[]) => any;
192
+ }
193
+
194
+ declare type GetServicesInput = (() => Promise<ServiceName[]>) | ((config: {
195
+ verbose: false;
196
+ }) => Promise<ServiceName[]>) | ((config: {
197
+ verbose: true;
198
+ }) => Promise<ServiceWithEndpoint[]>) | ((config: {
199
+ verbose: boolean;
200
+ }) => Promise<ServiceName[] | ServiceWithEndpoint[]>);
201
+ interface GetServices {
202
+ (): Promise<ServiceName[]>;
203
+ (config: {
204
+ verbose: false;
205
+ }): Promise<ServiceName[]>;
206
+ (config: {
207
+ verbose: true;
208
+ }): Promise<ServiceWithEndpoint[]>;
209
+ (config: {
210
+ verbose: boolean;
211
+ }): Promise<Service[]>;
212
+ }
213
+ interface Decision {
214
+ stage: string;
215
+ val?: unknown;
216
+ }
217
+ declare type Backup = {
218
+ block_difference: number;
219
+ version: string;
220
+ };
221
+ interface ServiceSelectionConfig {
222
+ blacklist?: Set<string> | undefined | null;
223
+ whitelist?: Set<string> | undefined | null;
224
+ getServices: GetServicesInput;
225
+ maxConcurrentRequests?: number;
226
+ requestTimeout?: Maybe<number>;
227
+ unhealthyTTL?: number;
228
+ backupsTTL?: number;
229
+ }
230
+ /**
231
+ * A class that assists with autoselecting services.
232
+ * `ServiceSelection` is intended to be overridden with further
233
+ * business logic that a particular sevice might preference.
234
+ *
235
+ * The general use case is as follows:
236
+ *
237
+ * ```
238
+ *
239
+ * const selector = new ServiceSelection({
240
+ * getServices: ethContracts.getDiscoveryProviders()
241
+ * })
242
+ *
243
+ * const service = await selector.select()
244
+ *
245
+ * ```
246
+ *
247
+ * This class operates by taking a list of services and
248
+ * round-robin makes requests at them until a suitable one is found.
249
+ *
250
+ * Two types of "bad" services are defined below:
251
+ * - Unhealthy: this service is bad and should not be used
252
+ * - Backup: this service is bad, but if we can't find anything better, maybe use it
253
+ *
254
+ * Classes that extend `ServiceSelection` can choose to implement custom logic on top
255
+ * of them and is generally how this class is intended to be used.
256
+ */
257
+ declare class ServiceSelection {
258
+ blacklist: Set<string> | undefined | null;
259
+ whitelist: Set<string> | undefined | null;
260
+ getServices: GetServices;
261
+ maxConcurrentRequests: number;
262
+ requestTimeout: number;
263
+ unhealthyTTL: number;
264
+ backupsTTL: number;
265
+ unhealthy: Set<string>;
266
+ backups: Record<string, Backup>;
267
+ totalAttempts: number;
268
+ decisionTree: Decision[];
269
+ unhealthyCleanupTimeout: NodeJS.Timeout | null;
270
+ backupCleanupTimeout: NodeJS.Timeout | null;
271
+ constructor({ blacklist, whitelist, getServices, maxConcurrentRequests, requestTimeout, // 30s
272
+ unhealthyTTL, // 1 hour
273
+ backupsTTL }: ServiceSelectionConfig);
274
+ /**
275
+ * Selects a service
276
+ * @param reset if reset is true, clear the decision tree
277
+ */
278
+ select(reset?: any): Promise<any>;
279
+ /**
280
+ * Finds all selectable services (respecting whitelist, health checks & timeouts).
281
+ * Note: this method is potentially slow.
282
+ * If you need just a single service, prefer calling `.select()`
283
+ * @param {boolean} verbose whether or not to return full services metadata
284
+ * @param {Set} whitelist a whitelist to override the set of endpoints
285
+ */
286
+ findAll({ verbose, whitelist }?: {
287
+ verbose?: boolean | undefined;
288
+ whitelist?: Set<string> | null | undefined;
289
+ }): Promise<(Service | null)[]>;
290
+ /** Triggers a clean up of unhealthy and backup services so they can be retried later */
291
+ triggerCleanup(): void;
292
+ clearUnhealthy(): void;
293
+ clearBackups(): void;
294
+ /** A short-circuit. If overriden, can be used to skip selection (which could be slow) */
295
+ shortcircuit(): null | string;
296
+ /**
297
+ * Filter out services that are in the blacklist
298
+ * @param services endpoints
299
+ */
300
+ filterFromBlacklist(services: string[]): string[];
301
+ /** Filter down services to those in the whitelist */
302
+ filterToWhitelist(services: string[]): string[];
303
+ /** Filter out known unhealthy services from the provided */
304
+ filterOutKnownUnhealthy(services: string[]): string[];
305
+ /** Given a list of services, samples maxConcurrentRequests from them */
306
+ getSelectionRound(services: string[]): string[];
307
+ /** Gets the total number of attempts we've made this instantiation */
308
+ getTotalAttempts(): number;
309
+ /** Where does the health check for this type of service live */
310
+ static getHealthCheckEndpoint(service: string): string;
311
+ /**
312
+ * What the criteria is for a healthy service
313
+ * @param response axios response
314
+ * @param {{ [key: string]: string}} urlMap health check urls mapped to their cannonical url
315
+ * e.g. https://discoveryprovider.audius.co/health_check => https://discoveryprovider.audius.co
316
+ */
317
+ isHealthy(response: AxiosResponse, _urlMap: Record<string, Service>): boolean;
318
+ /** Races requests against each other with provided timeouts and health checks */
319
+ race(services: string[]): Promise<{
320
+ best: null;
321
+ errored: (string | undefined)[];
322
+ }>;
323
+ /** Adds a service to the unhealthy set */
324
+ addUnhealthy(service: ServiceName): void;
325
+ /** Gets unhealthy set size */
326
+ getUnhealthySize(): number;
327
+ /**
328
+ * Removes from unhealthy set
329
+ * @param key service endpoint
330
+ */
331
+ removeFromUnhealthy(key: string): void;
332
+ /**
333
+ * Adds a service to the list of backups
334
+ * @param service the service to add
335
+ * @param response the services response. This can be used to weigh various
336
+ * backups against eachother
337
+ */
338
+ addBackup(service: string, response: Backup): void;
339
+ /**
340
+ * Controls how a backup is picked. Overriding methods may choose to use the backup's response.
341
+ * e.g. pick a backup that's the fewest versions behind
342
+ */
343
+ selectFromBackups(): Promise<string | undefined>;
344
+ /**
345
+ * Removes from backups
346
+ * @param key service endpoint
347
+ */
348
+ removeFromBackups(key: string): void;
349
+ /**
350
+ * Returns the size of backups
351
+ */
352
+ getBackupsSize(): number;
353
+ }
354
+
355
+ declare type TimeFrame = 'day' | 'week' | 'month' | 'year' | 'millennium';
356
+
357
+ declare type Web3Config$1 = {
358
+ useExternalWeb3: boolean;
359
+ internalWeb3Config: {
360
+ web3ProviderEndpoints: string[];
361
+ privateKey?: string;
362
+ };
363
+ externalWeb3Config?: {
364
+ web3: Web3__default;
365
+ ownerWallet: Wallet;
366
+ };
367
+ };
368
+
369
+ declare class AudiusABIDecoder {
370
+ static decodeMethod(contractName: string, encodedABI: string): abiDecoder.DecodedMethod;
371
+ static decodeLogs(_: string, logs: Log[]): abiDecoder.DecodedLog;
372
+ }
373
+
374
+ declare type Web3ManagerConfig = {
375
+ web3Config: Web3Config$1;
376
+ identityService: IdentityService;
377
+ hedgehog: Hedgehog;
378
+ isServer?: boolean;
379
+ };
380
+ /** singleton class to be instantiated and persisted with every AudiusLibs */
381
+ declare class Web3Manager {
382
+ web3Config: Web3Config$1;
383
+ isServer: boolean;
384
+ identityService: IdentityService;
385
+ hedgehog: Hedgehog;
386
+ AudiusABIDecoder: typeof AudiusABIDecoder;
387
+ web3: Web3__default | undefined;
388
+ useExternalWeb3: boolean | undefined;
389
+ ownerWallet: Wallet;
390
+ constructor({ web3Config, identityService, hedgehog, isServer }: Web3ManagerConfig);
391
+ init(): Promise<void>;
392
+ getWeb3(): Web3__default;
393
+ setWeb3(web3: Web3__default): void;
394
+ getWalletAddress(): any;
395
+ setOwnerWallet(ownerWallet: Wallet): void;
396
+ web3IsExternal(): boolean | undefined;
397
+ getOwnerWalletPrivateKey(): Buffer;
398
+ /**
399
+ * Signs provided string data (should be timestamped).
400
+ * @param data
401
+ */
402
+ sign(data: string): Promise<string | undefined>;
403
+ /**
404
+ * Given a data payload and signature, verifies that signature is valid, and returns
405
+ * Ethereum wallet address used to sign data.
406
+ * @param data information that was signed
407
+ * @param signature hex-formatted signature of data generated by web3 personalSign method
408
+ */
409
+ verifySignature(data: string, signature: string): Promise<string>;
410
+ signTypedData(signatureData: EIP712TypedData): Promise<unknown>;
411
+ sendTransaction(contractMethod: ContractMethod, contractRegistryKey?: string | null, contractAddress?: string | null, txRetries?: number, txGasLimit?: number): Promise<TransactionReceipt>;
412
+ provider(url: string, timeout: number): HttpProvider;
413
+ monkeyPatchProvider(httpProvider: HttpProvider): HttpProvider;
414
+ }
415
+
416
+ declare type Data = Record<string, unknown>;
417
+ declare type RelayTransaction = {
418
+ resp: {
419
+ txHash: string;
420
+ txParams: {
421
+ data: string;
422
+ gasLimit: string;
423
+ gasPrice: number;
424
+ nonce: string;
425
+ to: string;
426
+ value: string;
427
+ };
428
+ };
429
+ };
430
+ declare type TransactionData = {
431
+ recentBlockhash: string;
432
+ secpInstruction?: {
433
+ publicKey: string;
434
+ message: string;
435
+ signature: any;
436
+ recoveryId: number;
437
+ };
438
+ instruction: {
439
+ keys: Array<{
440
+ pubkey: string;
441
+ isSigner?: boolean;
442
+ isWritable?: boolean;
443
+ }>;
444
+ programId: string;
445
+ data: Record<string, unknown>;
446
+ };
447
+ };
448
+ declare type AttestationResult = {
449
+ status: string;
450
+ userId: string;
451
+ challengeId: string;
452
+ amount: number;
453
+ source: string;
454
+ specifier: string;
455
+ error?: string;
456
+ phase?: string;
457
+ reason?: string;
458
+ };
459
+ declare type IdentityServiceConfig = {
460
+ identityServiceEndpoint: string;
461
+ captcha?: Captcha;
462
+ };
463
+ declare class IdentityService {
464
+ identityServiceEndpoint: string;
465
+ captcha: Captcha | undefined;
466
+ web3Manager: Web3Manager | null;
467
+ constructor({ identityServiceEndpoint, captcha }: IdentityServiceConfig);
468
+ setWeb3Manager(web3Manager: Web3Manager): void;
469
+ getFn(params: {
470
+ lookupKey: string;
471
+ username: string;
472
+ }): Promise<{
473
+ iv: string;
474
+ cipherText: string;
475
+ }>;
476
+ setAuthFn(obj: Data): Promise<unknown>;
477
+ setUserFn(obj: Data & {
478
+ token?: string;
479
+ }): Promise<unknown>;
480
+ getUserEvents(walletAddress: string): Promise<unknown>;
481
+ sendRecoveryInfo(obj: Record<string, unknown>): Promise<unknown>;
482
+ /**
483
+ * Check if an email address has been previously registered.
484
+ */
485
+ checkIfEmailRegistered(email: string): Promise<{
486
+ exists: boolean;
487
+ }>;
488
+ getUserEmail(): Promise<{
489
+ email: string | undefined | null;
490
+ }>;
491
+ /**
492
+ * Associates a user with a twitter uuid.
493
+ * @param uuid from the Twitter API
494
+ * @param userId
495
+ * @param handle User handle
496
+ */
497
+ associateTwitterUser(uuid: string, userId: number, handle: string): Promise<unknown>;
498
+ /**
499
+ * Associates a user with an instagram uuid.
500
+ * @param uuid from the Instagram API
501
+ * @param userId
502
+ * @param handle
503
+ */
504
+ associateInstagramUser(uuid: string, userId: number, handle: string): Promise<unknown>;
505
+ /**
506
+ * Logs a track listen for a given user id.
507
+ * @param trackId
508
+ * @param userId
509
+ * @param listenerAddress if logging this listen on behalf of another IP address, pass through here
510
+ * @param signatureData if logging this listen via a 3p service, a signed piece of data proving authenticity
511
+ */
512
+ logTrackListen(trackId: number, userId: number, listenerAddress: string, signatureData?: {
513
+ signature: string;
514
+ timestamp: string;
515
+ }, solanaListen?: boolean): Promise<unknown>;
516
+ /**
517
+ * Return listen history tracks for a given user id.
518
+ * @param userId - User ID
519
+ * @param limit - max # of items to return
520
+ * @param offset - offset into list to return from (for pagination)
521
+ */
522
+ getListenHistoryTracks(userId: number, limit?: number, offset?: number): Promise<unknown>;
523
+ /**
524
+ * Looks up a Twitter account by handle.
525
+ * @returns twitter API response.
526
+ */
527
+ lookupTwitterHandle(handle: string): Promise<unknown>;
528
+ /**
529
+ * Gets tracks trending on Audius.
530
+ * @param timeFrame one of day, week, month, or year
531
+ * @param idsArray track ids
532
+ * @param limit
533
+ * @param offset
534
+ */
535
+ getTrendingTracks(timeFrame?: string | null, idsArray?: number[] | null, limit?: number | null, offset?: number | null): Promise<{
536
+ listenCounts: Array<{
537
+ trackId: number;
538
+ listens: number;
539
+ }>;
540
+ }>;
541
+ /**
542
+ * Gets listens for tracks bucketted by timeFrame.
543
+ * @param timeFrame one of day, week, month, or year
544
+ * @param idsArray track ids
545
+ * @param startTime parseable by Date.parse
546
+ * @param endTime parseable by Date.parse
547
+ * @param limit
548
+ * @param offset
549
+ */
550
+ getTrackListens(timeFrame?: TimeFrame | null, idsArray?: number[] | null, startTime?: string | null, endTime?: string | null, limit?: number | null, offset?: number | null): Promise<{
551
+ bucket: Array<{
552
+ trackId: number;
553
+ date: string;
554
+ listens: number;
555
+ }>;
556
+ }>;
557
+ createUserRecord(email: string, walletAddress: string): Promise<unknown>;
558
+ relay(contractRegistryKey: string | null | undefined, contractAddress: string | null | undefined, senderAddress: string, encodedABI: string, gasLimit: number): Promise<{
559
+ receipt: TransactionReceipt;
560
+ }>;
561
+ ethRelay(contractAddress: string, senderAddress: Wallet | string, encodedABI: string, gasLimit: string): Promise<RelayTransaction>;
562
+ wormholeRelay({ senderAddress, permit, transferTokens }: {
563
+ senderAddress: string;
564
+ permit: string;
565
+ transferTokens: string[];
566
+ }): Promise<unknown>;
567
+ /**
568
+ * Gets the correct wallet that will relay a txn for `senderAddress`
569
+ * @param senderAddress wallet
570
+ */
571
+ getEthRelayer(senderAddress: string): Promise<unknown>;
572
+ getRandomFeePayer(): Promise<unknown>;
573
+ solanaRelay(transactionData: TransactionData): Promise<unknown>;
574
+ solanaRelayRaw(transactionData: TransactionData): Promise<unknown>;
575
+ getMinimumDelegationAmount(wallet: string): Promise<unknown>;
576
+ updateMinimumDelegationAmount(wallet: string, minimumDelegationAmount: number, signedData: AxiosRequestConfig['headers']): Promise<unknown>;
577
+ /**
578
+ * Sends an attestation result to identity.
579
+ *
580
+ */
581
+ sendAttestationResult(data: AttestationResult): Promise<unknown>;
582
+ _makeRequest<T = unknown>(axiosRequestObj: AxiosRequestConfig): Promise<T>;
583
+ _signData(): Promise<{
584
+ "Encoded-Data-Message": string;
585
+ "Encoded-Data-Signature": string | undefined;
586
+ } | {
587
+ "Encoded-Data-Message"?: undefined;
588
+ "Encoded-Data-Signature"?: undefined;
589
+ }>;
590
+ }
591
+
592
+ declare type EthWeb3Config = {
593
+ ownerWallet: Wallet | string;
594
+ providers: string[];
595
+ };
596
+ declare type EthWeb3ManagerConfig = {
597
+ web3Config: EthWeb3Config;
598
+ identityService: IdentityService;
599
+ hedgehog?: Hedgehog;
600
+ };
601
+ /** Singleton state-manager for Audius Eth Contracts */
602
+ declare class EthWeb3Manager {
603
+ web3Config: EthWeb3Config;
604
+ web3: Web3__default;
605
+ identityService: IdentityService;
606
+ hedgehog?: Hedgehog;
607
+ ownerWallet: Maybe<Wallet | string>;
608
+ constructor({ web3Config, identityService, hedgehog }: EthWeb3ManagerConfig);
609
+ getWeb3(): Web3__default;
610
+ getWalletAddress(): any;
611
+ /**
612
+ * Signs provided string data (should be timestamped).
613
+ */
614
+ sign(data: string): Promise<string>;
615
+ sendTransaction(contractMethod: ContractMethod, contractAddress?: string | null, privateKey?: string | null, txRetries?: number, txGasLimit?: number | null): Promise<TransactionReceipt>;
616
+ /**
617
+ * Relays an eth transaction via the identity service with retries
618
+ * The relay pays for the transaction fee on behalf of the user
619
+ * The gas Limit is estimated if not provided
620
+ */
621
+ relayTransaction(contractMethod: ContractMethod, contractAddress: string, ownerWallet: Wallet | string, relayerWallet?: Wallet | string, txRetries?: number, txGasLimit?: number | null): Promise<Maybe<RelayTransaction['resp']>>;
622
+ getRelayMethodParams(contractAddress: string, contractMethod: ContractMethod, relayerWallet: Wallet): Promise<{
623
+ contractAddress: string;
624
+ encodedABI: string;
625
+ gasLimit: number;
626
+ }>;
627
+ }
628
+
629
+ declare class AudiusTokenClient {
630
+ ethWeb3Manager: EthWeb3Manager;
631
+ contractABI: AbiItem[];
632
+ contractAddress: string;
633
+ web3: Web3__default;
634
+ AudiusTokenContract: Contract;
635
+ bustCacheNonce: number;
636
+ constructor(ethWeb3Manager: EthWeb3Manager, contractABI: AbiItem[], contractAddress: string);
637
+ bustCache(): Promise<void>;
638
+ balanceOf(account: string): Promise<BN__default>;
639
+ name(): Promise<any>;
640
+ nonces(wallet: string): Promise<number>;
641
+ transfer(recipient: string, amount: BN__default): Promise<{
642
+ txReceipt: web3_core.TransactionReceipt;
643
+ }>;
644
+ transferFrom(owner: string, recipient: string, relayer: string, amount: BN__default): Promise<{
645
+ txReceipt: Maybe<{
646
+ txHash: string;
647
+ txParams: {
648
+ data: string;
649
+ gasLimit: string;
650
+ gasPrice: number;
651
+ nonce: string;
652
+ to: string;
653
+ value: string;
654
+ };
655
+ }>;
656
+ }>;
657
+ permit(owner: string, // address
658
+ spender: string, // address
659
+ value: BN__default, // uint
660
+ deadline: number, // uint
661
+ v: number, // uint8
662
+ r: Uint8Array | Buffer, // bytes32
663
+ s: Uint8Array | Buffer): Promise<Maybe<{
664
+ txHash: string;
665
+ txParams: {
666
+ data: string;
667
+ gasLimit: string;
668
+ gasPrice: number;
669
+ nonce: string;
670
+ to: string;
671
+ value: string;
672
+ };
673
+ }>>;
674
+ approve(spender: string, value: BN__default, privateKey?: null): Promise<{
675
+ txReceipt: web3_core.TransactionReceipt;
676
+ }>;
677
+ approveProxyTokens(owner: string, spender: string, value: BN__default, relayer: string): Promise<{
678
+ txReceipt: Maybe<{
679
+ txHash: string;
680
+ txParams: {
681
+ data: string;
682
+ gasLimit: string;
683
+ gasPrice: number;
684
+ nonce: string;
685
+ to: string;
686
+ value: string;
687
+ };
688
+ }>;
689
+ }>;
690
+ }
691
+
692
+ declare class RegistryClient {
693
+ web3Manager: EthWeb3Manager;
694
+ contractABI: AbiItem[];
695
+ contractAddress: string;
696
+ web3: Web3__default;
697
+ Registry: Contract;
698
+ constructor(web3Manager: EthWeb3Manager, contractABI: AbiItem[], contractAddress: string);
699
+ getContract(contractRegistryKey: string): Promise<string>;
700
+ }
701
+
702
+ /**
703
+ * This class provides the logic to select a healthy gateway
704
+ */
705
+ declare class ProviderSelection extends ServiceSelection {
706
+ services: string[];
707
+ constructor(services?: string[]);
708
+ /**
709
+ * Filters out previously tried providers, and then initializes the client
710
+ * (ContractClient, RegistryClient) with a healthy POA provider.
711
+ *
712
+ * @param client object used for making transaction calls
713
+ */
714
+ select(client: {
715
+ web3Manager: Web3Manager | EthWeb3Manager;
716
+ }): Promise<void>;
717
+ getServicesSize(): number;
718
+ }
719
+
720
+ declare type GetRegistryAddress = (key: string) => Promise<string>;
721
+ declare class ContractClient {
722
+ web3Manager: Web3Manager | EthWeb3Manager;
723
+ contractABI: ContractABI['abi'];
724
+ contractRegistryKey: string;
725
+ getRegistryAddress: GetRegistryAddress;
726
+ _contractAddress: Nullable<string>;
727
+ _contract: Nullable<Contract>;
728
+ _isInitialized: boolean;
729
+ _isInitializing: boolean;
730
+ _initAttempts: number;
731
+ providerSelector: Nullable<ProviderSelection>;
732
+ logger: Logger;
733
+ constructor(web3Manager: Web3Manager | EthWeb3Manager, contractABI: ContractABI['abi'], contractRegistryKey: string, getRegistryAddress: GetRegistryAddress, logger?: Logger, contractAddress?: Nullable<string>);
734
+ /** Inits the contract if necessary */
735
+ init(): Promise<void>;
736
+ retryInit(selectNewEndpoint?: boolean): Promise<void>;
737
+ /**
738
+ * Adds current provider into unhealthy set and selects the next healthy provider
739
+ */
740
+ selectNewEndpoint(): Promise<void>;
741
+ /** Gets the contract address and ensures that the contract has initted. */
742
+ getAddress(): Promise<string>;
743
+ /**
744
+ * Gets a contract method and ensures that the contract has initted
745
+ * The contract can then be invoked with .call() or be passed to a sendTransaction.
746
+ * @param methodName the name of the contract method
747
+ */
748
+ getMethod(methodName: string, ...args: any[]): Promise<any>;
749
+ getEthNetId(): Promise<number>;
750
+ getContract(): Promise<Contract>;
751
+ }
752
+
753
+ declare class StakingProxyClient extends ContractClient {
754
+ audiusTokenClient: AudiusTokenClient;
755
+ toBN: (value: string | number) => BN__default;
756
+ constructor(ethWeb3Manager: EthWeb3Manager, contractABI: ContractABI['abi'], contractRegistryKey: string, getRegistryAddress: GetRegistryAddress, audiusTokenClient: AudiusTokenClient, logger?: Logger);
757
+ token(): Promise<any>;
758
+ totalStaked(): Promise<BN__default>;
759
+ supportsHistory(): Promise<any>;
760
+ totalStakedFor(account: string): Promise<BN__default>;
761
+ totalStakedForAt(account: string, blockNumber: string): Promise<BN__default>;
762
+ totalStakedAt(blockNumber: number): Promise<BN__default>;
763
+ isStaker(account: string): Promise<any>;
764
+ getDelegateManagerAddress(): Promise<any>;
765
+ getClaimsManagerAddress(): Promise<any>;
766
+ getServiceProviderFactoryAddress(): Promise<any>;
767
+ getGovernanceAddress(): Promise<any>;
768
+ getLastClaimedBlockForUser(): Promise<any>;
769
+ }
770
+
771
+ declare type ProposalTxn = {
772
+ proposalId: string;
773
+ proposer: string;
774
+ submissionBlockNumber: string;
775
+ targetContractRegistryKey: string;
776
+ targetContractAddress: string;
777
+ callValue: string;
778
+ functionSignature: string;
779
+ callData: string;
780
+ outcome: string;
781
+ numVotes: string;
782
+ voteMagnitudeYes: string;
783
+ voteMagnitudeNo: string;
784
+ };
785
+ declare class GovernanceClient extends ContractClient {
786
+ audiusTokenClient: AudiusTokenClient;
787
+ stakingProxyClient: StakingProxyClient;
788
+ isDebug: boolean;
789
+ constructor(ethWeb3Manager: EthWeb3Manager, contractABI: ContractABI['abi'], contractRegistryKey: string, getRegistryAddress: GetRegistryAddress, audiusTokenClient: AudiusTokenClient, stakingProxyClient: StakingProxyClient, logger?: Logger, isDebug?: boolean);
790
+ /**
791
+ * Gets the function signature and call data for a contract method.
792
+ * The signature and call data are passed to other contracts (like governance)
793
+ * as arguments.
794
+ * @param methodName
795
+ * @param contractMethod
796
+ */
797
+ getSignatureAndCallData(methodName: string, contractMethod: ContractMethod): {
798
+ signature: string;
799
+ callData: string;
800
+ };
801
+ guardianExecuteTransaction(contractRegistryKey: string, functionSignature: string, callData: string): Promise<ContractMethod>;
802
+ getVotingPeriod(): Promise<number>;
803
+ setVotingPeriod(period: string): Promise<web3_core.TransactionReceipt>;
804
+ getVotingQuorumPercent(): Promise<number>;
805
+ getExecutionDelay(): Promise<number>;
806
+ setExecutionDelay(delay: number): Promise<web3_core.TransactionReceipt>;
807
+ getProposalById(id: number): Promise<{
808
+ proposalId: number;
809
+ proposer: string;
810
+ submissionBlockNumber: number;
811
+ targetContractRegistryKey: string;
812
+ targetContractAddress: string;
813
+ callValue: number;
814
+ functionSignature: string;
815
+ callData: string;
816
+ outcome: number;
817
+ numVotes: number;
818
+ voteMagnitudeYes: BN;
819
+ voteMagnitudeNo: BN;
820
+ }>;
821
+ getProposalTargetContractHash(id: string): Promise<any>;
822
+ getProposals(queryStartBlock?: number): Promise<{
823
+ proposalId: number;
824
+ proposer: any;
825
+ description: any;
826
+ name: any;
827
+ blockNumber: number;
828
+ }[]>;
829
+ getProposalsForAddresses(addresses: string[], queryStartBlock?: number): Promise<{
830
+ proposalId: number;
831
+ proposer: any;
832
+ description: any;
833
+ name: any;
834
+ blockNumber: number;
835
+ }[]>;
836
+ getProposalSubmission(proposalId: number, queryStartBlock?: number): Promise<{
837
+ proposalId: number;
838
+ proposer: any;
839
+ description: any;
840
+ name: any;
841
+ blockNumber: number;
842
+ }>;
843
+ getInProgressProposals(): Promise<any>;
844
+ submitProposal({ targetContractRegistryKey, callValue, functionSignature, callData, // array of args, e.g. [slashAmount, targetAddress]
845
+ name, description }: {
846
+ targetContractRegistryKey: string;
847
+ callValue: string;
848
+ functionSignature: string;
849
+ callData: string[];
850
+ name: string;
851
+ description: string;
852
+ }): Promise<any>;
853
+ submitVote({ proposalId, vote }: {
854
+ proposalId: number;
855
+ vote: string;
856
+ }): Promise<void>;
857
+ updateVote({ proposalId, vote }: {
858
+ proposalId: number;
859
+ vote: string;
860
+ }): Promise<void>;
861
+ evaluateProposalOutcome(proposalId: number): Promise<web3_core.TransactionReceipt>;
862
+ getProposalEvaluation(proposalId: number, queryStartBlock?: number): Promise<web3_eth_contract.EventData[]>;
863
+ getVotes({ proposalId, queryStartBlock }: {
864
+ proposalId: number;
865
+ queryStartBlock: number;
866
+ }): Promise<{
867
+ proposalId: number;
868
+ voter: any;
869
+ vote: number;
870
+ voterStake: BN;
871
+ blockNumber: number;
872
+ }[]>;
873
+ getVoteUpdates({ proposalId, queryStartBlock }: {
874
+ proposalId: number;
875
+ queryStartBlock: number;
876
+ }): Promise<{
877
+ proposalId: number;
878
+ voter: any;
879
+ vote: number;
880
+ voterStake: BN;
881
+ blockNumber: number;
882
+ }[]>;
883
+ getVoteSubmissionsByAddress({ addresses, queryStartBlock }: {
884
+ addresses: string[];
885
+ queryStartBlock: number;
886
+ }): Promise<{
887
+ proposalId: number;
888
+ voter: any;
889
+ vote: number;
890
+ voterStake: BN;
891
+ blockNumber: number;
892
+ }[]>;
893
+ getVoteUpdatesByAddress({ addresses, queryStartBlock }: {
894
+ addresses: string[];
895
+ queryStartBlock: number;
896
+ }): Promise<{
897
+ proposalId: number;
898
+ voter: any;
899
+ vote: number;
900
+ voterStake: BN;
901
+ blockNumber: number;
902
+ }[]>;
903
+ getVoteByProposalAndVoter({ proposalId, voterAddress }: {
904
+ proposalId: number[];
905
+ voterAddress: number;
906
+ }): Promise<number>;
907
+ /**
908
+ * ABI encodes argument types and values together into one encoded string
909
+ */
910
+ abiEncode(types: string[], values: string[]): string;
911
+ toBN(val: string): BN;
912
+ /**
913
+ * Prune off extraneous fields from proposal returned by txn
914
+ */
915
+ formatProposal(proposal: ProposalTxn): {
916
+ proposalId: number;
917
+ proposer: string;
918
+ submissionBlockNumber: number;
919
+ targetContractRegistryKey: string;
920
+ targetContractAddress: string;
921
+ callValue: number;
922
+ functionSignature: string;
923
+ callData: string;
924
+ outcome: number;
925
+ numVotes: number;
926
+ voteMagnitudeYes: BN;
927
+ voteMagnitudeNo: BN;
928
+ };
929
+ /**
930
+ * Formats a proposal event
931
+ */
932
+ formatProposalEvent(proposalEvent: EventLog): {
933
+ proposalId: number;
934
+ proposer: any;
935
+ description: any;
936
+ name: any;
937
+ blockNumber: number;
938
+ };
939
+ /**
940
+ * Prune off extraneous fields from vote event
941
+ */
942
+ formatVote(voteEvent: EventLog): {
943
+ proposalId: number;
944
+ voter: any;
945
+ vote: number;
946
+ voterStake: BN;
947
+ blockNumber: number;
948
+ };
949
+ /**
950
+ *
951
+ * @param {Number} proposalId id of the governance proposal
952
+ * @returns {BN} amount of tokens in wei required to reach quorum
953
+ */
954
+ calculateQuorum(proposalId: number): Promise<any>;
955
+ }
956
+
957
+ /**
958
+ * Contract class that extends a ContractClient and provides an interface
959
+ * to retrieve governed methods that cannot be executed directly.
960
+ */
961
+ declare class GovernedContractClient extends ContractClient {
962
+ governanceClient: GovernanceClient;
963
+ constructor(web3Manager: Web3Manager | EthWeb3Manager, contractABI: ContractABI['abi'], contractRegistryKey: string, getRegistryAddress: GetRegistryAddress, governanceClient: GovernanceClient, logger?: Logger);
964
+ /**
965
+ * Gets a governed version of a method and allows a single transaction
966
+ * to be sent to the governance client with the appropriate payload.
967
+ * Similar to `getMethod`
968
+ */
969
+ getGovernedMethod(methodName: string, ...args: unknown[]): Promise<ContractMethod>;
970
+ }
971
+
972
+ declare class ServiceTypeManagerClient extends GovernedContractClient {
973
+ /**
974
+ *
975
+ * @param serviceType Type of service to set the version, either `discovery-node` or `content-node`
976
+ * @param serviceVersion Version string to set on chain
977
+ * @param privateKey Optional privateKey to pass along to web3Manager sendTransaction
978
+ * @param dryRun Optional parameter to return the generated parameters without sending tx
979
+ * @returns comma-separated String of serviceType and serviceVersion if dryRun; else response from web3Manager.sendTransaction
980
+ */
981
+ setServiceVersion(serviceType: string, serviceVersion: string, privateKey?: string | null, dryRun?: boolean): Promise<string | web3_core.TransactionReceipt>;
982
+ addServiceType(serviceType: string, serviceTypeMin: string, serviceTypeMax: string, privateKey?: string | null): Promise<web3_core.TransactionReceipt>;
983
+ getValidServiceTypes(): Promise<string[]>;
984
+ getCurrentVersion(serviceType: string): Promise<string>;
985
+ getVersion(serviceType: string, serviceTypeIndex: number): Promise<string>;
986
+ getNumberOfVersions(serviceType: string): Promise<number>;
987
+ /**
988
+ * @notice Add a new service type
989
+ * @returns {
990
+ * isValid: Is the types type is isValid
991
+ * minStake: minimum stake for service type
992
+ * maxStake: minimum stake for service type
993
+ * }
994
+ */
995
+ getServiceTypeInfo(serviceType: string): Promise<{
996
+ isValid: any;
997
+ minStake: BN;
998
+ maxStake: BN;
999
+ }>;
1000
+ }
1001
+
1002
+ declare type GetEvent$1 = {
1003
+ serviceType: string;
1004
+ owner: string;
1005
+ queryStartBlock: number;
1006
+ };
1007
+ declare class ServiceProviderFactoryClient extends GovernedContractClient {
1008
+ audiusTokenClient: AudiusTokenClient;
1009
+ stakingProxyClient: StakingProxyClient;
1010
+ isDebug: boolean;
1011
+ constructor(ethWeb3Manager: EthWeb3Manager, contractABI: ContractABI['abi'], contractRegistryKey: string, getRegistryAddress: GetRegistryAddress, audiusTokenClient: AudiusTokenClient, stakingProxyClient: StakingProxyClient, governanceClient: GovernanceClient, logger?: Logger, isDebug?: boolean);
1012
+ registerWithDelegate(serviceType: string, endpoint: string, amount: number | string | BN__default, delegateOwnerWallet: string): Promise<{
1013
+ txReceipt: web3_core.TransactionReceipt;
1014
+ spID: number;
1015
+ serviceType: string;
1016
+ owner: any;
1017
+ endpoint: any;
1018
+ tokenApproveReceipt: {
1019
+ txReceipt: web3_core.TransactionReceipt;
1020
+ };
1021
+ }>;
1022
+ register(serviceType: string, endpoint: string, amount: BN__default): Promise<{
1023
+ txReceipt: web3_core.TransactionReceipt;
1024
+ spID: number;
1025
+ serviceType: string;
1026
+ owner: any;
1027
+ endpoint: any;
1028
+ tokenApproveReceipt: {
1029
+ txReceipt: web3_core.TransactionReceipt;
1030
+ };
1031
+ }>;
1032
+ getRegisteredServiceProviderEvents({ serviceType, owner, queryStartBlock }: GetEvent$1): Promise<{
1033
+ blockNumber: number;
1034
+ spID: number;
1035
+ serviceType: string;
1036
+ owner: any;
1037
+ endpoint: any;
1038
+ stakeAmount: BN__default;
1039
+ }[]>;
1040
+ getDeregisteredServiceProviderEvents({ serviceType, owner, queryStartBlock }: GetEvent$1): Promise<{
1041
+ blockNumber: number;
1042
+ spID: number;
1043
+ serviceType: string;
1044
+ owner: any;
1045
+ endpoint: any;
1046
+ stakeAmount: BN__default;
1047
+ }[]>;
1048
+ getIncreasedStakeEvents({ owner, queryStartBlock }: {
1049
+ owner: string;
1050
+ queryStartBlock: number;
1051
+ }): Promise<{
1052
+ blockNumber: number;
1053
+ owner: any;
1054
+ increaseAmount: BN__default;
1055
+ newStakeAmount: BN__default;
1056
+ }[]>;
1057
+ getDecreasedStakeEvaluatedEvents({ owner, queryStartBlock }: {
1058
+ owner: string;
1059
+ queryStartBlock: number;
1060
+ }): Promise<{
1061
+ blockNumber: number;
1062
+ owner: any;
1063
+ decreaseAmount: BN__default;
1064
+ newStakeAmount: BN__default;
1065
+ }[]>;
1066
+ getDecreasedStakeRequestedEvents({ owner, queryStartBlock }: {
1067
+ owner: string;
1068
+ queryStartBlock: number;
1069
+ }): Promise<{
1070
+ blockNumber: number;
1071
+ owner: any;
1072
+ decreaseAmount: BN__default;
1073
+ lockupExpiryBlock: number;
1074
+ }[]>;
1075
+ getDecreasedStakeCancelledEvents({ owner, queryStartBlock }: {
1076
+ owner: string;
1077
+ queryStartBlock: number;
1078
+ }): Promise<{
1079
+ blockNumber: number;
1080
+ owner: any;
1081
+ decreaseAmount: BN__default;
1082
+ lockupExpiryBlock: number;
1083
+ }[]>;
1084
+ getDeregisteredService({ serviceType, spID, queryStartBlock }: {
1085
+ serviceType: string;
1086
+ spID: string;
1087
+ queryStartBlock: number;
1088
+ }): Promise<{
1089
+ endpoint: string;
1090
+ delegateOwnerWallet: string;
1091
+ owner?: string | undefined;
1092
+ }>;
1093
+ increaseStake(amount: BN__default): Promise<{
1094
+ txReceipt: web3_core.TransactionReceipt;
1095
+ tokenApproveReceipt: {
1096
+ txReceipt: web3_core.TransactionReceipt;
1097
+ };
1098
+ }>;
1099
+ /**
1100
+ * Makes a request to decrease stake
1101
+ * @param amount
1102
+ * @returns decrease stake lockup expiry block
1103
+ */
1104
+ requestDecreaseStake(amount: BN__default): Promise<number>;
1105
+ /**
1106
+ * Gets the pending decrease stake request for a given account
1107
+ * @param account wallet address to fetch for
1108
+ */
1109
+ getPendingDecreaseStakeRequest(account: string): Promise<{
1110
+ amount: BN__default;
1111
+ lockupExpiryBlock: number;
1112
+ }>;
1113
+ /**
1114
+ * Gets the pending decrease stake lockup duration
1115
+ */
1116
+ getDecreaseStakeLockupDuration(): Promise<number>;
1117
+ /**
1118
+ * Gets the deployer cut lockup duration
1119
+ */
1120
+ getDeployerCutLockupDuration(): Promise<number>;
1121
+ /**
1122
+ * Cancels the pending decrease stake request
1123
+ * @param account wallet address to cancel request for
1124
+ */
1125
+ cancelDecreaseStakeRequest(account: string): Promise<void>;
1126
+ /**
1127
+ * Fetches the pending decrease stake lockup expiry block for a user
1128
+ * @param account wallet address to fetch for
1129
+ */
1130
+ getLockupExpiry(account: string): Promise<number>;
1131
+ decreaseStake(): Promise<{
1132
+ txReceipt: web3_core.TransactionReceipt;
1133
+ }>;
1134
+ /**
1135
+ * Deregisters a service
1136
+ * @param serviceType
1137
+ * @param endpoint
1138
+ */
1139
+ deregister(serviceType: string, endpoint: string): Promise<{
1140
+ txReceipt: web3_core.TransactionReceipt;
1141
+ spID: number;
1142
+ serviceType: string;
1143
+ owner: any;
1144
+ endpoint: any;
1145
+ }>;
1146
+ getTotalServiceTypeProviders(serviceType: string): Promise<number>;
1147
+ getServiceProviderIdFromEndpoint(endpoint: string): Promise<number>;
1148
+ getServiceProviderInfo(serviceType: string, serviceId: number): Promise<{
1149
+ owner: any;
1150
+ endpoint: any;
1151
+ spID: number;
1152
+ type: string;
1153
+ blockNumber: number;
1154
+ delegateOwnerWallet: any;
1155
+ }>;
1156
+ getServiceEndpointInfo(serviceType: string, serviceId: number): Promise<{
1157
+ owner: any;
1158
+ endpoint: any;
1159
+ spID: number;
1160
+ type: string;
1161
+ blockNumber: number;
1162
+ delegateOwnerWallet: any;
1163
+ }>;
1164
+ getServiceProviderInfoFromEndpoint(endpoint: string): Promise<{
1165
+ owner: any;
1166
+ endpoint: any;
1167
+ spID: number;
1168
+ type: string;
1169
+ blockNumber: number;
1170
+ delegateOwnerWallet: any;
1171
+ }>;
1172
+ getServiceProviderIdsFromAddress(ownerAddress: string, serviceType: string): Promise<number[]>;
1173
+ getServiceProviderIdFromAddress(ownerAddress: string, serviceType: string): Promise<number>;
1174
+ getServiceEndpointInfoFromAddress(ownerAddress: string, serviceType: string): Promise<{
1175
+ owner: any;
1176
+ endpoint: any;
1177
+ spID: number;
1178
+ type: string;
1179
+ blockNumber: number;
1180
+ delegateOwnerWallet: any;
1181
+ }[]>;
1182
+ /**
1183
+ * Returns all service providers of requested `serviceType`
1184
+ * Returns array of objects with schema { blockNumber, delegateOwnerWallet, endpoint, owner, spID, type }
1185
+ */
1186
+ getServiceProviderList(serviceType: string): Promise<{
1187
+ owner: any;
1188
+ endpoint: any;
1189
+ spID: number;
1190
+ type: string;
1191
+ blockNumber: number;
1192
+ delegateOwnerWallet: any;
1193
+ }[]>;
1194
+ updateDecreaseStakeLockupDuration(duration: string): Promise<web3_core.TransactionReceipt>;
1195
+ getServiceProviderDetails(serviceProviderAddress: string): Promise<{
1196
+ deployerCut: number;
1197
+ deployerStake: BN__default;
1198
+ maxAccountStake: BN__default;
1199
+ minAccountStake: BN__default;
1200
+ numberOfEndpoints: number;
1201
+ validBounds: any;
1202
+ }>;
1203
+ updateDelegateOwnerWallet(serviceType: string, endpoint: string, updatedDelegateOwnerWallet: string): Promise<web3_core.TransactionReceipt>;
1204
+ updateEndpoint(serviceType: string, oldEndpoint: string, newEndpoint: string): Promise<web3_core.TransactionReceipt>;
1205
+ requestUpdateDeployerCut(ownerAddress: string, deployerCut: string): Promise<web3_core.TransactionReceipt>;
1206
+ getPendingUpdateDeployerCutRequest(ownerAddress: string): Promise<{
1207
+ lockupExpiryBlock: number;
1208
+ newDeployerCut: number;
1209
+ }>;
1210
+ cancelUpdateDeployerCut(ownerAddress: string): Promise<web3_core.TransactionReceipt>;
1211
+ updateDeployerCut(ownerAddress: string): Promise<web3_core.TransactionReceipt>;
1212
+ updateServiceProviderStake(ownerAddress: string, newAmount: string): Promise<web3_core.TransactionReceipt>;
1213
+ }
1214
+
1215
+ declare type GetEvent = {
1216
+ delegator: string;
1217
+ serviceProvider: string;
1218
+ queryStartBlock: number;
1219
+ };
1220
+ declare class DelegateManagerClient extends GovernedContractClient {
1221
+ audiusTokenClient: AudiusTokenClient;
1222
+ stakingProxyClient: StakingProxyClient;
1223
+ constructor(ethWeb3Manager: EthWeb3Manager, contractABI: ContractABI['abi'], contractRegistryKey: string, getRegistryAddress: GetRegistryAddress, audiusTokenClient: AudiusTokenClient, stakingProxyClient: StakingProxyClient, governanceClient: GovernanceClient, logger?: Logger);
1224
+ delegateStake(targetSP: string, amount: BN__default): Promise<{
1225
+ txReceipt: web3_core.TransactionReceipt;
1226
+ tokenApproveReceipt: {
1227
+ txReceipt: web3_core.TransactionReceipt;
1228
+ };
1229
+ delegator: any;
1230
+ serviceProvider: any;
1231
+ increaseAmount: BN__default;
1232
+ }>;
1233
+ getIncreaseDelegateStakeEvents({ delegator, serviceProvider, queryStartBlock }: GetEvent): Promise<{
1234
+ blockNumber: number;
1235
+ delegator: any;
1236
+ increaseAmount: BN__default;
1237
+ serviceProvider: any;
1238
+ }[]>;
1239
+ getDecreaseDelegateStakeEvents({ delegator, serviceProvider, queryStartBlock }: GetEvent): Promise<{
1240
+ blockNumber: number;
1241
+ delegator: any;
1242
+ amount: BN__default;
1243
+ serviceProvider: any;
1244
+ }[]>;
1245
+ getUndelegateStakeRequestedEvents({ delegator, serviceProvider, queryStartBlock }: GetEvent): Promise<{
1246
+ blockNumber: number;
1247
+ lockupExpiryBlock: number;
1248
+ delegator: any;
1249
+ amount: BN__default;
1250
+ serviceProvider: any;
1251
+ }[]>;
1252
+ getUndelegateStakeCancelledEvents({ delegator, serviceProvider, queryStartBlock }: GetEvent): Promise<{
1253
+ blockNumber: number;
1254
+ delegator: any;
1255
+ amount: BN__default;
1256
+ serviceProvider: any;
1257
+ }[]>;
1258
+ getClaimEvents({ claimer, queryStartBlock }: {
1259
+ claimer: string;
1260
+ queryStartBlock: number;
1261
+ }): Promise<{
1262
+ blockNumber: number;
1263
+ claimer: any;
1264
+ rewards: BN__default;
1265
+ newTotal: BN__default;
1266
+ }[]>;
1267
+ getSlashEvents({ target, queryStartBlock }: {
1268
+ target: string;
1269
+ queryStartBlock: number;
1270
+ }): Promise<{
1271
+ blockNumber: number;
1272
+ target: any;
1273
+ amount: BN__default;
1274
+ newTotal: BN__default;
1275
+ }[]>;
1276
+ getDelegatorRemovedEvents({ target, queryStartBlock }: {
1277
+ target: string;
1278
+ queryStartBlock: number;
1279
+ }): Promise<{
1280
+ blockNumber: number;
1281
+ serviceProvider: any;
1282
+ delegator: any;
1283
+ unstakedAmount: BN__default;
1284
+ }[]>;
1285
+ requestUndelegateStake(targetSP: string, amount: BN__default): Promise<web3_core.TransactionReceipt>;
1286
+ cancelUndelegateStakeRequest(): Promise<web3_core.TransactionReceipt>;
1287
+ undelegateStake(): Promise<{
1288
+ txReceipt: web3_core.TransactionReceipt;
1289
+ delegator: any;
1290
+ serviceProvider: any;
1291
+ decreaseAmount: BN__default;
1292
+ }>;
1293
+ claimRewards(serviceProvider: string, txRetries?: number): Promise<web3_core.TransactionReceipt>;
1294
+ requestRemoveDelegator(serviceProvider: string, delegator: string): Promise<web3_core.TransactionReceipt>;
1295
+ cancelRemoveDelegatorRequest(serviceProvider: string, delegator: string): Promise<web3_core.TransactionReceipt>;
1296
+ removeDelegator(serviceProvider: string, delegator: string): Promise<{
1297
+ txReceipt: web3_core.TransactionReceipt;
1298
+ delegator: any;
1299
+ serviceProvider: any;
1300
+ unstakedAmount: BN__default;
1301
+ }>;
1302
+ getDelegatorsList(serviceProvider: string): Promise<any>;
1303
+ getTotalDelegatedToServiceProvider(serviceProvider: string): Promise<BN__default>;
1304
+ getTotalDelegatorStake(delegator: string): Promise<BN__default>;
1305
+ getTotalLockedDelegationForServiceProvider(serviceProvider: string): Promise<BN__default>;
1306
+ getDelegatorStakeForServiceProvider(delegator: string, serviceProvider: string): Promise<BN__default>;
1307
+ getPendingUndelegateRequest(delegator: string): Promise<{
1308
+ amount: BN__default;
1309
+ lockupExpiryBlock: number;
1310
+ target: any;
1311
+ }>;
1312
+ getPendingRemoveDelegatorRequest(serviceProvider: string, delegator: string): Promise<{
1313
+ lockupExpiryBlock: number;
1314
+ }>;
1315
+ getUndelegateLockupDuration(): Promise<number>;
1316
+ getMaxDelegators(): Promise<number>;
1317
+ getMinDelegationAmount(): Promise<BN__default>;
1318
+ getRemoveDelegatorLockupDuration(): Promise<number>;
1319
+ getRemoveDelegatorEvalDuration(): Promise<number>;
1320
+ getGovernanceAddress(): Promise<any>;
1321
+ getServiceProviderFactoryAddress(): Promise<any>;
1322
+ getClaimsManagerAddress(): Promise<any>;
1323
+ getStakingAddress(): Promise<any>;
1324
+ getSPMinDelegationAmount({ serviceProvider }: {
1325
+ serviceProvider: string;
1326
+ }): Promise<BN__default>;
1327
+ updateSPMinDelegationAmount({ serviceProvider, amount }: {
1328
+ serviceProvider: string;
1329
+ amount: BN__default;
1330
+ }): Promise<web3_core.TransactionReceipt>;
1331
+ updateRemoveDelegatorLockupDuration(duration: string): Promise<web3_core.TransactionReceipt>;
1332
+ updateUndelegateLockupDuration(duration: string): Promise<web3_core.TransactionReceipt>;
1333
+ }
1334
+
1335
+ declare class ClaimsManagerClient extends ContractClient {
1336
+ web3Manager: EthWeb3Manager;
1337
+ getFundingRoundBlockDiff(): Promise<number>;
1338
+ getLastFundedBlock(): Promise<number>;
1339
+ getFundsPerRound(): Promise<BN>;
1340
+ getTotalClaimedInRound(): Promise<BN>;
1341
+ getGovernanceAddress(): Promise<any>;
1342
+ getServiceProviderFactoryAddress(): Promise<any>;
1343
+ getDelegateManagerAddress(): Promise<any>;
1344
+ getStakingAddress(): Promise<any>;
1345
+ claimPending(address: string): Promise<any>;
1346
+ initiateRound(txRetries?: number): Promise<web3_core.TransactionReceipt>;
1347
+ getClaimProcessedEvents({ claimer, queryStartBlock }: {
1348
+ claimer: string;
1349
+ queryStartBlock: number;
1350
+ }): Promise<{
1351
+ blockNumber: number;
1352
+ claimer: any;
1353
+ rewards: BN;
1354
+ oldTotal: BN;
1355
+ newTotal: BN;
1356
+ }[]>;
1357
+ }
1358
+
1359
+ declare class ClaimDistributionClient extends ContractClient {
1360
+ /**
1361
+ * Calls the contract method to check if the claim index has been claimed
1362
+ */
1363
+ isClaimed(index: number): Promise<any>;
1364
+ /**
1365
+ * Proxies the calls the contract method to make a claim
1366
+ * @param index
1367
+ * @param account
1368
+ * @param amount
1369
+ * @param merkleProof
1370
+ * @returns transaction
1371
+ */
1372
+ claim(index: number, account: string, amount: BN__default, merkleProof: string[]): Promise<Maybe<{
1373
+ txHash: string;
1374
+ txParams: {
1375
+ /**
1376
+ * Proxies the calls the contract method to make a claim
1377
+ * @param index
1378
+ * @param account
1379
+ * @param amount
1380
+ * @param merkleProof
1381
+ * @returns transaction
1382
+ */
1383
+ data: string;
1384
+ gasLimit: string;
1385
+ gasPrice: number;
1386
+ nonce: string;
1387
+ to: string;
1388
+ value: string;
1389
+ };
1390
+ }>>;
1391
+ }
1392
+
1393
+ declare class WormholeClient {
1394
+ ethWeb3Manager: EthWeb3Manager;
1395
+ contractABI: ContractABI['abi'];
1396
+ contractAddress: string;
1397
+ web3: Web3__default;
1398
+ audiusTokenClient: AudiusTokenClient;
1399
+ WormholeContract: Contract;
1400
+ constructor(ethWeb3Manager: EthWeb3Manager, contractABI: ContractABI['abi'], contractAddress: string, audiusTokenClient: AudiusTokenClient);
1401
+ nonces(wallet: string): Promise<number>;
1402
+ initialize(fromAcct: string, wormholeAddress: string, relayer: string): Promise<{
1403
+ txReceipt: Maybe<{
1404
+ txHash: string;
1405
+ txParams: {
1406
+ data: string;
1407
+ gasLimit: string;
1408
+ gasPrice: number;
1409
+ nonce: string;
1410
+ to: string;
1411
+ value: string;
1412
+ };
1413
+ }>;
1414
+ }>;
1415
+ /**
1416
+ * Transfers in eth from the user's wallet to the wormhole contract and
1417
+ * specifies a solana wallet to realized the tokens in SOL
1418
+ */
1419
+ transferTokens(fromAcct: string, amount: BN__default, chainId: number, solanaAccount: string, arbiterFee: string, deadline: string, signedDigest: {
1420
+ v: string;
1421
+ r: string;
1422
+ s: string;
1423
+ }, relayer: string): Promise<Maybe<{
1424
+ txHash: string;
1425
+ txParams: {
1426
+ data: string;
1427
+ gasLimit: string;
1428
+ gasPrice: number;
1429
+ nonce: string;
1430
+ to: string;
1431
+ value: string;
1432
+ };
1433
+ }>>;
1434
+ }
1435
+
1436
+ declare class EthRewardsManagerClient extends ContractClient {
1437
+ token(): Promise<any>;
1438
+ getGovernanceAddress(): Promise<any>;
1439
+ getRecipientAddress(): Promise<any>;
1440
+ getAntiAbuseOracleAddresses(): Promise<any>;
1441
+ }
1442
+
1443
+ declare class TrustedNotifierManagerClient extends GovernedContractClient {
1444
+ /**
1445
+ * Register Trusted Notifier with specified fields (wallet, endpoint, email)
1446
+ * @notice Only callable by Governance contract
1447
+ * @notice All fields must be unique and non-falsey
1448
+ * @notice New Trusted Notifier is assigned an auto-incremented integer ID
1449
+ * @returns Newly assigned integer ID
1450
+ */
1451
+ registerNotifier(wallet: string, endpoint: string, email: string, privateKey?: string | null): Promise<web3_core.TransactionReceipt>;
1452
+ /**
1453
+ * Deregister Trusted Notifier associated with wallet
1454
+ * @notice Only callable by Governance contract or wallet
1455
+ * @returns ID of deregistered Trusted Notifier
1456
+ */
1457
+ deregisterNotifier(wallet: string, privateKey?: string | null): Promise<web3_core.TransactionReceipt>;
1458
+ getLatestNotifierID(): Promise<number>;
1459
+ /**
1460
+ * Returns all TrustedNotifier info associated with ID
1461
+ */
1462
+ getNotifierForID(ID: string): Promise<{
1463
+ wallet: any;
1464
+ endpoint: any;
1465
+ email: any;
1466
+ }>;
1467
+ /**
1468
+ * Returns all TrustedNotifier info associated with wallet
1469
+ */
1470
+ getNotifierForWallet(wallet: string): Promise<{
1471
+ ID: any;
1472
+ endpoint: any;
1473
+ email: any;
1474
+ }>;
1475
+ /**
1476
+ * Returns all TrustedNotifier info associated with endpoint
1477
+ */
1478
+ getNotifierForEndpoint(endpoint: string): Promise<{
1479
+ ID: any;
1480
+ wallet: any;
1481
+ email: any;
1482
+ }>;
1483
+ /**
1484
+ * Returns all TrustedNotifier info associated with email
1485
+ */
1486
+ getNotifierForEmail(email: string): Promise<{
1487
+ ID: any;
1488
+ wallet: any;
1489
+ endpoint: any;
1490
+ }>;
1491
+ }
1492
+
1493
+ declare type EthContractsConfig = {
1494
+ ethWeb3Manager: EthWeb3Manager;
1495
+ tokenContractAddress: string;
1496
+ registryAddress: string;
1497
+ claimDistributionContractAddress: string;
1498
+ wormholeContractAddress: string;
1499
+ isServer?: boolean;
1500
+ logger?: Logger;
1501
+ isDebug?: boolean;
1502
+ };
1503
+ declare class EthContracts {
1504
+ ethWeb3Manager: EthWeb3Manager;
1505
+ tokenContractAddress: string;
1506
+ claimDistributionContractAddress: string;
1507
+ wormholeContractAddress: string;
1508
+ registryAddress: string;
1509
+ isServer: boolean;
1510
+ logger: Logger;
1511
+ isDebug: boolean;
1512
+ expectedServiceVersions: null | string[];
1513
+ AudiusTokenClient: AudiusTokenClient;
1514
+ RegistryClient: RegistryClient;
1515
+ StakingProxyClient: StakingProxyClient;
1516
+ GovernanceClient: GovernanceClient;
1517
+ ClaimsManagerClient: ClaimsManagerClient;
1518
+ EthRewardsManagerClient: EthRewardsManagerClient;
1519
+ ServiceTypeManagerClient: ServiceTypeManagerClient;
1520
+ ServiceProviderFactoryClient: ServiceProviderFactoryClient;
1521
+ DelegateManagerClient: DelegateManagerClient;
1522
+ ClaimDistributionClient: ClaimDistributionClient | undefined;
1523
+ WormholeClient: WormholeClient;
1524
+ TrustedNotifierManagerClient: TrustedNotifierManagerClient;
1525
+ contractClients: ContractClient[];
1526
+ _regressedMode: boolean;
1527
+ contracts: Record<string, string> | undefined;
1528
+ contractAddresses: Record<string, string> | undefined;
1529
+ constructor({ ethWeb3Manager, tokenContractAddress, registryAddress, claimDistributionContractAddress, wormholeContractAddress, isServer, logger, isDebug }: EthContractsConfig);
1530
+ init(): Promise<void>;
1531
+ /**
1532
+ * Estabilishes that connection to discovery providers has regressed
1533
+ */
1534
+ enterRegressedMode(): void;
1535
+ isInRegressedMode(): boolean;
1536
+ getRegistryAddressForContract(contractName: string): Promise<string>;
1537
+ getCurrentVersion(serviceType: string): Promise<string>;
1538
+ getExpectedServiceVersions(): Promise<Record<string, string | null | undefined>>;
1539
+ /**
1540
+ * Determine whether major and minor versions match for two version strings
1541
+ * Version string 2 must have equivalent major/minor versions and a patch >= version1
1542
+ * @param version1 string 1
1543
+ * @param version2 string 2
1544
+ */
1545
+ isValidSPVersion(version1: string, version2: string): boolean;
1546
+ /**
1547
+ * Determines whether the major and minor versions are equal
1548
+ * @param version1 string 1
1549
+ * @param version2 string 2
1550
+ */
1551
+ hasSameMajorAndMinorVersion(version1: string, version2: string): boolean;
1552
+ getServiceProviderList(spType: string): Promise<{
1553
+ owner: any;
1554
+ endpoint: any;
1555
+ spID: number;
1556
+ type: string;
1557
+ blockNumber: number;
1558
+ delegateOwnerWallet: any;
1559
+ }[]>;
1560
+ getNumberOfVersions(spType: string): Promise<number>;
1561
+ getVersion(spType: string, queryIndex: number): Promise<string>;
1562
+ getServiceTypeInfo(spType: string): Promise<{
1563
+ isValid: any;
1564
+ minStake: BN;
1565
+ maxStake: BN;
1566
+ }>;
1567
+ }
1568
+
1569
+ declare type DiscoveryProviderSelectionConfig = Omit<ServiceSelectionConfig, 'getServices'> & {
1570
+ reselectTimeout?: number;
1571
+ selectionCallback?: (endpoint: string, decisionTree: Decision[]) => void;
1572
+ monitoringCallbacks?: {
1573
+ healthCheck: (config: Record<string, unknown>) => void;
1574
+ request: (config: Record<string, unknown>) => void;
1575
+ };
1576
+ unhealthySlotDiffPlays?: number;
1577
+ unhealthyBlockDiff?: number;
1578
+ };
1579
+ declare class DiscoveryProviderSelection extends ServiceSelection {
1580
+ currentVersion: string;
1581
+ ethContracts: EthContracts;
1582
+ reselectTimeout: Maybe<number>;
1583
+ selectionCallback: Maybe<DiscoveryProviderSelectionConfig['selectionCallback']>;
1584
+ monitoringCallbacks: NonNullable<DiscoveryProviderSelectionConfig['monitoringCallbacks']> | {};
1585
+ unhealthySlotDiffPlays: Nullable<number>;
1586
+ unhealthyBlockDiff: number;
1587
+ _regressedMode: boolean;
1588
+ validVersions: Nullable<string[]>;
1589
+ constructor(config: DiscoveryProviderSelectionConfig, ethContracts: EthContracts);
1590
+ /** Retrieves a cached discovery provider from localstorage */
1591
+ getCached(): any;
1592
+ /** Clears any cached discovery provider from localstorage */
1593
+ clearCached(): void;
1594
+ /** Sets a cached discovery provider in localstorage */
1595
+ setCached(endpoint: string): void;
1596
+ /** Allows the selection take a shortcut if there's a cached provider */
1597
+ shortcircuit(): any;
1598
+ select(): Promise<any>;
1599
+ /**
1600
+ * Checks whether a given response is healthy:
1601
+ * - Not behind in blocks
1602
+ * - 200 response
1603
+ * - Current version
1604
+ *
1605
+ * Other responses are collected in `this.backups` if
1606
+ * - Behind by only a patch version
1607
+ *
1608
+ * @param response axios response
1609
+ * @param urlMap health check urls mapped to their cannonical url
1610
+ * e.g. https://discoveryprovider.audius.co/health_check => https://discoveryprovider.audius.co
1611
+ */
1612
+ isHealthy(response: AxiosResponse, urlMap: Record<string, string>): boolean;
1613
+ /**
1614
+ * Estabilishes that connection to discovery providers has regressed
1615
+ */
1616
+ enterRegressedMode(): void;
1617
+ setUnhealthyBlockDiff(updatedDiff?: number): void;
1618
+ setUnhealthySlotDiffPlays(updatedDiff: number): void;
1619
+ isInRegressedMode(): boolean;
1620
+ /**
1621
+ * In the case of no "healthy" services, we resort to backups in the following order:
1622
+ * 1. Pick the most recent (patch) version that's not behind
1623
+ * 2. Pick the least behind provider that is a valid patch version and enter "regressed mode"
1624
+ * 3. Pick `null`
1625
+ */
1626
+ selectFromBackups(): Promise<string>;
1627
+ }
1628
+
1629
+ declare type CurrentUser = {
1630
+ user_id: string;
1631
+ wallet: string;
1632
+ blocknumber: number;
1633
+ track_blocknumber: number;
1634
+ creator_node_endpoint: string;
1635
+ is_creator: boolean;
1636
+ };
1637
+ /**
1638
+ * Singleton class to store the current user if initialized.
1639
+ * Some instances of AudiusLibs and services require a current user to
1640
+ * return valid queries, e.g. requesting the a discprov to return a reposted track.
1641
+ */
1642
+ declare class UserStateManager {
1643
+ currentUser: CurrentUser | null;
1644
+ constructor();
1645
+ /**
1646
+ * Sets this.currentUser with currentUser
1647
+ * @param {Object} currentUser fields to override this.currentUser with
1648
+ */
1649
+ setCurrentUser(currentUser: CurrentUser): void;
1650
+ getCurrentUser(): CurrentUser | null;
1651
+ getCurrentUserId(): string | null;
1652
+ clearUser(): void;
1653
+ }
1654
+
1655
+ declare type RequestParams = {
1656
+ queryParams: Record<string, string>;
1657
+ endpoint: string;
1658
+ timeout?: number;
1659
+ method?: Method;
1660
+ urlParams?: PathArg;
1661
+ headers?: Record<string, string>;
1662
+ data?: Record<string, unknown>;
1663
+ };
1664
+ declare type DiscoveryProviderConfig = {
1665
+ whitelist?: Set<string>;
1666
+ blacklist?: Set<string>;
1667
+ userStateManager: UserStateManager;
1668
+ ethContracts: EthContracts;
1669
+ web3Manager?: Web3Manager;
1670
+ reselectTimeout?: number;
1671
+ selectionCallback?: DiscoveryProviderSelectionConfig['selectionCallback'];
1672
+ monitoringCallbacks?: DiscoveryProviderSelectionConfig['monitoringCallbacks'];
1673
+ selectionRequestTimeout?: number;
1674
+ selectionRequestRetries?: number;
1675
+ unhealthySlotDiffPlays?: number;
1676
+ unhealthyBlockDiff?: number;
1677
+ };
1678
+ declare type UserProfile = {
1679
+ userId: number;
1680
+ email: string;
1681
+ name: string;
1682
+ handle: string;
1683
+ verified: boolean;
1684
+ imageURL?: string;
1685
+ sub: number;
1686
+ iat: string;
1687
+ };
1688
+ /**
1689
+ * Constructs a service class for a discovery node
1690
+ * @param whitelist whether or not to only include specified nodes in selection
1691
+ * @param userStateManager singleton UserStateManager instance
1692
+ * @param ethContracts singleton EthContracts instance
1693
+ * @param web3Manager
1694
+ * @param reselectTimeout timeout to clear locally cached discovery providers
1695
+ * @param selectionCallback invoked when a discovery node is selected
1696
+ * @param monitoringCallbacks callbacks to be invoked with metrics from requests sent to a service
1697
+ * @param monitoringCallbacks.request
1698
+ * @param monitoringCallbacks.healthCheck
1699
+ * @param selectionRequestTimeout the amount of time (ms) an individual request should take before reselecting
1700
+ * @param selectionRequestRetries the number of retries to a given discovery node we make before reselecting
1701
+ * @param unhealthySlotDiffPlays the number of slots we would consider a discovery node unhealthy
1702
+ * @param unhealthyBlockDiff the number of missed blocks after which we would consider a discovery node unhealthy
1703
+ */
1704
+ declare class DiscoveryProvider {
1705
+ whitelist: Set<string> | undefined;
1706
+ blacklist: Set<string> | undefined;
1707
+ userStateManager: UserStateManager;
1708
+ ethContracts: EthContracts;
1709
+ web3Manager: Web3Manager | undefined;
1710
+ unhealthyBlockDiff: number;
1711
+ serviceSelector: DiscoveryProviderSelection;
1712
+ selectionRequestTimeout: number;
1713
+ selectionRequestRetries: number;
1714
+ unhealthySlotDiffPlays: number | undefined;
1715
+ request404Count: number;
1716
+ maxRequestsForTrue404: number;
1717
+ monitoringCallbacks: DiscoveryProviderSelection['monitoringCallbacks'] | undefined;
1718
+ discoveryProviderEndpoint: string | undefined;
1719
+ constructor({ whitelist, blacklist, userStateManager, ethContracts, web3Manager, reselectTimeout, selectionCallback, monitoringCallbacks, selectionRequestTimeout, selectionRequestRetries, unhealthySlotDiffPlays, unhealthyBlockDiff }: DiscoveryProviderConfig);
1720
+ init(): Promise<void>;
1721
+ setEndpoint(endpoint: string): void;
1722
+ setUnhealthyBlockDiff(updatedBlockDiff?: number): void;
1723
+ setUnhealthySlotDiffPlays(updatedDiff: number): void;
1724
+ /**
1725
+ * Get users with all relevant user data
1726
+ * can be filtered by providing an integer array of ids
1727
+ * @param limit
1728
+ * @param offset
1729
+ * @param idsArray
1730
+ * @param walletAddress
1731
+ * @param handle
1732
+ * @param isCreator null returns all users, true returns creators only, false returns users only
1733
+ * @returns {Object} {Array of User metadata Objects}
1734
+ * additional metadata fields on user objects:
1735
+ * {Integer} track_count - track count for given user
1736
+ * {Integer} playlist_count - playlist count for given user
1737
+ * {Integer} album_count - album count for given user
1738
+ * {Integer} follower_count - follower count for given user
1739
+ * {Integer} followee_count - followee count for given user
1740
+ * {Integer} repost_count - repost count for given user
1741
+ * {Integer} track_blocknumber - blocknumber of latest track for user
1742
+ * {Boolean} does_current_user_follow - does current user follow given user
1743
+ * {Array} followee_follows - followees of current user that follow given user
1744
+ * @example
1745
+ * await getUsers()
1746
+ * await getUsers(100, 0, [3,2,6]) - Invalid user ids will not be accepted
1747
+ */
1748
+ getUsers(limit?: number, offset?: number, idsArray?: string[], walletAddress?: string, handle?: string, isCreator?: null, minBlockNumber?: number): Promise<unknown>;
1749
+ /**
1750
+ * get tracks with all relevant track data
1751
+ * can be filtered by providing an integer array of ids
1752
+ * @param limit
1753
+ * @param offset
1754
+ * @param idsArray
1755
+ * @param targetUserId the owner of the tracks being queried
1756
+ * @param sort a string of form eg. blocknumber:asc,timestamp:desc describing a sort path
1757
+ * @param minBlockNumber The min block number
1758
+ * @param filterDeleted If set to true, filters the deleted tracks
1759
+ * @returns {Object} {Array of track metadata Objects}
1760
+ * additional metadata fields on track objects:
1761
+ * {Integer} repost_count - repost count for given track
1762
+ * {Integer} save_count - save count for given track
1763
+ * {Array} followee_reposts - followees of current user that have reposted given track
1764
+ * {Boolean} has_current_user_reposted - has current user reposted given track
1765
+ * {Boolean} has_current_user_saved - has current user saved given track
1766
+ * @example
1767
+ * await getTracks()
1768
+ * await getTracks(100, 0, [3,2,6]) - Invalid track ids will not be accepted
1769
+ */
1770
+ getTracks(limit?: number, offset?: number, idsArray?: string[], targetUserId?: string, sort?: boolean, minBlockNumber?: number, filterDeleted?: boolean, withUsers?: boolean): Promise<unknown>;
1771
+ /**
1772
+ * Gets a particular track by its creator's handle and the track's URL slug
1773
+ * @param handle the handle of the owner of the track
1774
+ * @param slug the URL slug of the track, generally the title urlized
1775
+ * @returns {Object} the requested track's metadata
1776
+ */
1777
+ getTracksByHandleAndSlug(handle: string, slug: string): Promise<unknown>;
1778
+ /**
1779
+ * @typedef {Object} getTracksIdentifier
1780
+ * @property {string} handle
1781
+ * @property {number} id
1782
+ * @property {string} url_title
1783
+ */
1784
+ /**
1785
+ * gets all tracks matching identifiers, including unlisted.
1786
+ *
1787
+ * @param identifiers
1788
+ * @returns {(Array)} track
1789
+ */
1790
+ getTracksIncludingUnlisted(identifiers: string[], withUsers?: boolean): Promise<unknown>;
1791
+ /**
1792
+ * Gets random tracks from trending tracks for a given genre.
1793
+ * If genre not given, will return trending tracks across all genres.
1794
+ * Excludes specified track ids.
1795
+ *
1796
+ * @param genre
1797
+ * @param limit
1798
+ * @param exclusionList
1799
+ * @param time
1800
+ * @returns {(Array)} track
1801
+ */
1802
+ getRandomTracks(genre: string, limit: number, exclusionList: number[], time: string): Promise<unknown>;
1803
+ /**
1804
+ * Gets all stems for a given trackId as an array of tracks.
1805
+ * @param trackId
1806
+ * @returns {(Array)} track
1807
+ */
1808
+ getStemsForTrack(trackId: number): Promise<unknown>;
1809
+ /**
1810
+ * Gets all the remixes of a given trackId as an array of tracks.
1811
+ * @param trackId
1812
+ * @param limit
1813
+ * @param offset
1814
+ * @returns {(Array)} track
1815
+ */
1816
+ getRemixesOfTrack(trackId: number, limit?: number, offset?: number): Promise<unknown>;
1817
+ /**
1818
+ * Gets the remix parents of a given trackId as an array of tracks.
1819
+ * @param limit
1820
+ * @param offset
1821
+ * @returns {(Array)} track
1822
+ */
1823
+ getRemixTrackParents(trackId: number, limit?: number, offset?: number): Promise<unknown>;
1824
+ /**
1825
+ * Gets tracks trending on Audius.
1826
+ * @param genre
1827
+ * @param timeFrame one of day, week, month, or year
1828
+ * @param idsArray track ids
1829
+ * @param limit
1830
+ * @param offset
1831
+ */
1832
+ getTrendingTracks(genre?: string, timeFrame?: string, idsArray?: number[], limit?: number, offset?: number, withUsers?: boolean): Promise<{
1833
+ listenCounts: Array<{
1834
+ trackId: number;
1835
+ listens: number;
1836
+ }>;
1837
+ } | null | undefined>;
1838
+ /**
1839
+ * get full playlist objects, including tracks, for passed in array of playlistId
1840
+ * @returns {Array} array of playlist objects
1841
+ * additional metadata fields on playlist objects:
1842
+ * {Integer} repost_count - repost count for given playlist
1843
+ * {Integer} save_count - save count for given playlist
1844
+ * {Boolean} has_current_user_reposted - has current user reposted given playlist
1845
+ * {Array} followee_reposts - followees of current user that have reposted given playlist
1846
+ * {Boolean} has_current_user_reposted - has current user reposted given playlist
1847
+ * {Boolean} has_current_user_saved - has current user saved given playlist
1848
+ */
1849
+ getPlaylists(limit?: number, offset?: number, idsArray?: null, targetUserId?: null, withUsers?: boolean): Promise<unknown>;
1850
+ /**
1851
+ * Return social feed for current user
1852
+ * @param filter - filter by "all", "original", or "repost"
1853
+ * @param limit - max # of items to return
1854
+ * @param offset - offset into list to return from (for pagination)
1855
+ * @returns {Object} {Array of track and playlist metadata objects}
1856
+ * additional metadata fields on track and playlist objects:
1857
+ * {String} activity_timestamp - timestamp of requested user's repost for given track or playlist,
1858
+ * used for sorting feed
1859
+ * {Integer} repost_count - repost count of given track/playlist
1860
+ * {Integer} save_count - save count of given track/playlist
1861
+ * {Boolean} has_current_user_reposted - has current user reposted given track/playlist
1862
+ * {Array} followee_reposts - followees of current user that have reposted given track/playlist
1863
+ */
1864
+ getSocialFeed(filter: string, limit?: number, offset?: number, withUsers?: boolean, tracksOnly?: boolean): Promise<unknown>;
1865
+ /**
1866
+ * Return repost feed for requested user
1867
+ * @param userId - requested user id
1868
+ * @param limit - max # of items to return (for pagination)
1869
+ * @param offset - offset into list to return from (for pagination)
1870
+ * @returns {Object} {Array of track and playlist metadata objects}
1871
+ * additional metadata fields on track and playlist objects:
1872
+ * {String} activity_timestamp - timestamp of requested user's repost for given track or playlist,
1873
+ * used for sorting feed
1874
+ * {Integer} repost_count - repost count of given track/playlist
1875
+ * {Integer} save_count - save count of given track/playlist
1876
+ * {Boolean} has_current_user_reposted - has current user reposted given track/playlist
1877
+ * {Array} followee_reposts - followees of current user that have reposted given track/playlist
1878
+ */
1879
+ getUserRepostFeed(userId: number, limit?: number, offset?: number, withUsers?: boolean): Promise<unknown>;
1880
+ /**
1881
+ * get intersection of users that follow followeeUserId and users that are followed by followerUserId
1882
+ * @param followeeUserId user that is followed
1883
+ * @param followerUserId user that follows
1884
+ * @example
1885
+ * getFollowIntersectionUsers(100, 0, 1, 1) - IDs must be valid
1886
+ */
1887
+ getFollowIntersectionUsers(limit: number | undefined, offset: number | undefined, followeeUserId: number, followerUserId: number): Promise<unknown>;
1888
+ /**
1889
+ * get intersection of users that have reposted repostTrackId and users that are followed by followerUserId
1890
+ * followee = user that is followed; follower = user that follows
1891
+ * @param repostTrackId track that is reposted
1892
+ * @param followerUserId user that reposted track
1893
+ * @example
1894
+ * getTrackRepostIntersectionUsers(100, 0, 1, 1) - IDs must be valid
1895
+ */
1896
+ getTrackRepostIntersectionUsers(limit: number | undefined, offset: number | undefined, repostTrackId: number, followerUserId: number): Promise<unknown>;
1897
+ /**
1898
+ * get intersection of users that have reposted repostPlaylistId and users that are followed by followerUserId
1899
+ * followee = user that is followed; follower = user that follows
1900
+ * @param repostPlaylistId playlist that is reposted
1901
+ * @param followerUserId user that reposted track
1902
+ * @example
1903
+ * getPlaylistRepostIntersectionUsers(100, 0, 1, 1) - IDs must be valid
1904
+ */
1905
+ getPlaylistRepostIntersectionUsers(limit: number | undefined, offset: number | undefined, repostPlaylistId: number, followerUserId: number): Promise<unknown>;
1906
+ /**
1907
+ * get users that follow followeeUserId, sorted by follower count descending
1908
+ * @param followeeUserId user that is followed
1909
+ * @return {Array} array of user objects with standard user metadata
1910
+ */
1911
+ getFollowersForUser(limit: number | undefined, offset: number | undefined, followeeUserId: number): Promise<unknown>;
1912
+ /**
1913
+ * get users that are followed by followerUserId, sorted by follower count descending
1914
+ * @param followerUserId user - i am the one who follows
1915
+ * @return {Array} array of user objects with standard user metadata
1916
+ */
1917
+ getFolloweesForUser(limit: number | undefined, offset: number | undefined, followerUserId: number): Promise<unknown>;
1918
+ /**
1919
+ * get users that reposted repostTrackId, sorted by follower count descending
1920
+ * @param repostTrackId
1921
+ * @return {Array} array of user objects
1922
+ * additional metadata fields on user objects:
1923
+ * {Integer} follower_count - follower count of given user
1924
+ * @example
1925
+ * getRepostersForTrack(100, 0, 1) - ID must be valid
1926
+ */
1927
+ getRepostersForTrack(limit: number | undefined, offset: number | undefined, repostTrackId: number): Promise<unknown>;
1928
+ /**
1929
+ * get users that reposted repostPlaylistId, sorted by follower count descending
1930
+ * @param repostPlaylistId
1931
+ * @return {Array} array of user objects
1932
+ * additional metadata fields on user objects:
1933
+ * {Integer} follower_count - follower count of given user
1934
+ * @example
1935
+ * getRepostersForPlaylist(100, 0, 1) - ID must be valid
1936
+ */
1937
+ getRepostersForPlaylist(limit: number | undefined, offset: number | undefined, repostPlaylistId: number): Promise<unknown>;
1938
+ /**
1939
+ * get users that saved saveTrackId, sorted by follower count descending
1940
+ * @param saveTrackId
1941
+ * @return {Array} array of user objects
1942
+ * additional metadata fields on user objects:
1943
+ * {Integer} follower_count - follower count of given user
1944
+ * @example
1945
+ * getSaversForTrack(100, 0, 1) - ID must be valid
1946
+ */
1947
+ getSaversForTrack(limit: number | undefined, offset: number | undefined, saveTrackId: number): Promise<unknown>;
1948
+ /**
1949
+ * get users that saved savePlaylistId, sorted by follower count descending
1950
+ * @param savePlaylistId
1951
+ * @return {Array} array of user objects
1952
+ * additional metadata fields on user objects:
1953
+ * {Integer} follower_count - follower count of given user
1954
+ * @example
1955
+ * getSaversForPlaylist(100, 0, 1) - ID must be valid
1956
+ */
1957
+ getSaversForPlaylist(limit: number | undefined, offset: number | undefined, savePlaylistId: number): Promise<unknown>;
1958
+ /**
1959
+ * get whether a JWT given by Audius Oauth popup is valid
1960
+ * @param token - JWT
1961
+ * @return {UserProfile | false} profile info of user attached to JWT payload if the JWT is valid, else false
1962
+ */
1963
+ verifyToken(token: string): Promise<UserProfile | false>;
1964
+ /**
1965
+ * Perform a full-text search. Returns tracks, users, playlists, albums
1966
+ * with optional user-specific results for each
1967
+ * - user, track, and playlist objects have all same data as returned from standalone endpoints
1968
+ * @param text search query
1969
+ * @param kind 'tracks', 'users', 'playlists', 'albums', 'all'
1970
+ * @param limit max # of items to return per list (for pagination)
1971
+ * @param offset offset into list to return from (for pagination)
1972
+ */
1973
+ searchFull(text: string, kind: string, limit?: number, offset?: number): Promise<unknown>;
1974
+ /**
1975
+ * Perform a lighter-weight full-text search. Returns tracks, users, playlists, albums
1976
+ * with optional user-specific results for each
1977
+ * - user, track, and playlist objects have core data, and track & playlist objects
1978
+ * also return user object
1979
+ * @param text search query
1980
+ * @param limit max # of items to return per list (for pagination)
1981
+ * @param offset offset into list to return from (for pagination)
1982
+ */
1983
+ searchAutocomplete(text: string, limit?: number, offset?: number): Promise<unknown>;
1984
+ /**
1985
+ * Perform a tags-only search. Returns tracks with required tag and users
1986
+ * that have used a tag greater than a specified number of times
1987
+ * @param text search query
1988
+ * @param userTagCount min # of times a user must have used a tag to be returned
1989
+ * @param kind 'tracks', 'users', 'playlists', 'albums', 'all'
1990
+ * @param limit max # of items to return per list (for pagination)
1991
+ * @param offset offset into list to return from (for pagination)
1992
+ */
1993
+ searchTags(text: string, userTagCount?: number, kind?: string, limit?: number, offset?: number): Promise<unknown>;
1994
+ /**
1995
+ * Return saved playlists for current user
1996
+ * NOTE in returned JSON, SaveType string one of track, playlist, album
1997
+ * @param limit - max # of items to return
1998
+ * @param offset - offset into list to return from (for pagination)
1999
+ */
2000
+ getSavedPlaylists(limit?: number, offset?: number, withUsers?: boolean): Promise<unknown>;
2001
+ /**
2002
+ * Return saved albums for current user
2003
+ * NOTE in returned JSON, SaveType string one of track, playlist, album
2004
+ * @param limit - max # of items to return
2005
+ * @param offset - offset into list to return from (for pagination)
2006
+ */
2007
+ getSavedAlbums(limit?: number, offset?: number, withUsers?: boolean): Promise<unknown>;
2008
+ /**
2009
+ * Return saved tracks for current user
2010
+ * NOTE in returned JSON, SaveType string one of track, playlist, album
2011
+ * @param limit - max # of items to return
2012
+ * @param offset - offset into list to return from (for pagination)
2013
+ */
2014
+ getSavedTracks(limit?: number, offset?: number, withUsers?: boolean): Promise<unknown>;
2015
+ /**
2016
+ * Return user collections (saved & uploaded) along w/ users for those collections
2017
+ */
2018
+ getUserAccount(wallet: string): Promise<CurrentUser | null | undefined>;
2019
+ getTopPlaylists(type: string, limit: number, mood: string, filter: string, withUsers?: boolean): Promise<unknown>;
2020
+ getTopFolloweeWindowed(type: string, window: string, limit: string, withUsers?: boolean): Promise<unknown>;
2021
+ getTopFolloweeSaves(type: string, limit: string, withUsers?: boolean): Promise<unknown>;
2022
+ getLatest(type: string): Promise<unknown>;
2023
+ getTopCreatorsByGenres(genres: string[], limit?: number, offset?: number, withUsers?: boolean): Promise<unknown>;
2024
+ getURSMContentNodes(ownerWallet?: string | null): Promise<unknown>;
2025
+ getNotifications(minBlockNumber: string, trackIds: string[], timeout: number): Promise<unknown>;
2026
+ getSolanaNotifications(minSlotNumber: number, timeout: number): Promise<unknown>;
2027
+ getTrackListenMilestones(timeout: number): Promise<unknown>;
2028
+ getChallengeAttestation(challengeId: string, encodedUserId: string, specifier: string, oracleAddress: string, discoveryProviderEndpoint: string): Promise<any>;
2029
+ getCreateSenderAttestation(senderEthAddress: string, discoveryProviderEndpoint: string): Promise<any>;
2030
+ getUndisbursedChallenges(limit?: number | null, offset?: number | null, completedBlockNumber?: string | null, encodedUserId?: number | null): Promise<{
2031
+ amount: number;
2032
+ }[]>;
2033
+ /**
2034
+ * Performs a single request, defined in the request, via axios, calling any
2035
+ * monitoring callbacks as needed.
2036
+ *
2037
+ * @param {{
2038
+ endpoint: string,
2039
+ urlParams: string,
2040
+ queryParams: object,
2041
+ method: string,
2042
+ headers: object,
2043
+ }} requestObj
2044
+ * @param {string} discoveryProviderEndpoint
2045
+ * @returns
2046
+ * @memberof DiscoveryProvider
2047
+ */
2048
+ _performRequestWithMonitoring(requestObj: RequestParams, discoveryProviderEndpoint: string): Promise<any>;
2049
+ /**
2050
+ * Gets how many blocks behind a discovery node is.
2051
+ * If this method throws (missing data in health check response),
2052
+ * return an unhealthy number of blocks
2053
+ * @param parsedResponse health check response object
2054
+ * @returns a number of blocks if behind or null if not behind
2055
+ */
2056
+ _getBlocksBehind(parsedResponse: {
2057
+ latest_indexed_block: number;
2058
+ latest_chain_block: number;
2059
+ }): Promise<number | null>;
2060
+ /**
2061
+ * Gets how many plays slots behind a discovery node is.
2062
+ * If this method throws (missing data in health check response),
2063
+ * return an unhealthy number of slots
2064
+ * @param parsedResponse health check response object
2065
+ * @returns a number of slots if behind or null if not behind
2066
+ */
2067
+ _getPlaysSlotsBehind(parsedResponse: {
2068
+ latest_indexed_slot_plays: number;
2069
+ latest_chain_slot_plays: number;
2070
+ }): Promise<number | null>;
2071
+ /**
2072
+ * Makes a request to a discovery node, reselecting if necessary
2073
+ * @param {{
2074
+ * endpoint: string
2075
+ * urlParams: object
2076
+ * queryParams: object
2077
+ * method: string
2078
+ * headers: object
2079
+ * }} {
2080
+ * endpoint: the base route
2081
+ * urlParams: string of URL params to be concatenated after base route
2082
+ * queryParams: URL query (search) params
2083
+ * method: string HTTP method
2084
+ * }
2085
+ * @param retry whether to retry on failure
2086
+ * @param attemptedRetries number of attempted retries (stops retrying at max)
2087
+ */
2088
+ _makeRequest<Response>(requestObj: Record<string, unknown>, retry?: boolean, attemptedRetries?: number): Promise<Response | undefined | null>;
2089
+ /**
2090
+ * Gets the healthy discovery provider endpoint used in creating the axios request later.
2091
+ * If the number of retries is over the max count for retires, clear the cache and reselect
2092
+ * another healthy discovery provider. Else, return the current discovery provider endpoint
2093
+ * @param attemptedRetries the number of attempted requests made to the current disc prov endpoint
2094
+ */
2095
+ getHealthyDiscoveryProviderEndpoint(attemptedRetries: number): Promise<string>;
2096
+ /**
2097
+ * Creates the discovery provider axios request object with necessary configs
2098
+ * @param requestObj
2099
+ * @param discoveryProviderEndpoint
2100
+ */
2101
+ _createDiscProvRequest(requestObj: RequestParams, discoveryProviderEndpoint: string): AxiosRequestConfig;
2102
+ }
2103
+
2104
+ declare type LoginSuccessCallback = (profile: UserProfile) => void;
2105
+ declare type LoginErrorCallback = (errorMessage: string) => void;
2106
+ declare type ButtonOptions = {
2107
+ size: 'small' | 'medium' | 'large';
2108
+ corners: 'default' | 'pill';
2109
+ customText: string;
2110
+ disableHoverGrow: boolean;
2111
+ fullWidth: boolean;
2112
+ };
2113
+ declare type OauthConfig = {
2114
+ appName?: string;
2115
+ discoveryProvider: DiscoveryProvider;
2116
+ };
2117
+ declare class Oauth {
2118
+ discoveryProvider: DiscoveryProvider;
2119
+ appName: string | null;
2120
+ activePopupWindow: null | Window;
2121
+ popupCheckInterval: NodeJS.Timer | null;
2122
+ loginSuccessCallback: LoginSuccessCallback | null;
2123
+ loginErrorCallback: LoginErrorCallback | null;
2124
+ constructor({ discoveryProvider, appName }: OauthConfig);
2125
+ init(successCallback: LoginSuccessCallback, errorCallback?: LoginErrorCallback): void;
2126
+ login(): void;
2127
+ renderButton(element: HTMLElement, options?: ButtonOptions): void;
2128
+ verifyToken(token: string): Promise<false | UserProfile>;
2129
+ _surfaceError(errorMessage: string): void;
2130
+ _clearPopupCheckInterval(): void;
2131
+ _receiveMessage(event: MessageEvent): Promise<void>;
2132
+ }
2133
+
2134
+ declare type Web3Config = {
2135
+ providers: string[];
2136
+ };
2137
+ declare type SdkConfig = {
2138
+ appName: string;
2139
+ discoveryNodeConfig?: DiscoveryProviderConfig;
2140
+ ethContractsConfig?: EthContractsConfig;
2141
+ ethWeb3Config?: EthWeb3Config;
2142
+ identityServiceConfig?: IdentityService;
2143
+ web3Config?: Web3Config;
2144
+ };
2145
+ /**
2146
+ * The Audius SDK
2147
+ */
2148
+ declare const sdk: (config?: SdkConfig | undefined) => Promise<{
2149
+ oauth: Oauth | undefined;
2150
+ discoveryNode: DiscoveryProvider;
2151
+ }>;
2152
+
2153
+ declare type SchemaConfig = {
2154
+ schema: {
2155
+ definitions: Record<string, {
2156
+ required: string[];
2157
+ properties: Record<string, {
2158
+ default: unknown;
2159
+ }>;
2160
+ } | {}>;
2161
+ };
2162
+ baseDefinition: string;
2163
+ validate?: (obj: Record<string, unknown>) => void;
2164
+ };
2165
+ declare type Schemas = {
2166
+ TrackSchema: SchemaConfig;
2167
+ UserSchema: SchemaConfig;
2168
+ };
2169
+
2170
+ declare type Metadata = {
2171
+ track_segments: unknown;
2172
+ download?: {
2173
+ is_downloadable: boolean;
2174
+ cid: string;
2175
+ };
2176
+ cover_art_sizes: string;
2177
+ };
2178
+ declare type ProgressCB = (loaded: number, total: number) => void;
2179
+ declare type MonitoringCallbacks = {
2180
+ request?: Function;
2181
+ healthCheck?: Function;
2182
+ };
2183
+ declare type ClockValueRequestConfig = {
2184
+ user: CurrentUser;
2185
+ endpoint: string;
2186
+ timeout?: number;
2187
+ };
2188
+ declare type FileUploadResponse = {
2189
+ data: {
2190
+ uuid: string;
2191
+ };
2192
+ error: Error;
2193
+ };
2194
+ declare class CreatorNode {
2195
+ /**
2196
+ * Pulls off the primary creator node from a creator node endpoint string.
2197
+ * @param endpoints user.creator_node_endpoint
2198
+ */
2199
+ static getPrimary(endpoints: string): string | undefined;
2200
+ /**
2201
+ * Pulls off the secondary creator nodes from a creator node endpoint string.
2202
+ * @param endpoints user.creator_node_endpoint
2203
+ */
2204
+ static getSecondaries(endpoints: string): string[];
2205
+ /**
2206
+ * Pulls the user's creator nodes out of the list
2207
+ * @param endpoints user.creator_node_endpoint
2208
+ */
2209
+ static getEndpoints(endpoints: string): string[];
2210
+ /**
2211
+ * Builds the creator_node_endpoint value off of a primary and secondaries list
2212
+ * @param primary the primary endpoint
2213
+ * @param secondaries a list of secondary endpoints
2214
+ */
2215
+ static buildEndpoint(primary: string, secondaries: string[]): string;
2216
+ /**
2217
+ * Pulls off the user's clock value from a creator node endpoint and the user's wallet address.
2218
+ * @param endpoint content node endpoint
2219
+ * @param wallet user wallet address
2220
+ * @param timeout max time alloted for clock request
2221
+ * @param params optional query string params
2222
+ */
2223
+ static getClockValue(endpoint: string, wallet: string, timeout: number, params?: Record<string, string>): Promise<any>;
2224
+ /**
2225
+ * Checks if a download is available from provided creator node endpoints
2226
+ * @param endpoints creator node endpoints
2227
+ * @param trackId
2228
+ */
2229
+ static checkIfDownloadAvailable(endpoints: string, trackId: number): Promise<any>;
2230
+ web3Manager: Web3Manager;
2231
+ creatorNodeEndpoint: string;
2232
+ isServer: boolean;
2233
+ userStateManager: UserStateManager;
2234
+ lazyConnect: boolean;
2235
+ schemas: Schemas;
2236
+ passList: Set<string> | null;
2237
+ blockList: Set<string> | null;
2238
+ monitoringCallbacks: MonitoringCallbacks;
2239
+ connected: boolean;
2240
+ connecting: boolean;
2241
+ authToken: null;
2242
+ maxBlockNumber: number;
2243
+ /**
2244
+ * Constructs a service class for a creator node
2245
+ * @param web3Manager
2246
+ * @param creatorNodeEndpoint fallback creator node endpoint (to be deprecated)
2247
+ * @param isServer
2248
+ * @param userStateManager singleton UserStateManager instance
2249
+ * @param lazyConnect whether or not to lazy connect (sign in) on load
2250
+ * @param schemas
2251
+ * @param passList whether or not to include only specified nodes (default null)
2252
+ * @param blockList whether or not to exclude any nodes (default null)
2253
+ * @param monitoringCallbacks callbacks to be invoked with metrics from requests sent to a service
2254
+ */
2255
+ constructor(web3Manager: Web3Manager, creatorNodeEndpoint: string, isServer: boolean, userStateManager: UserStateManager, lazyConnect: boolean, schemas: Schemas, passList?: Set<string> | null, blockList?: Set<string> | null, monitoringCallbacks?: MonitoringCallbacks);
2256
+ init(): Promise<void>;
2257
+ /** Establishes a connection to a content node endpoint */
2258
+ connect(): Promise<void>;
2259
+ /** Checks if connected, otherwise establishing a connection */
2260
+ ensureConnected(): Promise<void>;
2261
+ getEndpoint(): string;
2262
+ /**
2263
+ * Switch from one creatorNodeEndpoint to another including logging out from the old node, updating the endpoint and logging into new node */
2264
+ setEndpoint(creatorNodeEndpoint: string): Promise<void>;
2265
+ /** Clear all connection state in this class by deleting authToken and setting 'connected' = false */
2266
+ clearConnection(): void;
2267
+ /**
2268
+ * Uploads creator content to a creator node
2269
+ * @param metadata the creator metadata
2270
+ */
2271
+ uploadCreatorContent(metadata: Metadata, blockNumber?: null): Promise<any>;
2272
+ /**
2273
+ * Creates a creator on the creator node, associating user id with file content
2274
+ * @param audiusUserId returned by user creation on-blockchain
2275
+ * @param metadataFileUUID unique ID for metadata file
2276
+ * @param blockNumber
2277
+ */
2278
+ associateCreator(audiusUserId: number, metadataFileUUID: string, blockNumber: number): Promise<void>;
2279
+ /**
2280
+ * Uploads a track (including audio and image content) to a creator node
2281
+ * @param trackFile the audio content
2282
+ * @param coverArtFile the image content
2283
+ * @param metadata the metadata for the track
2284
+ * @param onProgress an optional on progress callback
2285
+ */
2286
+ uploadTrackContent(trackFile: File, coverArtFile: File, metadata: Metadata, onProgress?: ProgressCB): Promise<any>;
2287
+ /**
2288
+ * Uploads track metadata to a creator node
2289
+ * The metadata object must include a `track_id` field or a
2290
+ * source file must be provided (returned from uploading track content).
2291
+ * @param metadata
2292
+ * @param sourceFile
2293
+ */
2294
+ uploadTrackMetadata(metadata: Metadata, sourceFile: string): Promise<any>;
2295
+ /**
2296
+ * Creates a track on the content node, associating track id with file content
2297
+ * @param audiusTrackId returned by track creation on-blockchain
2298
+ * @param metadataFileUUID unique ID for metadata file
2299
+ * @param blockNumber
2300
+ * @param transcodedTrackUUID the CID for the transcoded master if this is a first-time upload
2301
+ */
2302
+ associateTrack(audiusTrackId: number, metadataFileUUID: string, blockNumber: number, transcodedTrackUUID: string): Promise<void>;
2303
+ /**
2304
+ * Uploads an image to the connected content node
2305
+ * @param file image to upload
2306
+ * @param onProgress called with loaded bytes and total bytes
2307
+ * @param timeoutMs timeout in ms axios request to upload file to CN will wait
2308
+ * @return response body
2309
+ */
2310
+ uploadImage(file: File, square: boolean | undefined, onProgress: ProgressCB, timeoutMs?: number | null): Promise<{
2311
+ uuid: string;
2312
+ }>;
2313
+ /**
2314
+ * @param file track to upload
2315
+ * @param onProgress called with loaded bytes and total bytes
2316
+ * @return response body
2317
+ */
2318
+ uploadTrackAudio(file: File, onProgress: ProgressCB): Promise<any>;
2319
+ handleAsyncTrackUpload(file: File, onProgress: ProgressCB): Promise<any>;
2320
+ pollProcessingStatus(uuid: string): Promise<any>;
2321
+ /**
2322
+ * Gets the task progress given the task type and uuid associated with the task
2323
+ * @param uuid the uuid of the track transcoding task
2324
+ * @returns the status, and the success or failed response if the task is complete
2325
+ */
2326
+ getTrackContentProcessingStatus(uuid: string): Promise<any>;
2327
+ /**
2328
+ * Given a particular endpoint to a creator node, check whether
2329
+ * this user has a sync in progress on that node.
2330
+ * @param endpoint
2331
+ * @param timeout ms
2332
+ */
2333
+ getSyncStatus(endpoint: string, timeout?: number | null): Promise<{
2334
+ status: any;
2335
+ userBlockNumber: number;
2336
+ trackBlockNumber: number;
2337
+ isBehind: boolean;
2338
+ isConfigured: boolean;
2339
+ }>;
2340
+ /**
2341
+ * Syncs a secondary creator node for a given user
2342
+ * @param secondary
2343
+ * @param primary specific primary to use
2344
+ * @param immediate whether or not this is a blocking request and handled right away
2345
+ * @param validate whether or not to validate the provided secondary is valid
2346
+ */
2347
+ syncSecondary(secondary: string, primary?: string, immediate?: boolean, validate?: boolean): Promise<axios.AxiosResponse<any> | undefined>;
2348
+ /**
2349
+ * Signs up a creator node user with a wallet address
2350
+ * @param walletAddress
2351
+ */
2352
+ _signupNodeUser(walletAddress: string): Promise<void>;
2353
+ /**
2354
+ * Logs user into cnode, if not already logged in.
2355
+ * Requests a challenge from cnode, sends signed challenge response to cn.
2356
+ * If successful, receive and set authToken locally.
2357
+ */
2358
+ _loginNodeUser(): Promise<void>;
2359
+ /** Calls logout on the content node. Needs an authToken for this since logout is an authenticated endpoint */
2360
+ _logoutNodeUser(): Promise<void>;
2361
+ /**
2362
+ * Gets and returns the clock values across the replica set for the wallet in userStateManager.
2363
+ * @returns Array of objects with the structure:
2364
+ *
2365
+ * {
2366
+ * type: 'primary' or 'secondary',
2367
+ * endpoint: <Content Node endpoint>,
2368
+ * clockValue: clock value (should be an integer) or null
2369
+ * }
2370
+ *
2371
+ * 'clockValue' may be null if the request to fetch the clock value fails
2372
+ */
2373
+ getClockValuesFromReplicaSet(): Promise<{
2374
+ type: string;
2375
+ endpoint: string;
2376
+ clockValue: any;
2377
+ }[] | undefined>;
2378
+ /**
2379
+ * Wrapper around getClockValue() to return either a proper or null clock value
2380
+ * @param {Object} param
2381
+ * @param {Object} param.user user metadata object from userStateManager
2382
+ * @param {string} param.endpoint the Content Node endpoint to check the clock value for
2383
+ * @param {number?} [param.timeout=1000] the max time allotted for a clock request; defaulted to 1000ms
2384
+ */
2385
+ _clockValueRequest({ user, endpoint, timeout }: ClockValueRequestConfig): Promise<{
2386
+ type: string;
2387
+ endpoint: string;
2388
+ clockValue: any;
2389
+ }>;
2390
+ /**
2391
+ * Makes an axios request to the connected creator node.
2392
+ * @param requiresConnection if set, the currently configured creator node
2393
+ * is connected to before the request is made.
2394
+ * @return response body
2395
+ */
2396
+ _makeRequest(axiosRequestObj: AxiosRequestConfig, requiresConnection?: boolean): Promise<any>;
2397
+ /**
2398
+ * Create headers and formData for file upload
2399
+ * @param file the file to upload
2400
+ * @returns headers and formData in an object
2401
+ */
2402
+ createFormDataAndUploadHeaders(file: File, extraFormDataOptions?: Record<string, unknown>): {
2403
+ headers: Record<string, string | null>;
2404
+ formData: FormData;
2405
+ };
2406
+ /**
2407
+ * Uploads a file to the connected creator node.
2408
+ * @param file
2409
+ * @param route route to handle upload (image_upload, track_upload, etc.)
2410
+ * @param onProgress called with loaded bytes and total bytes
2411
+ * @param extraFormDataOptions extra FormData fields passed to the upload
2412
+ * @param retries max number of attempts made for axios request to upload file to CN before erroring
2413
+ * @param timeoutMs timeout in ms axios request to upload file to CN will wait
2414
+ */
2415
+ _uploadFile(file: File, route: string, onProgress?: ProgressCB, extraFormDataOptions?: Record<string, unknown>, retries?: number, timeoutMs?: number | null): Promise<FileUploadResponse>;
2416
+ _handleErrorHelper(e: Error | AxiosError, requestUrl?: string, requestId?: string | null): Promise<void>;
2417
+ }
2418
+
2419
+ type Options = { skipRollover: boolean }
2420
+
2421
+ declare class SanityChecks {
2422
+ libs: any
2423
+ options: Options
2424
+
2425
+ constructor(libsInstance: any, options?: Options): void
2426
+ async run(creatorNodeWhitelist: string[] | null): Promise<void>
2427
+ }
2428
+
2429
+ declare const libs: any;
2430
+
2431
+ export { CreatorNode, SanityChecks, Utils, libs, sdk };