This repository has been archived by the owner on Sep 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
/
AccountsService.js
215 lines (185 loc) · 6.28 KB
/
AccountsService.js
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
import { PublicService } from '@makerdao/services-core';
import { map, omit, pick } from 'lodash/fp';
import invariant from 'invariant';
import {
privateKeyAccountFactory,
providerAccountFactory,
browserProviderAccountFactory
} from './accounts/factories';
import { setupEngine } from './accounts/setup';
import { AccountType } from '../utils/constants';
import assert from 'assert';
import debug from 'debug';
const log = debug('dai:AccountsService');
const sanitizeAccount = pick(['name', 'type', 'address']);
export default class AccountsService extends PublicService {
constructor(name = 'accounts') {
super(name, ['event']);
this._accounts = {};
this._accountFactories = {
privateKey: privateKeyAccountFactory,
provider: providerAccountFactory,
browser: browserProviderAccountFactory
};
}
async initialize(settings = {}) {
this._settings = omit('web3', settings);
const result = await setupEngine(settings);
this._engine = result.engine;
this._provider = result.provider;
}
async connect() {
const accountNames = Object.keys(this._settings);
for (const name of accountNames) {
await this.addAccount(name, this._settings[name]);
}
if (accountNames.length === 0) {
await this.addAccount('default', { type: AccountType.PROVIDER });
}
this._engine.start();
}
getProvider() {
return this._engine;
}
addAccountType(type, factory) {
invariant(
!this._accountFactories[type],
`Account type "${type}" is already defined`
);
this._accountFactories[type] = factory;
}
async addAccount(name, options = {}) {
if (name && typeof name !== 'string') {
options = name;
name = null;
}
const { type, autoSwitch, ...otherSettings } = options;
invariant(this._engine, 'engine must be set up before adding an account');
if (name && this._accounts[name]) {
throw new Error('An account with this name already exists.');
}
const factory = this._accountFactories[type];
invariant(factory, `no factory for type "${type}"`);
const accountData = await factory(otherSettings, this._provider);
// TODO allow this to silently fail only in situations where it's expected,
// e.g. when connecting to a read-only provider
if (!accountData.address) {
log(`Not adding account "${name}" (no address found)`);
return;
}
accountData.address = accountData.address.toLowerCase();
if (this._getAccountWithAddress(accountData.address)) {
throw new Error('An account with this address already exists.');
}
if (!name) name = accountData.address;
const account = {
name,
type,
autoSwitch: autoSwitch || false,
...accountData
};
this._accounts[name] = account;
if (!this._currentAccount || name === 'default') {
this.useAccount(name);
}
if (this.hasAccount()) {
this.get('event').emit('accounts/ADD', {
account: sanitizeAccount(account)
});
}
return account;
}
listAccounts() {
return map(sanitizeAccount, this._accounts);
}
useAccount(name) {
const account = this._accounts[name];
invariant(account, `No account found with name "${name}".`);
if (this._autoSwitchCheckHandle) clearInterval(this._autoSwitchCheckHandle);
if (account.type === AccountType.BROWSER) {
assert(
isAddressSelected(account.address),
'cannot use a browser account that is not currently selected'
);
// detect account change and automatically switch active account if
// autoSwitch flag set (useful if using a browser wallet like MetaMask)
// see: https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#ear-listening-for-selected-account-changes
if (account.autoSwitch) {
this._autoSwitchCheckHandle = setInterval(
this._autoSwitchCheckAccountChange(account.address),
500
);
}
}
if (this._currentAccount) {
this._engine.stop();
this._engine.removeProvider(this.currentWallet());
}
this._currentAccount = name;
// add the provider at index 0 so that it takes precedence over RpcSource
this._engine.addProvider(this.currentWallet(), 0);
this._engine.start();
if (this.hasAccount()) {
this.get('event').emit('accounts/CHANGE', {
account: this.currentAccount()
});
}
}
_autoSwitchCheckAccountChange(addr) {
return async () => {
const activeBrowserAddress = getSelectedAddress().toLowerCase();
if (activeBrowserAddress !== addr) {
if (!this._getAccountWithAddress(activeBrowserAddress)) {
await this.addAccount({
type: AccountType.BROWSER,
autoSwitch: true
});
}
this.useAccountWithAddress(activeBrowserAddress);
}
};
}
_getAccountWithAddress(addr) {
const accountObjects = Object.values(this._accounts);
return accountObjects.find(
e => e.address.toUpperCase() === addr.toUpperCase()
);
}
useAccountWithAddress(addr) {
const account = this._getAccountWithAddress(addr);
if (!account) throw new Error(`No account found with address ${addr}`);
this.useAccount(account.name);
}
hasAccount() {
return !!this._currentAccount;
}
hasNonProviderAccount() {
return (
this.hasAccount() && this.currentAccount().type != AccountType.PROVIDER
);
}
// we intentionally omit subprovider (implementation detail) and privateKey
// (sensitive info).
currentAccount() {
invariant(this.hasAccount(), 'No account is set up.');
return sanitizeAccount(this._accounts[this._currentAccount]);
}
currentAddress() {
invariant(this.hasAccount(), 'No account is set up.');
return this._accounts[this._currentAccount].address;
}
currentWallet() {
return this._accounts[this._currentAccount].subprovider;
}
}
function getSelectedAddress() {
return typeof window.ethereum !== 'undefined'
? window.ethereum.selectedAddress
: window.web3.eth.defaultAccount;
}
function isAddressSelected(address) {
// if using browser/MetaMask, we must use the currently selected account;
// however, it can be blank the first time the user connects their account.
const selectedAddress = getSelectedAddress();
return !selectedAddress || selectedAddress.toLowerCase() === address;
}