generated from PolymeshAssociation/typescript-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 11
/
CurrentAccount.ts
96 lines (80 loc) · 2.8 KB
/
CurrentAccount.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
import { difference, differenceBy, differenceWith, isEqual } from 'lodash';
import { Account, CurrentIdentity } from '~/internal';
import { Permissions } from '~/types';
import { portfolioToPortfolioId, signerToString } from '~/utils/conversion';
/**
* Represents the current account that is bound to the SDK instance
*/
export class CurrentAccount extends Account {
/**
* Retrieve the current Identity (null if there is none)
*/
public async getIdentity(): Promise<CurrentIdentity | null> {
const identity = await super.getIdentity();
return identity && new CurrentIdentity({ did: identity.did }, this.context);
}
/**
* Retrieve the Permissions this Signer has as a Signing Key for its corresponding Identity
*/
public async getPermissions(): Promise<Permissions> {
const { context, address } = this;
const currentIdentity = await context.getCurrentIdentity();
const [primaryKey, secondaryKeys] = await Promise.all([
currentIdentity.getPrimaryKey(),
currentIdentity.getSecondaryKeys(),
]);
if (address === primaryKey) {
return {
tokens: null,
transactions: null,
portfolios: null,
};
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const key = secondaryKeys.find(({ signer }) => address === signerToString(signer))!;
return key.permissions;
}
/**
* Check if this Account possesses certain Permissions for its corresponding Identity
*/
public async hasPermissions(permissions: Permissions): Promise<boolean> {
const { tokens, transactions, portfolios } = permissions;
const {
tokens: currentTokens,
transactions: currentTransactions,
portfolios: currentPortfolios,
} = await this.getPermissions();
let hasTokens;
if (currentTokens === null) {
hasTokens = true;
} else if (tokens === null) {
hasTokens = false;
} else {
hasTokens = tokens.length === 0 || !differenceBy(tokens, currentTokens, 'ticker').length;
}
let hasTransactions;
if (currentTransactions === null) {
hasTransactions = true;
} else if (transactions === null) {
hasTransactions = false;
} else {
hasTransactions =
transactions.length === 0 || !difference(transactions, currentTransactions).length;
}
let hasPortfolios;
if (currentPortfolios === null) {
hasPortfolios = true;
} else if (portfolios === null) {
hasPortfolios = false;
} else {
hasPortfolios =
portfolios.length === 0 ||
!differenceWith(portfolios, currentPortfolios, (a, b) => {
const aId = portfolioToPortfolioId(a);
const bId = portfolioToPortfolioId(b);
return isEqual(aId, bId);
}).length;
}
return hasTokens && hasTransactions && hasPortfolios;
}
}