-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathaddressBook.ts
More file actions
202 lines (165 loc) · 6.2 KB
/
Copy pathaddressBook.ts
File metadata and controls
202 lines (165 loc) · 6.2 KB
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
import { getAddress } from 'ethers'
import { IAccountsController } from '../../interfaces/account'
import { Contacts, IAddressBookController } from '../../interfaces/addressBook'
import { IEventEmitterRegistryController } from '../../interfaces/eventEmitter'
import { ISelectedAccountController } from '../../interfaces/selectedAccount'
import { IStorageController } from '../../interfaces/storage'
import EventEmitter from '../eventEmitter/eventEmitter'
/**
* AddressBook controller- responsible for managing contacts in the Address Book. There are two internal types of contacts in the Address Book:
* 1. Manually added contacts (stored in storage)- can be added, renamed and removed using this controller.
* 2. Contacts, generated on the fly from the accounts in the wallet (not stored in storage)- can be managed via other controllers and are read-only in this one.
* Both types of contacts are combined and returned as a single array of contacts.
*/
export class AddressBookController extends EventEmitter implements IAddressBookController {
// Manually added contact (stored in storage)
#manuallyAddedContacts: Contacts = []
#storage: IStorageController
initialLoadPromise?: Promise<void>
#accounts: IAccountsController
#selectedAccount: ISelectedAccountController
constructor(
storage: IStorageController,
accounts: IAccountsController,
selectedAccount: ISelectedAccountController,
eventEmitterRegistry?: IEventEmitterRegistryController
) {
super(eventEmitterRegistry)
this.#storage = storage
this.#accounts = accounts
this.#selectedAccount = selectedAccount
this.initialLoadPromise = this.#load().finally(() => {
this.initialLoadPromise = undefined
})
}
// Contacts, generated on the fly from the accounts in the wallet (not stored in storage)
get #walletAccountsSourcedContacts() {
return this.#accounts.accounts.map((account) => ({
name: account.preferences.label,
address: account.addr,
isWalletAccount: true
}))
}
get contacts() {
if (!this.#selectedAccount.account) return []
return [...this.#manuallyAddedContacts, ...this.#walletAccountsSourcedContacts].filter(
({ address }) => address !== this.#selectedAccount.account!.addr
)
}
async #load() {
await this.#accounts.initialLoadPromise
await this.#selectedAccount.initialLoadPromise
try {
this.#manuallyAddedContacts = await this.#storage.get('contacts', [])
this.emitUpdate()
} catch (error: any) {
this.emitError({
message:
'Something went wrong when loading the Address Book. Please try again or contact support if the problem persists.',
level: 'major',
error
})
}
}
#handleManuallyAddedContactsChange() {
this.emitUpdate()
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.#storage.set('contacts', this.#manuallyAddedContacts)
}
#findManuallyAddedContactWithAddress(address: string) {
return this.#manuallyAddedContacts.find(
(contact) => contact.address.toLowerCase() === address.toLowerCase()
)
}
#findContactWithAddress(address: string) {
return !this.contacts.some((contact) => contact.address.toLowerCase() === address.toLowerCase())
}
#getChecksummedAddress(address: string) {
try {
return getAddress(address)
} catch {
this.emitError({
message: 'Invalid address',
level: 'minor',
error: new Error('Address Book: invalid address')
})
return ''
}
}
async addContact(name: string, address: string) {
await this.initialLoadPromise
const checksummedAddress = this.#getChecksummedAddress(address)
const trimmedName = name.trim()
if (!this.#findContactWithAddress(checksummedAddress)) {
this.emitError({
message: 'Contact with this address already exists in the Address Book',
level: 'minor',
error: new Error(
'Address Book: contact with this address already exists in the Address Book'
)
})
return
}
const newContact = {
name: trimmedName,
address: checksummedAddress,
createdAt: Date.now(),
updatedAt: Date.now()
}
this.debugLog('Adding a new contact', newContact)
this.#manuallyAddedContacts.push(newContact)
this.#handleManuallyAddedContactsChange()
}
async renameManuallyAddedContact(address: string, newName: string) {
await this.initialLoadPromise
const checksummedAddress = this.#getChecksummedAddress(address)
const trimmedNewName = newName.trim()
if (!this.#findManuallyAddedContactWithAddress(checksummedAddress)) {
this.emitError({
message: "Can't rename contact that doesn't exist in the Address Book",
level: 'minor',
error: new Error(
"Address Book: can't rename contact that doesn't exist in the Address Book"
)
})
return
}
this.#manuallyAddedContacts = this.#manuallyAddedContacts.map((contact) => {
if (contact.address.toLowerCase() === address.toLowerCase()) {
this.debugLog('Renaming manually added contact', () => ({
oldName: contact.name,
newName: trimmedNewName,
address: contact.address
}))
return { ...contact, name: trimmedNewName, updatedAt: Date.now() }
}
return contact
})
this.#handleManuallyAddedContactsChange()
}
async removeManuallyAddedContact(address: string) {
await this.initialLoadPromise
const checksummedAddress = this.#getChecksummedAddress(address)
if (!this.#findManuallyAddedContactWithAddress(checksummedAddress)) {
this.emitError({
message: "Can't remove contact that doesn't exist in the Address Book",
level: 'minor',
error: new Error(
"Address Book: can't remove contact that doesn't exist in the Address Book"
)
})
return
}
this.debugLog('Removing manually added contact', checksummedAddress)
this.#manuallyAddedContacts = this.#manuallyAddedContacts.filter(
(contact) => contact.address.toLowerCase() !== address.toLowerCase()
)
this.#handleManuallyAddedContactsChange()
}
toJSON() {
return {
...this,
contacts: this.contacts
}
}
}