generated from PolymeshAssociation/typescript-boilerplate
/
index.ts
220 lines (183 loc) · 5.63 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import { ApiPromise, Keyring } from '@polkadot/api';
import { IKeyringPair } from '@polkadot/types/types';
import stringToU8a from '@polkadot/util/string/toU8a';
import BigNumber from 'bignumber.js';
import { IdentityId } from 'polymesh-types/types';
import { Identity } from '~/api/entities';
import { PolymeshError } from '~/base';
import { ErrorCode } from '~/types';
import { balanceToBigNumber, identityIdToString, stringToAccountKey } from '~/utils';
interface SignerData {
currentPair: IKeyringPair;
did: IdentityId;
}
interface ConstructorParams {
polymeshApi: ApiPromise;
keyring: Keyring;
pair?: SignerData;
}
interface AccountData {
address: string;
name?: string;
}
/**
* Context in which the SDK is being used
*
* - Holds the current low level API
* - Holds the current keyring pair
* - Holds the current Identity
*/
export class Context {
private keyring: Keyring;
public polymeshApi: ApiPromise;
public currentPair?: IKeyringPair;
private currentIdentity?: Identity;
/**
* @hidden
*/
private constructor(params: ConstructorParams) {
const { polymeshApi, keyring, pair } = params;
this.polymeshApi = new Proxy(polymeshApi, {
get: (target, prop: keyof ApiPromise): ApiPromise[keyof ApiPromise] => {
if (prop === 'tx' && !this.currentPair) {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'Cannot perform transactions without an active account',
});
}
return target[prop];
},
});
this.keyring = keyring;
if (pair) {
this.currentPair = pair.currentPair;
this.currentIdentity = new Identity({ did: pair.did.toString() }, this);
}
}
static async create(params: { polymeshApi: ApiPromise; seed: string }): Promise<Context>;
static async create(params: { polymeshApi: ApiPromise; keyring: Keyring }): Promise<Context>;
static async create(params: { polymeshApi: ApiPromise; uri: string }): Promise<Context>;
static async create(params: { polymeshApi: ApiPromise }): Promise<Context>;
/**
* Create the Context instance
*/
static async create(params: {
polymeshApi: ApiPromise;
seed?: string;
keyring?: Keyring;
uri?: string;
}): Promise<Context> {
const { polymeshApi, seed, keyring: passedKeyring, uri } = params;
let keyring = new Keyring({ type: 'sr25519' });
let currentPair: IKeyringPair | undefined;
if (passedKeyring) {
keyring = passedKeyring;
currentPair = keyring.getPairs()[0];
} else if (seed) {
if (seed.length !== 32) {
throw new PolymeshError({
code: ErrorCode.ValidationError,
message: 'Seed must be 32 characters in length',
});
}
currentPair = keyring.addFromSeed(stringToU8a(seed));
} else if (uri) {
currentPair = keyring.addFromUri(uri);
}
if (currentPair) {
try {
const identityIds = await polymeshApi.query.identity.keyToIdentityIds(
currentPair.publicKey
);
const did = identityIds.unwrap().asUnique;
return new Context({ polymeshApi, keyring, pair: { currentPair, did } });
} catch (err) {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'There is no Identity associated to this account',
});
}
}
return new Context({ polymeshApi, keyring });
}
/**
* Retrieve a list of addresses associated with the account
*/
public getAccounts(): Array<AccountData> {
const { keyring } = this;
return keyring.getPairs().map(({ address, meta }) => {
return { address, name: meta.name };
});
}
/**
* Set a pair as the current account keyring pair
*/
public async setPair(address: string): Promise<void> {
const {
keyring,
polymeshApi: {
query: { identity },
},
} = this;
let newCurrentPair;
let identityIds;
let did;
try {
newCurrentPair = keyring.getPair(address);
} catch (e) {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'The address is not present in the keyring set',
});
}
try {
identityIds = await identity.keyToIdentityIds(
stringToAccountKey(newCurrentPair.address, this)
);
did = identityIds.unwrap().asUnique;
} catch (e) {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'There is no Identity associated to this account',
});
}
this.currentPair = newCurrentPair;
this.currentIdentity = new Identity({ did: identityIdToString(did) }, this);
}
/**
* Retrieve the account level POLYX balance
*/
public async accountBalance(accountId?: string): Promise<BigNumber> {
const { currentPair } = this;
let address: string;
if (accountId) {
address = accountId;
} else if (currentPair) {
address = currentPair.address;
} else {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'There is no account associated with the SDK',
});
}
const {
data: { free },
} = await this.polymeshApi.query.system.account(address);
return balanceToBigNumber(free);
}
/**
* Retrieve current Identity
*
* @throws if there is no identity associated to the current account (or there is no current account associated to the SDK instance)
*/
public getCurrentIdentity(): Identity {
const { currentIdentity } = this;
if (!currentIdentity) {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'The current account does not have an associated identity',
});
}
return currentIdentity;
}
}