1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-27 04:46:10 +01:00
metamask-extension/app/scripts/controllers/address-book.js

80 lines
2.4 KiB
JavaScript
Raw Normal View History

2017-03-09 22:58:42 +01:00
const ObservableStore = require('obs-store')
const extend = require('xtend')
class AddressBookController {
2017-03-10 18:34:13 +01:00
// Controller in charge of managing the address book functionality from the
// recipients field on the send screen. Manages a history of all saved
// addresses and all currently owned addresses.
constructor (opts = {}, keyringController) {
2017-03-09 22:58:42 +01:00
const initState = extend({
addressBook: [],
}, opts.initState)
this.store = new ObservableStore(initState)
this.keyringController = keyringController
2017-03-09 22:58:42 +01:00
}
//
// PUBLIC METHODS
//
2017-03-10 18:34:13 +01:00
// Sets a new address book in store by accepting a new address and nickname.
2017-03-10 00:09:50 +01:00
setAddressBook (address, name) {
2017-03-10 18:34:13 +01:00
return this._addToAddressBook(address, name)
2017-03-09 22:58:42 +01:00
.then((addressBook) => {
this.store.updateState({
addressBook,
})
return Promise.resolve()
})
}
2017-03-10 18:34:13 +01:00
//
// PRIVATE METHODS
//
// Performs the logic to add the address and name into the address book. The
// pushed object is an object of two fields. Current behavior does not set an
// upper limit to the number of addresses.
_addToAddressBook (address, name) {
2017-04-27 06:05:45 +02:00
const addressBook = this._getAddressBook()
const identities = this._getIdentities()
2017-04-27 06:05:45 +02:00
const addressBookIndex = addressBook.findIndex((element) => { return element.address.toLowerCase() === address.toLowerCase() || element.name === name })
const identitiesIndex = Object.keys(identities).findIndex((element) => { return element.toLowerCase() === address.toLowerCase() })
// trigger this condition if we own this address--no need to overwrite.
if (identitiesIndex !== -1) {
return Promise.resolve(addressBook)
// trigger this condition if we've seen this address before--may need to update nickname.
} else if (addressBookIndex !== -1) {
addressBook.splice(addressBookIndex, 1)
} else if (addressBook.length > 15) {
addressBook.shift()
2017-03-09 22:58:42 +01:00
}
2017-03-09 22:58:42 +01:00
addressBook.push({
address: address,
2017-03-09 22:58:42 +01:00
name,
})
return Promise.resolve(addressBook)
}
2017-03-10 18:34:13 +01:00
// Internal method to get the address book. Current persistence behavior
// should not require that this method be called from the UI directly.
_getAddressBook () {
2017-03-09 22:58:42 +01:00
return this.store.getState().addressBook
}
// Retrieves identities from the keyring controller in order to avoid
// duplication
_getIdentities () {
return this.keyringController.memStore.getState().identities
}
2017-03-09 22:58:42 +01:00
}
module.exports = AddressBookController