generated from PolymeshAssociation/typescript-boilerplate
/
Polymesh.ts
92 lines (79 loc) · 2.37 KB
/
Polymesh.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { ApiPromise, Keyring, WsProvider } from '@polymathnetwork/polkadot/api';
import { BigNumber } from 'bignumber.js';
import { Context, PolymeshError } from '~/base';
import { ErrorCode } from '~/types';
/**
* Main entry point of the Polymesh SDK
*/
export class Polymesh {
private context: Context = {} as Context;
/**
* @hidden
*/
private constructor(context: Context) {
this.context = context;
}
static async connect(params: { nodeUrl: string; accountSeed: string }): Promise<Polymesh>;
static async connect(params: { nodeUrl: string; keyring: Keyring }): Promise<Polymesh>;
static async connect(params: { nodeUrl: string; accountUri: string }): Promise<Polymesh>;
static async connect(params: { nodeUrl: string }): Promise<Polymesh>;
/**
* Create the instance and connect to the Polymesh node
*/
static async connect(params: {
nodeUrl: string;
accountSeed?: string;
keyring?: Keyring;
accountUri?: string;
}): Promise<Polymesh> {
const { nodeUrl, accountSeed, keyring, accountUri } = params;
let polymeshApi: ApiPromise;
try {
polymeshApi = await ApiPromise.create({
provider: new WsProvider(nodeUrl),
});
let context: Context = {} as Context;
if (accountSeed) {
context = await Context.create({
polymeshApi,
seed: accountSeed,
});
} else if (keyring) {
context = await Context.create({
polymeshApi,
keyring,
});
} else if (accountUri) {
context = await Context.create({
polymeshApi,
uri: accountUri,
});
} else {
context = await Context.create({
polymeshApi,
});
}
return new Polymesh(context);
} catch (e) {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: `Error while connecting to "${nodeUrl}": "${e.message}"`,
});
}
}
/**
* Get the POLY balance of the current account
*/
public getPolyBalance = async (): Promise<BigNumber> => {
const { currentIdentity } = this.context;
if (currentIdentity) {
const balance = await currentIdentity.getIdentityBalance();
return balance;
} else {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'The current account does not have an associated identity',
});
}
};
}