aboutsummaryrefslogtreecommitdiffstats
path: root/app
diff options
context:
space:
mode:
authorkumavis <kumavis@users.noreply.github.com>2018-02-28 03:25:29 +0800
committerGitHub <noreply@github.com>2018-02-28 03:25:29 +0800
commit3fefccd37219c9b4b513fc8d929723e07022b9c4 (patch)
tree22865ecd672570a6162ac3c9402ec9d63ad3f7ef /app
parent6a7ea00cd34f83b257f6b4280a5f4e20aa5d34ee (diff)
parentced62ac551a095c8f94f550f0c01a9d4fd04ce5b (diff)
downloadtangerine-wallet-browser-3fefccd37219c9b4b513fc8d929723e07022b9c4.tar.gz
tangerine-wallet-browser-3fefccd37219c9b4b513fc8d929723e07022b9c4.tar.zst
tangerine-wallet-browser-3fefccd37219c9b4b513fc8d929723e07022b9c4.zip
Merge branch 'master' into mascara-deploy
Diffstat (limited to 'app')
-rw-r--r--app/_locales/ko/messages.json10
-rw-r--r--app/currencies.json1
-rw-r--r--app/fonts/DIN Next/DIN Next W01 Bold.otfbin0 -> 106032 bytes
-rw-r--r--app/fonts/DIN Next/DIN Next W01 Regular.otfbin0 -> 106580 bytes
-rw-r--r--app/fonts/DIN Next/DIN Next W10 Black.otfbin0 -> 105972 bytes
-rw-r--r--app/fonts/DIN Next/DIN Next W10 Italic.otfbin0 -> 115984 bytes
-rw-r--r--app/fonts/DIN Next/DIN Next W10 Light.otfbin0 -> 108672 bytes
-rw-r--r--app/fonts/DIN Next/DIN Next W10 Medium.otfbin0 -> 105684 bytes
-rw-r--r--app/fonts/DIN_OT/DINOT-2.otfbin0 -> 44144 bytes
-rw-r--r--app/fonts/DIN_OT/DINOT-Bold 2.otfbin0 -> 45564 bytes
-rw-r--r--app/fonts/DIN_OT/DINOT-BoldItalic.otfbin0 -> 49684 bytes
-rw-r--r--app/fonts/DIN_OT/DINOT-Italic 2.otfbin0 -> 47956 bytes
-rw-r--r--app/fonts/DIN_OT/DINOT-Medium 2.otfbin0 -> 44652 bytes
-rw-r--r--app/fonts/DIN_OT/DINOT-MediumItalic 2.otfbin0 -> 47732 bytes
-rwxr-xr-xapp/fonts/Lato/Lato-Black.ttfbin0 -> 114588 bytes
-rwxr-xr-xapp/fonts/Lato/Lato-BlackItalic.ttfbin0 -> 111616 bytes
-rwxr-xr-xapp/fonts/Lato/Lato-Bold.ttfbin0 -> 121788 bytes
-rwxr-xr-xapp/fonts/Lato/Lato-BoldItalic.ttfbin0 -> 120312 bytes
-rwxr-xr-xapp/fonts/Lato/Lato-Hairline.ttfbin0 -> 115316 bytes
-rwxr-xr-xapp/fonts/Lato/Lato-HairlineItalic.ttfbin0 -> 91460 bytes
-rwxr-xr-xapp/fonts/Lato/Lato-Italic.ttfbin0 -> 118352 bytes
-rwxr-xr-xapp/fonts/Lato/Lato-Light.ttfbin0 -> 122524 bytes
-rwxr-xr-xapp/fonts/Lato/Lato-LightItalic.ttfbin0 -> 91600 bytes
-rwxr-xr-xapp/fonts/Lato/Lato-Regular.ttfbin0 -> 120196 bytes
-rwxr-xr-xapp/fonts/Lato/OFL.txt93
-rw-r--r--app/fonts/Roboto/Roboto-Black.ttfbin0 -> 142472 bytes
-rw-r--r--app/fonts/Roboto/Roboto-BlackItalic.ttfbin0 -> 149644 bytes
-rw-r--r--app/fonts/Roboto/Roboto-Bold.ttfbin0 -> 135820 bytes
-rw-r--r--app/fonts/Roboto/Roboto-BoldItalic.ttfbin0 -> 144700 bytes
-rw-r--r--app/fonts/Roboto/Roboto-Italic.ttfbin0 -> 148540 bytes
-rw-r--r--app/fonts/Roboto/Roboto-Light.ttfbin0 -> 140276 bytes
-rw-r--r--app/fonts/Roboto/Roboto-LightItalic.ttfbin0 -> 145932 bytes
-rw-r--r--app/fonts/Roboto/Roboto-Medium.ttfbin0 -> 137308 bytes
-rw-r--r--app/fonts/Roboto/Roboto-MediumItalic.ttfbin0 -> 147876 bytes
-rw-r--r--app/fonts/Roboto/Roboto-Regular.ttfbin0 -> 145348 bytes
-rw-r--r--app/fonts/Roboto/Roboto-Thin.ttfbin0 -> 130044 bytes
-rw-r--r--app/fonts/Roboto/Roboto-ThinItalic.ttfbin0 -> 132376 bytes
-rw-r--r--app/fonts/Roboto/RobotoCondensed-Bold.ttfbin0 -> 141796 bytes
-rw-r--r--app/fonts/Roboto/RobotoCondensed-BoldItalic.ttfbin0 -> 145256 bytes
-rw-r--r--app/fonts/Roboto/RobotoCondensed-Italic.ttfbin0 -> 144404 bytes
-rw-r--r--app/fonts/Roboto/RobotoCondensed-Light.ttfbin0 -> 141384 bytes
-rw-r--r--app/fonts/Roboto/RobotoCondensed-LightItalic.ttfbin0 -> 145104 bytes
-rw-r--r--app/fonts/Roboto/RobotoCondensed-Regular.ttfbin0 -> 140396 bytes
-rw-r--r--app/home.html12
-rw-r--r--app/images/.DS_Storebin6148 -> 0 bytes
-rw-r--r--app/images/caret-right.svg76
-rw-r--r--app/images/check-white.svg14
-rw-r--r--app/images/coinbase logo.pngbin0 -> 9775 bytes
-rw-r--r--app/images/eth_logo.svg11
-rw-r--r--app/images/import-account.svg18
-rw-r--r--app/images/info-logo.pngbin0 -> 32567 bytes
-rw-r--r--app/images/metamask-fox.svg128
-rw-r--r--app/images/mm-bolt.svg11
-rw-r--r--app/images/mm-info-icon.svg11
-rw-r--r--app/images/open.svg15
-rw-r--r--app/images/plus-btn-white.svg17
-rw-r--r--app/images/popout.svg21
-rw-r--r--app/images/settings.svg46
-rw-r--r--app/images/shapeshift logo.pngbin0 -> 17537 bytes
-rw-r--r--app/manifest.json6
-rw-r--r--app/notification.html4
-rw-r--r--app/popup.html7
-rw-r--r--app/scripts/account-import-strategies/index.js2
-rw-r--r--app/scripts/background.js108
-rw-r--r--app/scripts/config.js38
-rw-r--r--app/scripts/contentscript.js96
-rw-r--r--app/scripts/controllers/address-book.js8
-rw-r--r--app/scripts/controllers/balance.js80
-rw-r--r--app/scripts/controllers/blacklist.js60
-rw-r--r--app/scripts/controllers/computed-balances.js77
-rw-r--r--app/scripts/controllers/currency.js14
-rw-r--r--app/scripts/controllers/infura.js43
-rw-r--r--app/scripts/controllers/network.js214
-rw-r--r--app/scripts/controllers/preferences.js80
-rw-r--r--app/scripts/controllers/recent-blocks.js110
-rw-r--r--app/scripts/controllers/transactions.js325
-rw-r--r--app/scripts/first-time-state.js12
-rw-r--r--app/scripts/inpage.js37
-rw-r--r--app/scripts/keyring-controller.js594
-rw-r--r--app/scripts/lib/account-tracker.js125
-rw-r--r--app/scripts/lib/auto-faucet.js20
-rw-r--r--app/scripts/lib/auto-reload.js76
-rw-r--r--app/scripts/lib/buy-eth-url.js8
-rw-r--r--app/scripts/lib/config-manager.js89
-rw-r--r--app/scripts/lib/createLoggerMiddleware.js15
-rw-r--r--app/scripts/lib/createOriginMiddleware.js9
-rw-r--r--app/scripts/lib/createProviderMiddleware.js12
-rw-r--r--app/scripts/lib/environment-type.js10
-rw-r--r--app/scripts/lib/eth-store.js136
-rw-r--r--app/scripts/lib/events-proxy.js31
-rw-r--r--app/scripts/lib/inpage-provider.js92
-rw-r--r--app/scripts/lib/is-popup-or-notification.js5
-rw-r--r--app/scripts/lib/message-manager.js4
-rw-r--r--app/scripts/lib/migrator/index.js43
-rw-r--r--app/scripts/lib/nodeify.js34
-rw-r--r--app/scripts/lib/nonce-tracker.js149
-rw-r--r--app/scripts/lib/notification-manager.js7
-rw-r--r--app/scripts/lib/obj-multiplex.js44
-rw-r--r--app/scripts/lib/pending-balance-calculator.js51
-rw-r--r--app/scripts/lib/pending-tx-tracker.js189
-rw-r--r--app/scripts/lib/personal-message-manager.js4
-rw-r--r--app/scripts/lib/port-stream.js16
-rw-r--r--app/scripts/lib/setupMetamaskMeshMetrics.js9
-rw-r--r--app/scripts/lib/stream-utils.js24
-rw-r--r--app/scripts/lib/tx-gas-utils.js125
-rw-r--r--app/scripts/lib/tx-state-history-helper.js41
-rw-r--r--app/scripts/lib/tx-state-manager.js266
-rw-r--r--app/scripts/lib/tx-utils.js136
-rw-r--r--app/scripts/lib/typed-message-manager.js123
-rw-r--r--app/scripts/lib/util.js44
-rw-r--r--app/scripts/metamask-controller.js652
-rw-r--r--app/scripts/migrations/002.js2
-rw-r--r--app/scripts/migrations/003.js2
-rw-r--r--app/scripts/migrations/004.js2
-rw-r--r--app/scripts/migrations/005.js2
-rw-r--r--app/scripts/migrations/006.js2
-rw-r--r--app/scripts/migrations/007.js2
-rw-r--r--app/scripts/migrations/008.js2
-rw-r--r--app/scripts/migrations/009.js2
-rw-r--r--app/scripts/migrations/010.js2
-rw-r--r--app/scripts/migrations/011.js2
-rw-r--r--app/scripts/migrations/012.js2
-rw-r--r--app/scripts/migrations/013.js34
-rw-r--r--app/scripts/migrations/014.js34
-rw-r--r--app/scripts/migrations/015.js38
-rw-r--r--app/scripts/migrations/016.js41
-rw-r--r--app/scripts/migrations/017.js40
-rw-r--r--app/scripts/migrations/018.js52
-rw-r--r--app/scripts/migrations/019.js83
-rw-r--r--app/scripts/migrations/020.js41
-rw-r--r--app/scripts/migrations/021.js34
-rw-r--r--app/scripts/migrations/_multi-keyring.js13
-rw-r--r--app/scripts/migrations/index.js9
-rw-r--r--app/scripts/notice-controller.js44
-rw-r--r--app/scripts/platforms/extension.js15
-rw-r--r--app/scripts/popup-core.js8
-rw-r--r--app/scripts/popup.js36
-rw-r--r--app/scripts/setupRaven.js26
-rw-r--r--app/scripts/transaction-manager.js404
-rw-r--r--app/scripts/vendor/raven.min.js3
140 files changed, 4017 insertions, 1948 deletions
diff --git a/app/_locales/ko/messages.json b/app/_locales/ko/messages.json
new file mode 100644
index 000000000..c58af4b80
--- /dev/null
+++ b/app/_locales/ko/messages.json
@@ -0,0 +1,10 @@
+{
+ "appName": {
+ "message": "MetaMask",
+ "description": "The name of the application"
+ },
+ "appDescription": {
+ "message": "이더리움 계좌 관리",
+ "description": "The description of the application"
+ }
+}
diff --git a/app/currencies.json b/app/currencies.json
deleted file mode 100644
index 07889798b..000000000
--- a/app/currencies.json
+++ /dev/null
@@ -1 +0,0 @@
-{"rows":[{"code":"007","name":"007","statuses":["primary"]},{"code":"1337","name":"1337","statuses":["primary"]},{"code":"1CR","name":"1CR","statuses":["primary"]},{"code":"256","name":"256","statuses":["primary"]},{"code":"2FLAV","name":"2FLAV","statuses":["primary"]},{"code":"2GIVE","name":"2GIVE","statuses":["primary"]},{"code":"404","name":"404","statuses":["primary"]},{"code":"611","name":"611","statuses":["primary"]},{"code":"888","name":"888","statuses":["primary"]},{"code":"8BIT","name":"8Bit","statuses":["primary"]},{"code":"ACLR","name":"ACLR","statuses":["primary"]},{"code":"ACOIN","name":"ACOIN","statuses":["primary"]},{"code":"ACP","name":"ACP","statuses":["primary"]},{"code":"ADC","name":"ADC","statuses":["primary"]},{"code":"ADZ","name":"Adzcoin","statuses":["primary"]},{"code":"AEC","name":"AEC","statuses":["primary"]},{"code":"AEON","name":"Aeon","statuses":["primary"]},{"code":"AGRS","name":"Agoras Tokens","statuses":["primary"]},{"code":"AIB","name":"AIB","statuses":["primary"]},{"code":"ADN","name":"Aiden","statuses":["primary"]},{"code":"AIR","name":"AIR","statuses":["primary"]},{"code":"ALC","name":"ALC","statuses":["primary"]},{"code":"ALTC","name":"ALTC","statuses":["primary"]},{"code":"AM","name":"AM","statuses":["primary"]},{"code":"AMBER","name":"AMBER","statuses":["primary"]},{"code":"AMS","name":"AMS","statuses":["primary"]},{"code":"ANAL","name":"ANAL","statuses":["primary"]},{"code":"AND","name":"AND","statuses":["primary"]},{"code":"ANI","name":"ANI","statuses":["primary"]},{"code":"ANC","name":"Anoncoin","statuses":["primary"]},{"code":"ANTI","name":"AntiBitcoin","statuses":["primary"]},{"code":"APEX","name":"APEX","statuses":["primary"]},{"code":"APC","name":"Applecoin","statuses":["primary"]},{"code":"APT","name":"APT","statuses":["primary"]},{"code":"AR2","name":"AR2","statuses":["primary"]},{"code":"ARB","name":"ARB","statuses":["primary"]},{"code":"ARC","name":"ARC","statuses":["primary"]},{"code":"ARCH","name":"ARCH","statuses":["primary"]},{"code":"ABY","name":"ArtByte","statuses":["primary"]},{"code":"ARTC","name":"ARTC","statuses":["primary"]},{"code":"ADCN","name":"Asiadigicoin","statuses":["primary"]},{"code":"ATEN","name":"ATEN","statuses":["primary"]},{"code":"REP","name":"Augur","statuses":["primary"]},{"code":"AUR","name":"Auroracoin","statuses":["primary"]},{"code":"AUD","name":"Australian Dollar","statuses":["secondary"]},{"code":"AV","name":"AV","statuses":["primary"]},{"code":"BA","name":"BA","statuses":["primary"]},{"code":"BAC","name":"BAC","statuses":["primary"]},{"code":"BTA","name":"Bata","statuses":["primary"]},{"code":"BAY","name":"BAY","statuses":["primary"]},{"code":"BBCC","name":"BBCC","statuses":["primary"]},{"code":"BQC","name":"BBQCoin","statuses":["primary"]},{"code":"BDC","name":"BDC","statuses":["primary"]},{"code":"BEC","name":"BEC","statuses":["primary"]},{"code":"BEEZ","name":"BEEZ","statuses":["primary"]},{"code":"BELA","name":"BellaCoin","statuses":["primary"]},{"code":"BERN","name":"BERNcash","statuses":["primary"]},{"code":"BILL","name":"BILL","statuses":["primary"]},{"code":"BILS","name":"BILS","statuses":["primary"]},{"code":"BIOS","name":"BiosCrypto","statuses":["primary"]},{"code":"BIT","name":"BIT","statuses":["primary"]},{"code":"BIT16","name":"BIT16","statuses":["primary"]},{"code":"BITB","name":"BitBean","statuses":["primary"]},{"code":"BTC","name":"Bitcoin","statuses":["primary","secondary"]},{"code":"XBC","name":"Bitcoin Plus","statuses":["primary"]},{"code":"BTCD","name":"BitcoinDark","statuses":["primary"]},{"code":"BCY","name":"Bitcrystals","statuses":["primary"]},{"code":"BTM","name":"Bitmark","statuses":["primary"]},{"code":"BTQ","name":"BitQuark","statuses":["primary"]},{"code":"BITS","name":"BITS","statuses":["primary"]},{"code":"BSD","name":"BitSend","statuses":["primary"]},{"code":"BTS","name":"BitShares","statuses":["primary"]},{"code":"PTS","name":"BitShares PTS","statuses":["primary"]},{"code":"SWIFT","name":"BitSwift","statuses":["primary"]},{"code":"BITZ","name":"Bitz","statuses":["primary"]},{"code":"BLK","name":"Blackcoin","statuses":["primary"]},{"code":"JACK","name":"BlackJack","statuses":["primary"]},{"code":"BLC","name":"Blakecoin","statuses":["primary"]},{"code":"BLEU","name":"BLEU","statuses":["primary"]},{"code":"BLITZ","name":"Blitzcoin","statuses":["primary"]},{"code":"BLOCK","name":"Blocknet","statuses":["primary"]},{"code":"BLRY","name":"BLRY","statuses":["primary"]},{"code":"BLU","name":"BLU","statuses":["primary"]},{"code":"BM","name":"BM","statuses":["primary"]},{"code":"BNT","name":"BNT","statuses":["primary"]},{"code":"BOB","name":"BOB","statuses":["primary"]},{"code":"BON","name":"BON","statuses":["primary"]},{"code":"BBR","name":"Boolberry","statuses":["primary"]},{"code":"BOST","name":"BoostCoin","statuses":["primary"]},{"code":"BOSS","name":"BOSS","statuses":["primary"]},{"code":"BPOK","name":"BPOK","statuses":["primary"]},{"code":"BRAIN","name":"BRAIN","statuses":["primary"]},{"code":"BRC","name":"BRC","statuses":["primary"]},{"code":"BRDD","name":"BRDD","statuses":["primary"]},{"code":"BRIT","name":"BRIT","statuses":["primary"]},{"code":"GBP","name":"British Pound Sterling","statuses":["secondary"]},{"code":"BRK","name":"BRK","statuses":["primary"]},{"code":"BRX","name":"BRX","statuses":["primary"]},{"code":"BSC","name":"BSC","statuses":["primary"]},{"code":"BST","name":"BST","statuses":["primary"]},{"code":"BTCHC","name":"BTCHC","statuses":["primary"]},{"code":"BTCR","name":"BTCR","statuses":["primary"]},{"code":"BTCS","name":"BTCS","statuses":["primary"]},{"code":"BTCU","name":"BTCU","statuses":["primary"]},{"code":"BTTF","name":"BTTF","statuses":["primary"]},{"code":"BTX","name":"BTX","statuses":["primary"]},{"code":"BUCKS","name":"BUCKS","statuses":["primary"]},{"code":"BUN","name":"BUN","statuses":["primary"]},{"code":"BURST","name":"Burst","statuses":["primary"]},{"code":"BUZZ","name":"BUZZ","statuses":["primary"]},{"code":"BVC","name":"BVC","statuses":["primary"]},{"code":"BYC","name":"Bytecent","statuses":["primary"]},{"code":"BCN","name":"Bytecoin","statuses":["primary"]},{"code":"XCT","name":"C-Bit","statuses":["primary"]},{"code":"C0C0","name":"C0C0","statuses":["primary"]},{"code":"CAB","name":"Cabbage Unit","statuses":["primary"]},{"code":"CAD","name":"CAD","statuses":["primary","secondary"]},{"code":"CAGE","name":"CAGE","statuses":["primary"]},{"code":"CANN","name":"CannabisCoin","statuses":["primary"]},{"code":"CCN","name":"Cannacoin","statuses":["primary"]},{"code":"CPC","name":"Capricoin","statuses":["primary"]},{"code":"DIEM","name":"CarpeDiemCoin","statuses":["primary"]},{"code":"CASH","name":"CASH","statuses":["primary"]},{"code":"CBIT","name":"CBIT","statuses":["primary"]},{"code":"CC","name":"CC","statuses":["primary"]},{"code":"CCB","name":"CCB","statuses":["primary"]},{"code":"CD","name":"CD","statuses":["primary"]},{"code":"CDN","name":"CDN","statuses":["primary"]},{"code":"CF","name":"CF","statuses":["primary"]},{"code":"CFC","name":"CFC","statuses":["primary"]},{"code":"CGA","name":"CGA","statuses":["primary"]},{"code":"CHC","name":"CHC","statuses":["primary"]},{"code":"CKC","name":"Checkcoin","statuses":["primary"]},{"code":"CHEMX","name":"CHEMX","statuses":["primary"]},{"code":"CHESS","name":"CHESS","statuses":["primary"]},{"code":"CHF","name":"CHF","statuses":["primary","secondary"]},{"code":"CNY","name":"Chinese Yuan","statuses":["secondary"]},{"code":"CHRG","name":"CHRG","statuses":["primary"]},{"code":"CJ","name":"CJ","statuses":["primary"]},{"code":"CLAM","name":"Clams","statuses":["primary"]},{"code":"CLICK","name":"CLICK","statuses":["primary"]},{"code":"CLINT","name":"CLINT","statuses":["primary"]},{"code":"CLOAK","name":"Cloakcoin","statuses":["primary"]},{"code":"CLR","name":"CLR","statuses":["primary"]},{"code":"CLUB","name":"CLUB","statuses":["primary"]},{"code":"CLUD","name":"CLUD","statuses":["primary"]},{"code":"CMT","name":"CMT","statuses":["primary"]},{"code":"CNC","name":"CNC","statuses":["primary"]},{"code":"COXST","name":"CoExistCoin","statuses":["primary"]},{"code":"COIN","name":"COIN","statuses":["primary"]},{"code":"C2","name":"Coin2.1","statuses":["primary"]},{"code":"CNMT","name":"Coinomat","statuses":["primary"]},{"code":"CV2","name":"Colossuscoin2.0","statuses":["primary"]},{"code":"CON","name":"CON","statuses":["primary"]},{"code":"XCP","name":"Counterparty","statuses":["primary"]},{"code":"COV","name":"COV","statuses":["primary"]},{"code":"CRAFT","name":"CRAFT","statuses":["primary"]},{"code":"CRAVE","name":"CRAVE","statuses":["primary"]},{"code":"CRC","name":"CRC","statuses":["primary"]},{"code":"CRE","name":"CRE","statuses":["primary"]},{"code":"CRBIT","name":"Creditbit","statuses":["primary"]},{"code":"CREVA","name":"CrevaCoin","statuses":["primary"]},{"code":"CRIME","name":"CRIME","statuses":["primary"]},{"code":"CRT","name":"CRT","statuses":["primary"]},{"code":"CRW","name":"CRW","statuses":["primary"]},{"code":"CRY","name":"CRY","statuses":["primary"]},{"code":"XCR","name":"Crypti","statuses":["primary"]},{"code":"CBX","name":"Crypto Bullion","statuses":["primary"]},{"code":"CESC","name":"CryptoEscudo","statuses":["primary"]},{"code":"XCN","name":"Cryptonite","statuses":["primary"]},{"code":"CSMIC","name":"CSMIC","statuses":["primary"]},{"code":"CST","name":"CST","statuses":["primary"]},{"code":"CTC","name":"CTC","statuses":["primary"]},{"code":"CTO","name":"CTO","statuses":["primary"]},{"code":"CURE","name":"Curecoin","statuses":["primary"]},{"code":"CYP","name":"Cypher","statuses":["primary"]},{"code":"CZC","name":"CZC","statuses":["primary"]},{"code":"CZECO","name":"CZECO","statuses":["primary"]},{"code":"CZR","name":"CZR","statuses":["primary"]},{"code":"DAO","name":"DAO","statuses":["primary"]},{"code":"DGD","name":"DarkGoldCoin","statuses":["primary"]},{"code":"DNET","name":"Darknet","statuses":["primary"]},{"code":"DASH","name":"Dash","statuses":["primary"]},{"code":"DTC","name":"Datacoin","statuses":["primary"]},{"code":"DBG","name":"DBG","statuses":["primary"]},{"code":"DBLK","name":"DBLK","statuses":["primary"]},{"code":"DBTC","name":"DBTC","statuses":["primary"]},{"code":"DCK","name":"DCK","statuses":["primary"]},{"code":"DCR","name":"Decred","statuses":["primary"]},{"code":"DES","name":"Destiny","statuses":["primary"]},{"code":"DETH","name":"DETH","statuses":["primary"]},{"code":"DEUR","name":"DEUR","statuses":["primary"]},{"code":"DEM","name":"Deutsche eMark","statuses":["primary"]},{"code":"DVC","name":"Devcoin","statuses":["primary"]},{"code":"DGCS","name":"DGCS","statuses":["primary"]},{"code":"DGMS","name":"DGMS","statuses":["primary"]},{"code":"DGORE","name":"DGORE","statuses":["primary"]},{"code":"DMD","name":"Diamond","statuses":["primary"]},{"code":"DGB","name":"Digibyte","statuses":["primary"]},{"code":"CUBE","name":"DigiCube","statuses":["primary"]},{"code":"DGC","name":"Digitalcoin","statuses":["primary"]},{"code":"XDN","name":"DigitalNote","statuses":["primary"]},{"code":"DP","name":"DigitalPrice","statuses":["primary"]},{"code":"DIGS","name":"DIGS","statuses":["primary"]},{"code":"DIME","name":"Dimecoin","statuses":["primary"]},{"code":"DISK","name":"DISK","statuses":["primary"]},{"code":"DLISK","name":"DLISK","statuses":["primary"]},{"code":"NOTE","name":"DNotes","statuses":["primary"]},{"code":"DOGE","name":"DOGE","statuses":["primary","secondary"]},{"code":"DOGE","name":"Dogecoin","statuses":["primary","secondary"]},{"code":"DON","name":"DON","statuses":["primary"]},{"code":"DOPE","name":"DopeCoin","statuses":["primary"]},{"code":"DOX","name":"DOX","statuses":["primary"]},{"code":"DRACO","name":"DRACO","statuses":["primary"]},{"code":"DRM","name":"DRM","statuses":["primary"]},{"code":"DROP","name":"DROP","statuses":["primary"]},{"code":"DRZ","name":"DRZ","statuses":["primary"]},{"code":"DSH","name":"DSH","statuses":["primary"]},{"code":"DBIC","name":"DubaiCoin","statuses":["primary"]},{"code":"DUO","name":"DUO","statuses":["primary"]},{"code":"DUST","name":"DUST","statuses":["primary"]},{"code":"EAC","name":"Earthcoin","statuses":["primary"]},{"code":"ECCHI","name":"ECCHI","statuses":["primary"]},{"code":"ECC","name":"ECCoin","statuses":["primary"]},{"code":"ECOS","name":"ECOS","statuses":["primary"]},{"code":"EDC","name":"EDC","statuses":["primary"]},{"code":"EDRC","name":"EDRC","statuses":["primary"]},{"code":"EGG","name":"EGG","statuses":["primary"]},{"code":"EMC2","name":"Einsteinium","statuses":["primary"]},{"code":"EKO","name":"EKO","statuses":["primary"]},{"code":"EL","name":"EL","statuses":["primary"]},{"code":"ELCO","name":"ELcoin","statuses":["primary"]},{"code":"ELE","name":"ELE","statuses":["primary"]},{"code":"EFL","name":"Electronic Gulden","statuses":["primary"]},{"code":"EMC","name":"Emercoin","statuses":["primary"]},{"code":"EMIRG","name":"EMIRG","statuses":["primary"]},{"code":"ENE","name":"ENE","statuses":["primary"]},{"code":"ENRG","name":"Energycoin","statuses":["primary"]},{"code":"EPC","name":"EPC","statuses":["primary"]},{"code":"EPY","name":"EPY","statuses":["primary"]},{"code":"ERC","name":"ERC","statuses":["primary"]},{"code":"ERC3","name":"ERC3","statuses":["primary"]},{"code":"ESC","name":"ESC","statuses":["primary"]},{"code":"ETH","name":"Ethereum","statuses":["primary","secondary"]},{"code":"ETC","name":"Ethereum Classic","statuses":["primary"]},{"code":"ETHS","name":"ETHS","statuses":["primary"]},{"code":"EURC","name":"EURC","statuses":["primary"]},{"code":"EUR","name":"Euro","statuses":["primary","secondary"]},{"code":"EGC","name":"EvergreenCoin","statuses":["primary"]},{"code":"EVIL","name":"EVIL","statuses":["primary"]},{"code":"EVO","name":"EVO","statuses":["primary"]},{"code":"EXCL","name":"EXCL","statuses":["primary"]},{"code":"EXIT","name":"EXIT","statuses":["primary"]},{"code":"EXP","name":"Expanse","statuses":["primary"]},{"code":"FCT","name":"Factom","statuses":["primary"]},{"code":"FAIR","name":"Faircoin","statuses":["primary"]},{"code":"FC2","name":"FC2","statuses":["primary"]},{"code":"FCN","name":"FCN","statuses":["primary"]},{"code":"FTC","name":"Feathercoin","statuses":["primary"]},{"code":"TIPS","name":"Fedoracoin","statuses":["primary"]},{"code":"FFC","name":"FFC","statuses":["primary"]},{"code":"FIBRE","name":"Fibre","statuses":["primary"]},{"code":"FIT","name":"FIT","statuses":["primary"]},{"code":"FJC","name":"FJC","statuses":["primary"]},{"code":"FLO","name":"Florincoin","statuses":["primary"]},{"code":"FLOZ","name":"FLOZ","statuses":["primary"]},{"code":"FLT","name":"FlutterCoin","statuses":["primary"]},{"code":"FLX","name":"FLX","statuses":["primary"]},{"code":"FLY","name":"Flycoin","statuses":["primary"]},{"code":"FLDC","name":"FoldingCoin","statuses":["primary"]},{"code":"FONZ","name":"FONZ","statuses":["primary"]},{"code":"FRK","name":"Franko","statuses":["primary"]},{"code":"FRC","name":"Freicoin","statuses":["primary"]},{"code":"FRN","name":"FRN","statuses":["primary"]},{"code":"FRWC","name":"FRWC","statuses":["primary"]},{"code":"FSC2","name":"FSC2","statuses":["primary"]},{"code":"FST","name":"FST","statuses":["primary"]},{"code":"FTP","name":"FTP","statuses":["primary"]},{"code":"FUN","name":"FUN","statuses":["primary"]},{"code":"FUTC","name":"FUTC","statuses":["primary"]},{"code":"FUZZ","name":"FUZZ","statuses":["primary"]},{"code":"GAIA","name":"GAIA","statuses":["primary"]},{"code":"GAIN","name":"GAIN","statuses":["primary"]},{"code":"GAKH","name":"GAKH","statuses":["primary"]},{"code":"GAM","name":"GAM","statuses":["primary"]},{"code":"GBT","name":"GameBet Coin","statuses":["primary"]},{"code":"GAME","name":"GameCredits","statuses":["primary"]},{"code":"GAP","name":"Gapcoin","statuses":["primary"]},{"code":"GARY","name":"GARY","statuses":["primary"]},{"code":"GB","name":"GB","statuses":["primary"]},{"code":"GBC","name":"GBC","statuses":["primary"]},{"code":"GBIT","name":"GBIT","statuses":["primary"]},{"code":"GCC","name":"GCC","statuses":["primary"]},{"code":"GCN","name":"GCN","statuses":["primary"]},{"code":"GEO","name":"GeoCoin","statuses":["primary"]},{"code":"GEMZ","name":"GetGems","statuses":["primary"]},{"code":"GHOST","name":"GHOST","statuses":["primary"]},{"code":"GHS","name":"GHS","statuses":["primary"]},{"code":"GIFT","name":"GIFT","statuses":["primary"]},{"code":"GIG","name":"GIG","statuses":["primary"]},{"code":"GLC","name":"GLC","statuses":["primary"]},{"code":"BSTY","name":"GlobalBoost-Y","statuses":["primary"]},{"code":"GML","name":"GML","statuses":["primary"]},{"code":"GMX","name":"GMX","statuses":["primary"]},{"code":"GCR","name":"GoCoineR","statuses":["primary"]},{"code":"GLD","name":"GoldCoin","statuses":["primary"]},{"code":"GOON","name":"GOON","statuses":["primary"]},{"code":"GP","name":"GP","statuses":["primary"]},{"code":"GPU","name":"GPU","statuses":["primary"]},{"code":"GRAM","name":"GRAM","statuses":["primary"]},{"code":"GRT","name":"Grantcoin","statuses":["primary"]},{"code":"GRE","name":"GRE","statuses":["primary"]},{"code":"GRC","name":"Gridcoin","statuses":["primary"]},{"code":"GRN","name":"GRN","statuses":["primary"]},{"code":"GRS","name":"Groestlcoin","statuses":["primary"]},{"code":"GRW","name":"GRW","statuses":["primary"]},{"code":"GSM","name":"GSM","statuses":["primary"]},{"code":"GSX","name":"GSX","statuses":["primary"]},{"code":"GUA","name":"GUA","statuses":["primary"]},{"code":"NLG","name":"Gulden","statuses":["primary"]},{"code":"GUN","name":"GUN","statuses":["primary"]},{"code":"HAM","name":"HAM","statuses":["primary"]},{"code":"HAWK","name":"HAWK","statuses":["primary"]},{"code":"HCC","name":"HCC","statuses":["primary"]},{"code":"HEAT","name":"HEAT","statuses":["primary"]},{"code":"HMP","name":"HempCoin","statuses":["primary"]},{"code":"XHI","name":"HiCoin","statuses":["primary"]},{"code":"HIFUN","name":"HIFUN","statuses":["primary"]},{"code":"HILL","name":"HILL","statuses":["primary"]},{"code":"HIRE","name":"HIRE","statuses":["primary"]},{"code":"HNC","name":"HNC","statuses":["primary"]},{"code":"HODL","name":"HOdlcoin","statuses":["primary"]},{"code":"HKD","name":"Hong Kong Dollar","statuses":["secondary"]},{"code":"HZ","name":"Horizon","statuses":["primary"]},{"code":"HTC","name":"HTC","statuses":["primary"]},{"code":"HTML5","name":"HTMLCOIN","statuses":["primary"]},{"code":"HUC","name":"HUC","statuses":["primary"]},{"code":"HVCO","name":"HVCO","statuses":["primary"]},{"code":"HYPER","name":"Hyper","statuses":["primary"]},{"code":"HYP","name":"HyperStake","statuses":["primary"]},{"code":"I0C","name":"I0C","statuses":["primary"]},{"code":"IBANK","name":"IBANK","statuses":["primary"]},{"code":"ICASH","name":"iCash","statuses":["primary"]},{"code":"ICN","name":"ICN","statuses":["primary"]},{"code":"IEC","name":"IEC","statuses":["primary"]},{"code":"IFC","name":"Infinitecoin","statuses":["primary"]},{"code":"INFX","name":"Influxcoin","statuses":["primary"]},{"code":"INV","name":"INV","statuses":["primary"]},{"code":"IOC","name":"IO Coin","statuses":["primary"]},{"code":"ION","name":"ION","statuses":["primary"]},{"code":"IRL","name":"IRL","statuses":["primary"]},{"code":"ISL","name":"IslaCoin","statuses":["primary"]},{"code":"IVZ","name":"IVZ","statuses":["primary"]},{"code":"IXC","name":"IXC","statuses":["primary"]},{"code":"JIF","name":"JIF","statuses":["primary"]},{"code":"JPC","name":"JPC","statuses":["primary"]},{"code":"JPY","name":"JPY","statuses":["primary","secondary"]},{"code":"JBS","name":"Jumbucks","statuses":["primary"]},{"code":"KAT","name":"KAT","statuses":["primary"]},{"code":"KGC","name":"KGC","statuses":["primary"]},{"code":"KNC","name":"KhanCoin","statuses":["primary"]},{"code":"KLC","name":"KLC","statuses":["primary"]},{"code":"KOBO","name":"KOBO","statuses":["primary"]},{"code":"KORE","name":"KoreCoin","statuses":["primary"]},{"code":"KRAK","name":"KRAK","statuses":["primary"]},{"code":"KRYP","name":"KRYP","statuses":["primary"]},{"code":"KR","name":"Krypton","statuses":["primary"]},{"code":"KTK","name":"KTK","statuses":["primary"]},{"code":"KUBO","name":"KUBO","statuses":["primary"]},{"code":"LANA","name":"LANA","statuses":["primary"]},{"code":"LBC","name":"LBC","statuses":["primary"]},{"code":"LC","name":"LC","statuses":["primary"]},{"code":"LEA","name":"LeaCoin","statuses":["primary"]},{"code":"LEMON","name":"LEMON","statuses":["primary"]},{"code":"LEO","name":"LEO","statuses":["primary"]},{"code":"LFC","name":"LFC","statuses":["primary"]},{"code":"LFO","name":"LFO","statuses":["primary"]},{"code":"LFTC","name":"LFTC","statuses":["primary"]},{"code":"LQD","name":"LIQUID","statuses":["primary"]},{"code":"LIR","name":"LIR","statuses":["primary"]},{"code":"LSK","name":"Lisk","statuses":["primary"]},{"code":"LTC","name":"Litecoin","statuses":["primary","secondary"]},{"code":"LTCR","name":"Litecred","statuses":["primary"]},{"code":"LDOGE","name":"LiteDoge","statuses":["primary"]},{"code":"LKC","name":"LKC","statuses":["primary"]},{"code":"LOC","name":"LOC","statuses":["primary"]},{"code":"LOOT","name":"LOOT","statuses":["primary"]},{"code":"LTBC","name":"LTBcoin","statuses":["primary"]},{"code":"LTC","name":"LTC","statuses":["primary","secondary"]},{"code":"LTH","name":"LTH","statuses":["primary"]},{"code":"LTS","name":"LTS","statuses":["primary"]},{"code":"LUN","name":"LUN","statuses":["primary"]},{"code":"LXC","name":"LXC","statuses":["primary"]},{"code":"LYB","name":"LYB","statuses":["primary"]},{"code":"M1","name":"M1","statuses":["primary"]},{"code":"MAD","name":"MAD","statuses":["primary"]},{"code":"XMG","name":"Magi","statuses":["primary"]},{"code":"MAID","name":"MaidSafeCoin","statuses":["primary"]},{"code":"MXT","name":"MarteXcoin","statuses":["primary"]},{"code":"MARV","name":"MARV","statuses":["primary"]},{"code":"MARYJ","name":"MARYJ","statuses":["primary"]},{"code":"OMNI","name":"Mastercoin (Omni)","statuses":["primary"]},{"code":"MTR","name":"MasterTraderCoin","statuses":["primary"]},{"code":"MAX","name":"Maxcoin","statuses":["primary"]},{"code":"MZC","name":"Mazacoin","statuses":["primary"]},{"code":"MBL","name":"MBL","statuses":["primary"]},{"code":"MCAR","name":"MCAR","statuses":["primary"]},{"code":"MCN","name":"MCN","statuses":["primary"]},{"code":"MCZ","name":"MCZ","statuses":["primary"]},{"code":"MED","name":"MediterraneanCoin","statuses":["primary"]},{"code":"MEC","name":"Megacoin","statuses":["primary"]},{"code":"MEME","name":"Memetic","statuses":["primary"]},{"code":"METAL","name":"METAL","statuses":["primary"]},{"code":"MND","name":"MindCoin","statuses":["primary"]},{"code":"MINT","name":"Mintcoin","statuses":["primary"]},{"code":"MIS","name":"MIS","statuses":["primary"]},{"code":"MM","name":"MM","statuses":["primary"]},{"code":"MMC","name":"MMC","statuses":["primary"]},{"code":"MMNXT","name":"MMNXT","statuses":["primary"]},{"code":"MMXVI","name":"MMXVI","statuses":["primary"]},{"code":"MNM","name":"MNM","statuses":["primary"]},{"code":"MOIN","name":"MOIN","statuses":["primary"]},{"code":"MOJO","name":"MojoCoin","statuses":["primary"]},{"code":"MONA","name":"MonaCoin","statuses":["primary"]},{"code":"XMR","name":"Monero","statuses":["primary","secondary"]},{"code":"MNTA","name":"Moneta","statuses":["primary"]},{"code":"MUE","name":"MonetaryUnit","statuses":["primary"]},{"code":"MOON","name":"Mooncoin","statuses":["primary"]},{"code":"MOOND","name":"MOOND","statuses":["primary"]},{"code":"MOTO","name":"MOTO","statuses":["primary"]},{"code":"MPRO","name":"MPRO","statuses":["primary"]},{"code":"MRB","name":"MRB","statuses":["primary"]},{"code":"MRP","name":"MRP","statuses":["primary"]},{"code":"MSC","name":"MSC","statuses":["primary"]},{"code":"MYR","name":"Myriadcoin","statuses":["primary"]},{"code":"NMC","name":"Namecoin","statuses":["primary"]},{"code":"NAUT","name":"Nautiluscoin","statuses":["primary"]},{"code":"NAV","name":"NAV Coin","statuses":["primary"]},{"code":"NCS","name":"NCS","statuses":["primary"]},{"code":"XEM","name":"NEM","statuses":["primary"]},{"code":"NEOS","name":"NeosCoin","statuses":["primary"]},{"code":"NETC","name":"NETC","statuses":["primary"]},{"code":"NET","name":"NetCoin","statuses":["primary"]},{"code":"NEU","name":"NeuCoin","statuses":["primary"]},{"code":"NTRN","name":"Neutron","statuses":["primary"]},{"code":"NEVA","name":"NevaCoin","statuses":["primary"]},{"code":"NEWB","name":"NEWB","statuses":["primary"]},{"code":"NIRO","name":"Nexus","statuses":["primary"]},{"code":"NIC","name":"NIC","statuses":["primary"]},{"code":"NKA","name":"NKA","statuses":["primary"]},{"code":"NKC","name":"NKC","statuses":["primary"]},{"code":"NOBL","name":"NobleCoin","statuses":["primary"]},{"code":"NODE","name":"NODE","statuses":["primary"]},{"code":"NODES","name":"NODES","statuses":["primary"]},{"code":"NOO","name":"NOO","statuses":["primary"]},{"code":"NVC","name":"Novacoin","statuses":["primary"]},{"code":"NRC","name":"NRC","statuses":["primary"]},{"code":"NRS","name":"NRS","statuses":["primary"]},{"code":"NUBIS","name":"NUBIS","statuses":["primary"]},{"code":"NBT","name":"NuBits","statuses":["primary"]},{"code":"NUM","name":"NUM","statuses":["primary"]},{"code":"NSR","name":"NuShares","statuses":["primary"]},{"code":"NXE","name":"NXE","statuses":["primary"]},{"code":"NXT","name":"NXT","statuses":["primary"]},{"code":"NXTTY","name":"Nxttycoin","statuses":["primary"]},{"code":"NYC","name":"NYC","statuses":["primary"]},{"code":"NZC","name":"NZC","statuses":["primary"]},{"code":"NZD","name":"NZD","statuses":["primary","secondary"]},{"code":"OC","name":"OC","statuses":["primary"]},{"code":"OCOW","name":"OCOW","statuses":["primary"]},{"code":"OK","name":"OKCash","statuses":["primary"]},{"code":"OMA","name":"OMA","statuses":["primary"]},{"code":"ONE","name":"ONE","statuses":["primary"]},{"code":"ONEC","name":"ONEC","statuses":["primary"]},{"code":"OP","name":"OP","statuses":["primary"]},{"code":"OPAL","name":"OPAL","statuses":["primary"]},{"code":"OPES","name":"OPES","statuses":["primary"]},{"code":"ORB","name":"Orbitcoin","statuses":["primary"]},{"code":"ORLY","name":"Orlycoin","statuses":["primary"]},{"code":"OS76","name":"OS76","statuses":["primary"]},{"code":"OZC","name":"OZC","statuses":["primary"]},{"code":"PAC","name":"PAC","statuses":["primary"]},{"code":"PAK","name":"PAK","statuses":["primary"]},{"code":"PND","name":"Pandacoin","statuses":["primary"]},{"code":"PAPAF","name":"PAPAF","statuses":["primary"]},{"code":"XPY","name":"Paycoin","statuses":["primary"]},{"code":"PBC","name":"PBC","statuses":["primary"]},{"code":"PDC","name":"PDC","statuses":["primary"]},{"code":"XPB","name":"Pebblecoin","statuses":["primary"]},{"code":"PPC","name":"Peercoin","statuses":["primary"]},{"code":"PEN","name":"PEN","statuses":["primary"]},{"code":"PHR","name":"PHR","statuses":["primary"]},{"code":"PIGGY","name":"Piggycoin","statuses":["primary"]},{"code":"PC","name":"Pinkcoin","statuses":["primary"]},{"code":"PKB","name":"PKB","statuses":["primary"]},{"code":"PLN","name":"PLN","statuses":["primary","secondary"]},{"code":"PLNC","name":"PLNC","statuses":["primary"]},{"code":"PNC","name":"PNC","statuses":["primary"]},{"code":"PNK","name":"PNK","statuses":["primary"]},{"code":"POKE","name":"POKE","statuses":["primary"]},{"code":"PONZ2","name":"PONZ2","statuses":["primary"]},{"code":"PONZI","name":"PONZI","statuses":["primary"]},{"code":"PEX","name":"PosEx","statuses":["primary"]},{"code":"POST","name":"POST","statuses":["primary"]},{"code":"POT","name":"Potcoin","statuses":["primary"]},{"code":"PRES","name":"PRES","statuses":["primary"]},{"code":"PXI","name":"Prime-XI","statuses":["primary"]},{"code":"PRIME","name":"PrimeChain","statuses":["primary"]},{"code":"XPM","name":"Primecoin","statuses":["primary"]},{"code":"PRM","name":"PRM","statuses":["primary"]},{"code":"PRT","name":"PRT","statuses":["primary"]},{"code":"PSP","name":"PSP","statuses":["primary"]},{"code":"PTC","name":"PTC","statuses":["primary"]},{"code":"PULSE","name":"PULSE","statuses":["primary"]},{"code":"PURE","name":"PURE","statuses":["primary"]},{"code":"PUTIN","name":"PUTIN","statuses":["primary"]},{"code":"PWR","name":"PWR","statuses":["primary"]},{"code":"PXL","name":"PXL","statuses":["primary"]},{"code":"QBC","name":"QBC","statuses":["primary"]},{"code":"QBK","name":"QBK","statuses":["primary"]},{"code":"QCN","name":"QCN","statuses":["primary"]},{"code":"QORA","name":"Qora","statuses":["primary"]},{"code":"QTZ","name":"QTZ","statuses":["primary"]},{"code":"QRK","name":"Quark","statuses":["primary"]},{"code":"QTL","name":"Quatloo","statuses":["primary"]},{"code":"RADI","name":"RADI","statuses":["primary"]},{"code":"RADS","name":"Radium","statuses":["primary"]},{"code":"RED","name":"RED","statuses":["primary"]},{"code":"RDD","name":"Reddcoin","statuses":["primary"]},{"code":"REE","name":"REE","statuses":["primary"]},{"code":"REV","name":"Revenu","statuses":["primary"]},{"code":"RBR","name":"RibbitRewards","statuses":["primary"]},{"code":"RICHX","name":"RICHX","statuses":["primary"]},{"code":"RIC","name":"Riecoin","statuses":["primary"]},{"code":"RBT","name":"Rimbit","statuses":["primary"]},{"code":"RIO","name":"RIO","statuses":["primary"]},{"code":"XRP","name":"Ripple","statuses":["primary"]},{"code":"RISE","name":"RISE","statuses":["primary"]},{"code":"RMS","name":"RMS","statuses":["primary"]},{"code":"RONIN","name":"RONIN","statuses":["primary"]},{"code":"ROOT","name":"ROOT","statuses":["primary"]},{"code":"ROS","name":"RosCoin","statuses":["primary"]},{"code":"RPC","name":"RPC","statuses":["primary"]},{"code":"RBIES","name":"Rubies","statuses":["primary"]},{"code":"RUBIT","name":"RUBIT","statuses":["primary"]},{"code":"RUR","name":"Ruble","statuses":["secondary"]},{"code":"RBY","name":"Rubycoin","statuses":["primary"]},{"code":"RUST","name":"RUST","statuses":["primary"]},{"code":"SEC","name":"Safe Exchange Coin","statuses":["primary"]},{"code":"SAK","name":"SAK","statuses":["primary"]},{"code":"SAR","name":"SAR","statuses":["primary"]},{"code":"SBD","name":"SBD","statuses":["primary"]},{"code":"SBIT","name":"SBIT","statuses":["primary"]},{"code":"SCAN","name":"SCAN","statuses":["primary"]},{"code":"SCOT","name":"Scotcoin","statuses":["primary"]},{"code":"SCRPT","name":"SCRPT","statuses":["primary"]},{"code":"SCRT","name":"SCRT","statuses":["primary"]},{"code":"SRC","name":"SecureCoin","statuses":["primary"]},{"code":"SXC","name":"Sexcoin","statuses":["primary"]},{"code":"SFE","name":"SFE","statuses":["primary"]},{"code":"SFR","name":"SFR","statuses":["primary"]},{"code":"SGD","name":"SGD","statuses":["primary","secondary"]},{"code":"SDC","name":"ShadowCash","statuses":["primary"]},{"code":"SHELL","name":"SHELL","statuses":["primary"]},{"code":"SHF","name":"SHF","statuses":["primary"]},{"code":"SHI","name":"SHI","statuses":["primary"]},{"code":"SHIFT","name":"Shift","statuses":["primary"]},{"code":"SHREK","name":"SHREK","statuses":["primary"]},{"code":"SC","name":"Siacoin","statuses":["primary"]},{"code":"SIB","name":"Siberian chervonets","statuses":["primary"]},{"code":"SIC","name":"SIC","statuses":["primary"]},{"code":"SIGU","name":"SIGU","statuses":["primary"]},{"code":"SILK","name":"Silkcoin","statuses":["primary"]},{"code":"SIX","name":"SIX","statuses":["primary"]},{"code":"SLING","name":"Sling","statuses":["primary"]},{"code":"SLS","name":"SLS","statuses":["primary"]},{"code":"SMBR","name":"SMBR","statuses":["primary"]},{"code":"SMC","name":"SMC","statuses":["primary"]},{"code":"SMLY","name":"SmileyCoin","statuses":["primary"]},{"code":"SNRG","name":"SNRG","statuses":["primary"]},{"code":"SOIL","name":"SOILcoin","statuses":["primary"]},{"code":"SLR","name":"Solarcoin","statuses":["primary"]},{"code":"SOLO","name":"SOLO","statuses":["primary"]},{"code":"SONG","name":"SongCoin","statuses":["primary"]},{"code":"SOON","name":"SOON","statuses":["primary"]},{"code":"SPC","name":"SPC","statuses":["primary"]},{"code":"SPEX","name":"SPEX","statuses":["primary"]},{"code":"SPHR","name":"Sphere","statuses":["primary"]},{"code":"SPM","name":"SPM","statuses":["primary"]},{"code":"SPN","name":"SPN","statuses":["primary"]},{"code":"SPOTS","name":"SPOTS","statuses":["primary"]},{"code":"SPR","name":"SpreadCoin","statuses":["primary"]},{"code":"SPRTS","name":"Sprouts","statuses":["primary"]},{"code":"SQC","name":"SQC","statuses":["primary"]},{"code":"SSC","name":"SSC","statuses":["primary"]},{"code":"SSTC","name":"SSTC","statuses":["primary"]},{"code":"STA","name":"STA","statuses":["primary"]},{"code":"START","name":"Startcoin","statuses":["primary"]},{"code":"XST","name":"Stealthcoin","statuses":["primary"]},{"code":"STEEM","name":"Steem","statuses":["primary"]},{"code":"XLM","name":"Stellar","statuses":["primary"]},{"code":"STR","name":"Stellar","statuses":["primary"]},{"code":"STEPS","name":"Steps","statuses":["primary"]},{"code":"SLG","name":"Sterlingcoin","statuses":["primary"]},{"code":"STL","name":"STL","statuses":["primary"]},{"code":"SJCX","name":"Storjcoin X","statuses":["primary"]},{"code":"STP","name":"STP","statuses":["primary"]},{"code":"STRB","name":"STRB","statuses":["primary"]},{"code":"STS","name":"Stress","statuses":["primary"]},{"code":"STRP","name":"STRP","statuses":["primary"]},{"code":"STV","name":"STV","statuses":["primary"]},{"code":"SUB","name":"Subcriptio","statuses":["primary"]},{"code":"SUPER","name":"SUPER","statuses":["primary"]},{"code":"UNITY","name":"SuperNET","statuses":["primary"]},{"code":"SWARM","name":"Swarm","statuses":["primary"]},{"code":"SWING","name":"SWING","statuses":["primary"]},{"code":"SDP","name":"SydPak Coin","statuses":["primary"]},{"code":"SYNC","name":"SYNC","statuses":["primary"]},{"code":"AMP","name":"Synereo","statuses":["primary"]},{"code":"SYS","name":"Syscoin","statuses":["primary"]},{"code":"TAG","name":"TagCoin","statuses":["primary"]},{"code":"TAJ","name":"TAJ","statuses":["primary"]},{"code":"TAK","name":"TAK","statuses":["primary"]},{"code":"TAM","name":"TAM","statuses":["primary"]},{"code":"TAO","name":"TAO","statuses":["primary"]},{"code":"TBC","name":"TBC","statuses":["primary"]},{"code":"TBCX","name":"TBCX","statuses":["primary"]},{"code":"TCR","name":"TCR","statuses":["primary"]},{"code":"TDFB","name":"TDFB","statuses":["primary"]},{"code":"TDY","name":"TDY","statuses":["primary"]},{"code":"TEK","name":"TEKcoin","statuses":["primary"]},{"code":"TRC","name":"Terracoin","statuses":["primary"]},{"code":"TESLA","name":"TESLA","statuses":["primary"]},{"code":"TES","name":"TeslaCoin","statuses":["primary"]},{"code":"TET","name":"TET","statuses":["primary"]},{"code":"USDT","name":"Tether","statuses":["primary","secondary"]},{"code":"THC","name":"THC","statuses":["primary"]},{"code":"THS","name":"THS","statuses":["primary"]},{"code":"TIX","name":"Tickets","statuses":["primary"]},{"code":"XTC","name":"TileCoin","statuses":["primary"]},{"code":"TIT","name":"Titcoin","statuses":["primary"]},{"code":"TTC","name":"TittieCoin","statuses":["primary"]},{"code":"TMC","name":"TMC","statuses":["primary"]},{"code":"TODAY","name":"TODAY","statuses":["primary"]},{"code":"TOKEN","name":"TOKEN","statuses":["primary"]},{"code":"TP1","name":"TP1","statuses":["primary"]},{"code":"TPC","name":"TPC","statuses":["primary"]},{"code":"TPG","name":"TPG","statuses":["primary"]},{"code":"TX","name":"Transfercoin","statuses":["primary"]},{"code":"TRAP","name":"TRAP","statuses":["primary"]},{"code":"TRICK","name":"TRICK","statuses":["primary"]},{"code":"TROLL","name":"TROLL","statuses":["primary"]},{"code":"TRK","name":"Truckcoin","statuses":["primary"]},{"code":"TRUMP","name":"TrumpCoin","statuses":["primary"]},{"code":"TRUST","name":"TRUST","statuses":["primary"]},{"code":"UAE","name":"UAE","statuses":["primary"]},{"code":"UFO","name":"UFO Coin","statuses":["primary"]},{"code":"UIS","name":"UIS","statuses":["primary"]},{"code":"UTC","name":"UltraCoin","statuses":["primary"]},{"code":"UNC","name":"UNC","statuses":["primary"]},{"code":"UNIQ","name":"UNIQ","statuses":["primary"]},{"code":"UNIT","name":"Universal Currency","statuses":["primary"]},{"code":"UNO","name":"Unobtanium","statuses":["primary"]},{"code":"URO","name":"Uro","statuses":["primary"]},{"code":"USD","name":"US Dollar","statuses":["primary","secondary"]},{"code":"USDE","name":"USDE","statuses":["primary"]},{"code":"UTH","name":"UTH","statuses":["primary"]},{"code":"VAL","name":"VAL","statuses":["primary"]},{"code":"XVC","name":"Vcash","statuses":["primary"]},{"code":"VCN","name":"VCN","statuses":["primary"]},{"code":"VEG","name":"VEG","statuses":["primary"]},{"code":"VENE","name":"VENE","statuses":["primary"]},{"code":"XVG","name":"Verge","statuses":["primary"]},{"code":"VRC","name":"VeriCoin","statuses":["primary"]},{"code":"VTC","name":"Vertcoin","statuses":["primary"]},{"code":"VIA","name":"Viacoin","statuses":["primary"]},{"code":"VIOR","name":"Viorcoin","statuses":["primary"]},{"code":"VIP","name":"VIP Tokens","statuses":["primary"]},{"code":"VIRAL","name":"Viral","statuses":["primary"]},{"code":"VOOT","name":"VootCoin","statuses":["primary"]},{"code":"VOX","name":"Voxels","statuses":["primary"]},{"code":"VOYA","name":"VOYA","statuses":["primary"]},{"code":"VPN","name":"VPNCoin","statuses":["primary"]},{"code":"VPRC","name":"VPRC","statuses":["primary"]},{"code":"VTA","name":"VTA","statuses":["primary"]},{"code":"VTN","name":"VTN","statuses":["primary"]},{"code":"VTR","name":"VTR","statuses":["primary"]},{"code":"WAC","name":"WAC","statuses":["primary"]},{"code":"WARP","name":"WARP","statuses":["primary"]},{"code":"WAVES","name":"WAVES","statuses":["primary"]},{"code":"WGC","name":"WGC","statuses":["primary"]},{"code":"XWC","name":"Whitecoin","statuses":["primary"]},{"code":"WBB","name":"Wild Beast Block","statuses":["primary"]},{"code":"WLC","name":"WLC","statuses":["primary"]},{"code":"WMC","name":"WMC","statuses":["primary"]},{"code":"LOG","name":"Woodcoin","statuses":["primary"]},{"code":"WOP","name":"WOP","statuses":["primary"]},{"code":"WDC","name":"Worldcoin","statuses":["primary"]},{"code":"XAB","name":"XAB","statuses":["primary"]},{"code":"XAI","name":"XAI","statuses":["primary"]},{"code":"XAU","name":"Xaurum","statuses":["primary"]},{"code":"XBS","name":"XBS","statuses":["primary"]},{"code":"XBU","name":"XBU","statuses":["primary"]},{"code":"XCO","name":"XCO","statuses":["primary"]},{"code":"XC","name":"XCurrency","statuses":["primary"]},{"code":"XDB","name":"XDB","statuses":["primary"]},{"code":"XEMP","name":"XEMP","statuses":["primary"]},{"code":"XFC","name":"XFC","statuses":["primary"]},{"code":"MI","name":"Xiaomicoin","statuses":["primary"]},{"code":"XID","name":"XID","statuses":["primary"]},{"code":"XJO","name":"XJO","statuses":["primary"]},{"code":"XLTCG","name":"XLTCG","statuses":["primary"]},{"code":"XMS","name":"XMS","statuses":["primary"]},{"code":"XNX","name":"XNX","statuses":["primary"]},{"code":"XPD","name":"XPD","statuses":["primary"]},{"code":"XPOKE","name":"XPOKE","statuses":["primary"]},{"code":"XPRO","name":"XPRO","statuses":["primary"]},{"code":"XQN","name":"XQN","statuses":["primary"]},{"code":"XSEED","name":"XSEED","statuses":["primary"]},{"code":"XSP","name":"XSP","statuses":["primary"]},{"code":"XT","name":"XT","statuses":["primary"]},{"code":"XTP","name":"XTP","statuses":["primary"]},{"code":"XUSD","name":"XUSD","statuses":["primary"]},{"code":"YACC","name":"YACC","statuses":["primary"]},{"code":"YAC","name":"Yacoin","statuses":["primary"]},{"code":"YAY","name":"YAY","statuses":["primary"]},{"code":"YBC","name":"Ybcoin","statuses":["primary"]},{"code":"YOC","name":"YOC","statuses":["primary"]},{"code":"YOVI","name":"YOVI","statuses":["primary"]},{"code":"YUM","name":"YUM","statuses":["primary"]},{"code":"ZCC","name":"ZCC","statuses":["primary"]},{"code":"ZEIT","name":"Zeitcoin","statuses":["primary"]},{"code":"ZET","name":"Zetacoin","statuses":["primary"]},{"code":"ZRC","name":"ZiftrCOIN","statuses":["primary"]},{"code":"ZMC","name":"ZMC","statuses":["primary"]},{"code":"ZNY","name":"ZNY","statuses":["primary"]},{"code":"ZS","name":"ZS","statuses":["primary"]}]} \ No newline at end of file
diff --git a/app/fonts/DIN Next/DIN Next W01 Bold.otf b/app/fonts/DIN Next/DIN Next W01 Bold.otf
new file mode 100644
index 000000000..2b78d1ff4
--- /dev/null
+++ b/app/fonts/DIN Next/DIN Next W01 Bold.otf
Binary files differ
diff --git a/app/fonts/DIN Next/DIN Next W01 Regular.otf b/app/fonts/DIN Next/DIN Next W01 Regular.otf
new file mode 100644
index 000000000..09f6ee297
--- /dev/null
+++ b/app/fonts/DIN Next/DIN Next W01 Regular.otf
Binary files differ
diff --git a/app/fonts/DIN Next/DIN Next W10 Black.otf b/app/fonts/DIN Next/DIN Next W10 Black.otf
new file mode 100644
index 000000000..08eb73373
--- /dev/null
+++ b/app/fonts/DIN Next/DIN Next W10 Black.otf
Binary files differ
diff --git a/app/fonts/DIN Next/DIN Next W10 Italic.otf b/app/fonts/DIN Next/DIN Next W10 Italic.otf
new file mode 100644
index 000000000..73f2b9e8c
--- /dev/null
+++ b/app/fonts/DIN Next/DIN Next W10 Italic.otf
Binary files differ
diff --git a/app/fonts/DIN Next/DIN Next W10 Light.otf b/app/fonts/DIN Next/DIN Next W10 Light.otf
new file mode 100644
index 000000000..700450e49
--- /dev/null
+++ b/app/fonts/DIN Next/DIN Next W10 Light.otf
Binary files differ
diff --git a/app/fonts/DIN Next/DIN Next W10 Medium.otf b/app/fonts/DIN Next/DIN Next W10 Medium.otf
new file mode 100644
index 000000000..b73f2e43f
--- /dev/null
+++ b/app/fonts/DIN Next/DIN Next W10 Medium.otf
Binary files differ
diff --git a/app/fonts/DIN_OT/DINOT-2.otf b/app/fonts/DIN_OT/DINOT-2.otf
new file mode 100644
index 000000000..4a5e13127
--- /dev/null
+++ b/app/fonts/DIN_OT/DINOT-2.otf
Binary files differ
diff --git a/app/fonts/DIN_OT/DINOT-Bold 2.otf b/app/fonts/DIN_OT/DINOT-Bold 2.otf
new file mode 100644
index 000000000..6ed5b6c3d
--- /dev/null
+++ b/app/fonts/DIN_OT/DINOT-Bold 2.otf
Binary files differ
diff --git a/app/fonts/DIN_OT/DINOT-BoldItalic.otf b/app/fonts/DIN_OT/DINOT-BoldItalic.otf
new file mode 100644
index 000000000..148c90588
--- /dev/null
+++ b/app/fonts/DIN_OT/DINOT-BoldItalic.otf
Binary files differ
diff --git a/app/fonts/DIN_OT/DINOT-Italic 2.otf b/app/fonts/DIN_OT/DINOT-Italic 2.otf
new file mode 100644
index 000000000..e365e77ab
--- /dev/null
+++ b/app/fonts/DIN_OT/DINOT-Italic 2.otf
Binary files differ
diff --git a/app/fonts/DIN_OT/DINOT-Medium 2.otf b/app/fonts/DIN_OT/DINOT-Medium 2.otf
new file mode 100644
index 000000000..a87a2df37
--- /dev/null
+++ b/app/fonts/DIN_OT/DINOT-Medium 2.otf
Binary files differ
diff --git a/app/fonts/DIN_OT/DINOT-MediumItalic 2.otf b/app/fonts/DIN_OT/DINOT-MediumItalic 2.otf
new file mode 100644
index 000000000..14eddfc76
--- /dev/null
+++ b/app/fonts/DIN_OT/DINOT-MediumItalic 2.otf
Binary files differ
diff --git a/app/fonts/Lato/Lato-Black.ttf b/app/fonts/Lato/Lato-Black.ttf
new file mode 100755
index 000000000..6848db0d1
--- /dev/null
+++ b/app/fonts/Lato/Lato-Black.ttf
Binary files differ
diff --git a/app/fonts/Lato/Lato-BlackItalic.ttf b/app/fonts/Lato/Lato-BlackItalic.ttf
new file mode 100755
index 000000000..5decf1297
--- /dev/null
+++ b/app/fonts/Lato/Lato-BlackItalic.ttf
Binary files differ
diff --git a/app/fonts/Lato/Lato-Bold.ttf b/app/fonts/Lato/Lato-Bold.ttf
new file mode 100755
index 000000000..74343694e
--- /dev/null
+++ b/app/fonts/Lato/Lato-Bold.ttf
Binary files differ
diff --git a/app/fonts/Lato/Lato-BoldItalic.ttf b/app/fonts/Lato/Lato-BoldItalic.ttf
new file mode 100755
index 000000000..684aacf5b
--- /dev/null
+++ b/app/fonts/Lato/Lato-BoldItalic.ttf
Binary files differ
diff --git a/app/fonts/Lato/Lato-Hairline.ttf b/app/fonts/Lato/Lato-Hairline.ttf
new file mode 100755
index 000000000..288be2955
--- /dev/null
+++ b/app/fonts/Lato/Lato-Hairline.ttf
Binary files differ
diff --git a/app/fonts/Lato/Lato-HairlineItalic.ttf b/app/fonts/Lato/Lato-HairlineItalic.ttf
new file mode 100755
index 000000000..c2bfd3353
--- /dev/null
+++ b/app/fonts/Lato/Lato-HairlineItalic.ttf
Binary files differ
diff --git a/app/fonts/Lato/Lato-Italic.ttf b/app/fonts/Lato/Lato-Italic.ttf
new file mode 100755
index 000000000..3d3b7a298
--- /dev/null
+++ b/app/fonts/Lato/Lato-Italic.ttf
Binary files differ
diff --git a/app/fonts/Lato/Lato-Light.ttf b/app/fonts/Lato/Lato-Light.ttf
new file mode 100755
index 000000000..a958067a8
--- /dev/null
+++ b/app/fonts/Lato/Lato-Light.ttf
Binary files differ
diff --git a/app/fonts/Lato/Lato-LightItalic.ttf b/app/fonts/Lato/Lato-LightItalic.ttf
new file mode 100755
index 000000000..5e45ad9a6
--- /dev/null
+++ b/app/fonts/Lato/Lato-LightItalic.ttf
Binary files differ
diff --git a/app/fonts/Lato/Lato-Regular.ttf b/app/fonts/Lato/Lato-Regular.ttf
new file mode 100755
index 000000000..04ea8efb1
--- /dev/null
+++ b/app/fonts/Lato/Lato-Regular.ttf
Binary files differ
diff --git a/app/fonts/Lato/OFL.txt b/app/fonts/Lato/OFL.txt
new file mode 100755
index 000000000..dfca0da4b
--- /dev/null
+++ b/app/fonts/Lato/OFL.txt
@@ -0,0 +1,93 @@
+Copyright (c) 2010-2014 by tyPoland Lukasz Dziedzic (team@latofonts.com) with Reserved Font Name "Lato"
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/app/fonts/Roboto/Roboto-Black.ttf b/app/fonts/Roboto/Roboto-Black.ttf
new file mode 100644
index 000000000..71f01ac2b
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-Black.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-BlackItalic.ttf b/app/fonts/Roboto/Roboto-BlackItalic.ttf
new file mode 100644
index 000000000..ec309c785
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-BlackItalic.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-Bold.ttf b/app/fonts/Roboto/Roboto-Bold.ttf
new file mode 100644
index 000000000..aaf374d2c
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-Bold.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-BoldItalic.ttf b/app/fonts/Roboto/Roboto-BoldItalic.ttf
new file mode 100644
index 000000000..dcd0f8007
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-BoldItalic.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-Italic.ttf b/app/fonts/Roboto/Roboto-Italic.ttf
new file mode 100644
index 000000000..f382c6874
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-Italic.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-Light.ttf b/app/fonts/Roboto/Roboto-Light.ttf
new file mode 100644
index 000000000..664e1b2f9
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-Light.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-LightItalic.ttf b/app/fonts/Roboto/Roboto-LightItalic.ttf
new file mode 100644
index 000000000..b8f529637
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-LightItalic.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-Medium.ttf b/app/fonts/Roboto/Roboto-Medium.ttf
new file mode 100644
index 000000000..aa00de0ef
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-Medium.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-MediumItalic.ttf b/app/fonts/Roboto/Roboto-MediumItalic.ttf
new file mode 100644
index 000000000..67e25f019
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-MediumItalic.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-Regular.ttf b/app/fonts/Roboto/Roboto-Regular.ttf
new file mode 100644
index 000000000..3e6e2e761
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-Regular.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-Thin.ttf b/app/fonts/Roboto/Roboto-Thin.ttf
new file mode 100644
index 000000000..d262d1446
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-Thin.ttf
Binary files differ
diff --git a/app/fonts/Roboto/Roboto-ThinItalic.ttf b/app/fonts/Roboto/Roboto-ThinItalic.ttf
new file mode 100644
index 000000000..63e9f9718
--- /dev/null
+++ b/app/fonts/Roboto/Roboto-ThinItalic.ttf
Binary files differ
diff --git a/app/fonts/Roboto/RobotoCondensed-Bold.ttf b/app/fonts/Roboto/RobotoCondensed-Bold.ttf
new file mode 100644
index 000000000..48dd63534
--- /dev/null
+++ b/app/fonts/Roboto/RobotoCondensed-Bold.ttf
Binary files differ
diff --git a/app/fonts/Roboto/RobotoCondensed-BoldItalic.ttf b/app/fonts/Roboto/RobotoCondensed-BoldItalic.ttf
new file mode 100644
index 000000000..ad728646a
--- /dev/null
+++ b/app/fonts/Roboto/RobotoCondensed-BoldItalic.ttf
Binary files differ
diff --git a/app/fonts/Roboto/RobotoCondensed-Italic.ttf b/app/fonts/Roboto/RobotoCondensed-Italic.ttf
new file mode 100644
index 000000000..a232513d5
--- /dev/null
+++ b/app/fonts/Roboto/RobotoCondensed-Italic.ttf
Binary files differ
diff --git a/app/fonts/Roboto/RobotoCondensed-Light.ttf b/app/fonts/Roboto/RobotoCondensed-Light.ttf
new file mode 100644
index 000000000..a6e368d40
--- /dev/null
+++ b/app/fonts/Roboto/RobotoCondensed-Light.ttf
Binary files differ
diff --git a/app/fonts/Roboto/RobotoCondensed-LightItalic.ttf b/app/fonts/Roboto/RobotoCondensed-LightItalic.ttf
new file mode 100644
index 000000000..5b2b6ae08
--- /dev/null
+++ b/app/fonts/Roboto/RobotoCondensed-LightItalic.ttf
Binary files differ
diff --git a/app/fonts/Roboto/RobotoCondensed-Regular.ttf b/app/fonts/Roboto/RobotoCondensed-Regular.ttf
new file mode 100644
index 000000000..65bf32a19
--- /dev/null
+++ b/app/fonts/Roboto/RobotoCondensed-Regular.ttf
Binary files differ
diff --git a/app/home.html b/app/home.html
new file mode 100644
index 000000000..cfb4b00a0
--- /dev/null
+++ b/app/home.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1 user-scalable=no">
+ <title>MetaMask Plugin</title>
+ </head>
+ <body>
+ <div id="app-content"></div>
+ <script src="./scripts/popup.js" type="text/javascript" charset="utf-8"></script>
+ </body>
+</html>
diff --git a/app/images/.DS_Store b/app/images/.DS_Store
deleted file mode 100644
index d28ef2089..000000000
--- a/app/images/.DS_Store
+++ /dev/null
Binary files differ
diff --git a/app/images/caret-right.svg b/app/images/caret-right.svg
new file mode 100644
index 000000000..8981ac254
--- /dev/null
+++ b/app/images/caret-right.svg
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ viewBox="0 0 1000 1000" style="enable-background:new 0 0 1000 1000;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#231F20;}
+ .st1{fill:none;stroke:#000000;stroke-width:35;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10;}
+
+ .st2{fill:none;stroke:#000000;stroke-width:35;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:25,61;}
+ .st3{display:none;}
+ .st4{display:inline;}
+ .st5{fill:#EC008C;}
+ .st6{display:inline;fill:#FFF200;}
+</style>
+<g id="Layer_4">
+</g>
+<g id="Layer_1">
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <g>
+ <path class="st0" d="M380.4,756.7c-4.5,0-9-1.7-12.4-5.1c-6.8-6.8-6.8-17.9,0-24.7L594.9,500L368,273.2
+ c-6.8-6.8-6.8-17.9,0-24.7c6.8-6.8,17.9-6.8,24.7,0L632,487.6c6.8,6.8,6.8,17.9,0,24.7L392.8,751.6
+ C389.3,755,384.9,756.7,380.4,756.7z"/>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+</g>
+<g id="Layer_2" class="st3">
+</g>
+</svg>
diff --git a/app/images/check-white.svg b/app/images/check-white.svg
new file mode 100644
index 000000000..0f15667da
--- /dev/null
+++ b/app/images/check-white.svg
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="16px" height="13px" viewBox="0 0 16 13" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 47 (45396) - http://www.bohemiancoding.com/sketch -->
+ <title>check-white</title>
+ <desc>Created with Sketch.</desc>
+ <defs></defs>
+ <g id="MetaMascara-v2" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="account-dropdown-top-bar-IXD" transform="translate(-17.000000, -80.000000)" fill-rule="nonzero" fill="#FFFFFF">
+ <g id="Group-11" transform="translate(18.000000, 74.000000)">
+ <polygon id="check-white" points="4.2 15.5712828 0.714212839 12.0143571 -0.714212839 13.4142143 4.2 18.4287172 14.7142128 7.69992858 13.2857872 6.30007142"></polygon>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/app/images/coinbase logo.png b/app/images/coinbase logo.png
new file mode 100644
index 000000000..a23d7926d
--- /dev/null
+++ b/app/images/coinbase logo.png
Binary files differ
diff --git a/app/images/eth_logo.svg b/app/images/eth_logo.svg
new file mode 100644
index 000000000..894bd70dd
--- /dev/null
+++ b/app/images/eth_logo.svg
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg width="256px" height="417px" viewBox="0 0 256 417" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid">
+ <g>
+ <polygon fill="#343434" points="127.9611 0 125.1661 9.5 125.1661 285.168 127.9611 287.958 255.9231 212.32"/>
+ <polygon fill="#8C8C8C" points="127.962 0 0 212.32 127.962 287.959 127.962 154.158"/>
+ <polygon fill="#3C3C3B" points="127.9611 312.1866 126.3861 314.1066 126.3861 412.3056 127.9611 416.9066 255.9991 236.5866"/>
+ <polygon fill="#8C8C8C" points="127.962 416.9052 127.962 312.1852 0 236.5852"/>
+ <polygon fill="#141414" points="127.9611 287.9577 255.9211 212.3207 127.9611 154.1587"/>
+ <polygon fill="#393939" points="0.0009 212.3208 127.9609 287.9578 127.9609 154.1588"/>
+ </g>
+</svg> \ No newline at end of file
diff --git a/app/images/import-account.svg b/app/images/import-account.svg
new file mode 100644
index 000000000..d6a81b70c
--- /dev/null
+++ b/app/images/import-account.svg
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="15px" height="15px" viewBox="0 0 15 15" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 47 (45396) - http://www.bohemiancoding.com/sketch -->
+ <title>import-account</title>
+ <desc>Created with Sketch.</desc>
+ <defs></defs>
+ <g id="MetaMascara-v2" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="account-dropdown-top-bar-IXD" transform="translate(-25.000000, -718.000000)">
+ <g id="Group-6" transform="translate(4.000000, 646.000000)">
+ <g id="import-account" transform="translate(21.000000, 72.000000)">
+ <rect id="Rectangle-49" fill="#FFFFFF" x="0" y="13.1721326" width="14.4893459" height="1.08397642"></rect>
+ <rect id="Rectangle" fill="#FFFFFF" x="6.5860663" y="0" width="1.08397642" height="10.5377061"></rect>
+ <polyline id="Path-12" stroke="#FFFFFF" points="2.63442652 6.5860663 7.24467293 10.5377061 11.8549193 6.5860663"></polyline>
+ </g>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/app/images/info-logo.png b/app/images/info-logo.png
new file mode 100644
index 000000000..f654ed5b1
--- /dev/null
+++ b/app/images/info-logo.png
Binary files differ
diff --git a/app/images/metamask-fox.svg b/app/images/metamask-fox.svg
new file mode 100644
index 000000000..f3c24f79e
--- /dev/null
+++ b/app/images/metamask-fox.svg
@@ -0,0 +1,128 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns:ev="http://www.w3.org/2001/xml-events"
+ xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 318.6 318.6"
+ style="enable-background:new 0 0 318.6 318.6;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#161616;stroke:#161616;}
+ .st1{fill:#E4761B;stroke:#E4761B;stroke-linecap:round;stroke-linejoin:round;}
+ .st2{fill:#763D16;stroke:#763D16;stroke-linecap:round;stroke-linejoin:round;}
+ .st3{fill:#F6851B;stroke:#F6851B;stroke-linecap:round;stroke-linejoin:round;}
+ .st4{fill:#E2761B;stroke:#E2761B;stroke-linecap:round;stroke-linejoin:round;}
+ .st5{fill:#CD6116;stroke:#CD6116;stroke-linecap:round;stroke-linejoin:round;}
+ .st6{fill:#C0AD9E;stroke:#C0AD9E;stroke-linecap:round;stroke-linejoin:round;}
+ .st7{fill:#D7C1B3;stroke:#D7C1B3;stroke-linecap:round;stroke-linejoin:round;}
+ .st8{fill:#E4751F;stroke:#E4751F;stroke-linecap:round;stroke-linejoin:round;}
+ .st9{fill:#233447;stroke:#233447;stroke-linecap:round;stroke-linejoin:round;}
+ .st10{fill:#161616;stroke:#161616;stroke-linecap:round;stroke-linejoin:round;}
+</style>
+<polygon class="st0" points="277.3,145.6 272.3,142 280.3,134.7 274.2,129.9 282.2,123.8 276.9,119.8 285.3,79 272.7,41.1
+ 191.6,71.4 124.1,71.4 43,41.1 30.4,79 38.9,119.8 33.5,123.8 41.5,129.9 35.4,134.7 43.4,142 38.4,145.6 49.9,159.1 32.5,213.3
+ 48.6,268.6 105.3,253 116.3,262 138.7,277.5 177,277.5 199.4,262 210.4,253 267.1,268.6 283.3,213.3 265.8,159.1 "/>
+<g>
+ <polygon class="st1" points="105.3,253 48.6,268.6 32.5,213.3 "/>
+ <polygon class="st1" points="283.3,213.3 267.1,268.6 210.4,253 "/>
+ <polygon class="st2" points="265.8,159.1 213.5,143.8 231.8,139 "/>
+ <polygon class="st2" points="49.9,159.1 84,139 102.2,143.8 "/>
+ <polygon class="st2" points="43.4,142 41.5,129.9 84,139 "/>
+ <polygon class="st2" points="272.3,142 231.8,139 274.2,129.9 "/>
+ <polygon class="st2" points="272.3,142 265.8,159.1 231.8,139 "/>
+ <polygon class="st2" points="43.4,142 84,139 49.9,159.1 "/>
+ <polygon class="st2" points="231.8,139 276.9,119.8 274.2,129.9 "/>
+ <polygon class="st2" points="84,139 41.5,129.9 38.9,119.8 "/>
+ <polygon class="st3" points="124.1,71.4 191.6,71.4 176.5,112.5 "/>
+ <polygon class="st3" points="176.5,112.5 139.2,112.5 124.1,71.4 "/>
+ <polygon class="st2" points="276.9,119.8 231.8,139 231,87.4 "/>
+ <polygon class="st2" points="102.2,143.8 84,139 84.7,87.4 "/>
+ <polygon class="st2" points="84.7,87.4 84,139 38.9,119.8 "/>
+ <polygon class="st2" points="231,87.4 231.8,139 213.5,143.8 "/>
+ <polygon class="st1" points="139.2,112.5 43,41.1 124.1,71.4 "/>
+ <polygon class="st4" points="272.7,41.1 176.5,112.5 191.6,71.4 "/>
+ <polygon class="st1" points="210.4,253 236.9,213.3 283.3,213.3 "/>
+ <polygon class="st1" points="32.5,213.3 78.9,213.3 105.3,253 "/>
+ <polygon class="st3" points="229.3,167.7 283.3,213.3 236.9,213.3 "/>
+ <polygon class="st3" points="86.4,167.7 32.5,213.3 49.9,159.1 "/>
+ <polygon class="st3" points="78.9,213.3 32.5,213.3 86.4,167.7 "/>
+ <polygon class="st3" points="229.3,167.7 265.8,159.1 283.3,213.3 "/>
+ <polygon class="st2" points="84.7,87.4 139.2,112.5 102.2,143.8 "/>
+ <polygon class="st2" points="213.5,143.8 176.5,112.5 231,87.4 "/>
+ <polygon class="st2" points="265.8,159.1 272.3,142 277.3,145.6 "/>
+ <polygon class="st2" points="49.9,159.1 38.4,145.6 43.4,142 "/>
+ <polygon class="st2" points="272.3,142 274.2,129.9 280.3,134.7 "/>
+ <polygon class="st2" points="43.4,142 35.4,134.7 41.5,129.9 "/>
+ <polygon class="st2" points="33.5,123.8 38.9,119.8 41.5,129.9 "/>
+ <polygon class="st2" points="282.2,123.8 274.2,129.9 276.9,119.8 "/>
+ <polygon class="st3" points="49.9,159.1 102.2,143.8 86.4,167.7 "/>
+ <polygon class="st3" points="265.8,159.1 229.3,167.7 213.5,143.8 "/>
+ <polygon class="st2" points="38.9,119.8 30.4,79 84.7,87.4 "/>
+ <polygon class="st2" points="231,87.4 285.3,79 276.9,119.8 "/>
+ <polygon class="st1" points="102.2,143.8 139.2,112.5 142.6,170.2 "/>
+ <polygon class="st1" points="213.5,143.8 229.3,167.7 173.1,170.2 "/>
+ <polygon class="st1" points="173.1,170.2 176.5,112.5 213.5,143.8 "/>
+ <polygon class="st1" points="142.6,170.2 86.4,167.7 102.2,143.8 "/>
+ <polygon class="st2" points="272.7,41.1 285.3,79 231,87.4 "/>
+ <polygon class="st2" points="43,41.1 139.2,112.5 84.7,87.4 "/>
+ <polygon class="st2" points="231,87.4 176.5,112.5 272.7,41.1 "/>
+ <polygon class="st2" points="84.7,87.4 30.4,79 43,41.1 "/>
+ <polygon class="st5" points="105.3,253 78.9,213.3 110,213.7 "/>
+ <polygon class="st5" points="210.4,253 205.7,213.7 236.9,213.3 "/>
+ <polygon class="st3" points="173.1,170.2 142.6,170.2 139.2,112.5 "/>
+ <polygon class="st3" points="139.2,112.5 176.5,112.5 173.1,170.2 "/>
+ <polygon class="st6" points="116.3,262 105.3,253 136.8,267.9 "/>
+ <polygon class="st6" points="178.9,267.9 210.4,253 199.4,262 "/>
+ <polygon class="st7" points="136.6,258.6 136.8,267.9 105.3,253 "/>
+ <polygon class="st7" points="179.2,258.6 210.4,253 178.9,267.9 "/>
+ <polygon class="st3" points="86.4,167.7 110,213.7 78.9,213.3 "/>
+ <polygon class="st3" points="236.9,213.3 205.7,213.7 229.3,167.7 "/>
+ <polygon class="st8" points="86.4,167.7 109.2,190.8 110,213.7 "/>
+ <polygon class="st8" points="229.3,167.7 205.7,213.7 206.6,190.8 "/>
+ <polygon class="st7" points="105.3,253 139.2,236.5 136.6,258.6 "/>
+ <polygon class="st7" points="210.4,253 179.2,258.6 176.5,236.5 "/>
+ <polygon class="st1" points="139.2,236.5 105.3,253 110,213.7 "/>
+ <polygon class="st1" points="176.5,236.5 205.7,213.7 210.4,253 "/>
+ <polygon class="st5" points="173.1,170.2 229.3,167.7 206.6,190.8 "/>
+ <polygon class="st5" points="109.2,190.8 86.4,167.7 142.6,170.2 "/>
+ <polygon class="st5" points="142.6,170.2 129.1,181.7 109.2,190.8 "/>
+ <polygon class="st5" points="206.6,190.8 186.6,181.7 173.1,170.2 "/>
+ <polygon class="st3" points="205.7,213.7 178.3,199.1 206.6,190.8 "/>
+ <polygon class="st3" points="110,213.7 109.2,190.8 137.4,199.1 "/>
+ <polygon class="st9" points="137.4,199.1 109.2,190.8 129.1,181.7 "/>
+ <polygon class="st9" points="178.3,199.1 186.6,181.7 206.6,190.8 "/>
+ <polygon class="st5" points="186.6,181.7 178.3,199.1 173.1,170.2 "/>
+ <polygon class="st5" points="129.1,181.7 142.6,170.2 137.4,199.1 "/>
+ <polygon class="st6" points="199.4,262 177,277.5 178.9,267.9 "/>
+ <polygon class="st6" points="136.8,267.9 138.7,277.5 116.3,262 "/>
+ <polygon class="st4" points="178.3,199.1 171.8,188.4 173.1,170.2 "/>
+ <polygon class="st8" points="137.4,199.1 142.6,170.2 143.9,188.4 "/>
+ <polygon class="st3" points="173.1,170.2 171.8,188.4 143.9,188.4 "/>
+ <polygon class="st3" points="143.9,188.4 142.6,170.2 173.1,170.2 "/>
+ <polygon class="st3" points="178.3,199.1 205.7,213.7 176.5,236.5 "/>
+ <polygon class="st3" points="139.2,236.5 110,213.7 137.4,199.1 "/>
+ <polygon class="st3" points="137.4,199.1 144,233.2 139.2,236.5 "/>
+ <polygon class="st3" points="176.5,236.5 171.7,233.2 178.3,199.1 "/>
+ <polygon class="st8" points="171.8,188.4 178.3,199.1 171.7,233.2 "/>
+ <polygon class="st8" points="143.9,188.4 144,233.2 137.4,199.1 "/>
+ <polygon class="st3" points="143.9,188.4 171.8,188.4 171.7,233.2 "/>
+ <polygon class="st3" points="171.7,233.2 144,233.2 143.9,188.4 "/>
+ <polygon class="st6" points="179.2,258.6 178.9,267.9 177,277.5 "/>
+ <polygon class="st6" points="138.7,277.5 136.8,267.9 136.6,258.6 "/>
+ <polygon class="st6" points="136.6,258.6 139,256.4 138.7,277.5 "/>
+ <polygon class="st6" points="177,277.5 176.7,256.4 179.2,258.6 "/>
+ <polygon class="st6" points="138.7,277.5 139,256.4 176.7,256.4 "/>
+ <polygon class="st6" points="176.7,256.4 177,277.5 138.7,277.5 "/>
+ <polygon class="st10" points="176.5,236.5 179.2,258.6 176.7,256.4 "/>
+ <polygon class="st10" points="139,256.4 136.6,258.6 139.2,236.5 "/>
+ <polygon class="st10" points="139.2,236.5 140.7,241.2 139,256.4 "/>
+ <polygon class="st10" points="176.7,256.4 175,241.2 176.5,236.5 "/>
+ <polygon class="st10" points="143.7,237.7 140.7,241.2 139.2,236.5 "/>
+ <polygon class="st10" points="176.5,236.5 175,241.2 172,237.7 "/>
+ <polygon class="st10" points="172,237.7 171.7,233.2 176.5,236.5 "/>
+ <polygon class="st10" points="139.2,236.5 144,233.2 143.7,237.7 "/>
+ <polygon class="st10" points="171.7,233.2 172,237.7 143.7,237.7 "/>
+ <polygon class="st10" points="143.7,237.7 144,233.2 171.7,233.2 "/>
+ <polygon class="st10" points="140.7,241.2 175,241.2 176.7,256.4 "/>
+ <polygon class="st10" points="176.7,256.4 139,256.4 140.7,241.2 "/>
+ <polygon class="st10" points="140.7,241.2 143.7,237.7 172,237.7 "/>
+ <polygon class="st10" points="172,237.7 175,241.2 140.7,241.2 "/>
+</g>
+</svg>
diff --git a/app/images/mm-bolt.svg b/app/images/mm-bolt.svg
new file mode 100644
index 000000000..bbf0abcc7
--- /dev/null
+++ b/app/images/mm-bolt.svg
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 21.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ viewBox="0 0 252 251.7" style="enable-background:new 0 0 252 251.7;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#757575;}
+</style>
+<path class="st0" d="M211.3,103.9h-60.7c-2,0-3.6-1.6-3.6-3.6V3.6c0-3.5-4.5-5-6.6-2.2l-102.7,140c-1.8,2.4,0,5.8,2.9,5.8h60.7
+ c2,0,3.6,1.6,3.6,3.6v96.6c0,3.5,4.5,5,6.6,2.2l102.7-140C216,107.3,214.3,103.9,211.3,103.9z"/>
+</svg>
diff --git a/app/images/mm-info-icon.svg b/app/images/mm-info-icon.svg
new file mode 100644
index 000000000..825f0f200
--- /dev/null
+++ b/app/images/mm-info-icon.svg
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 21.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ viewBox="0 0 10 10" style="enable-background:new 0 0 10 10;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#B8B8B8;}
+</style>
+<path class="st0" d="M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0z M5,2c0.4,0,0.7,0.3,0.7,0.7c0,0.4-0.3,0.7-0.7,0.7
+ S4.3,3.2,4.3,2.8C4.3,2.4,4.6,2,5,2z M5.7,8H4.3V4.3h1.5V8z"/>
+</svg>
diff --git a/app/images/open.svg b/app/images/open.svg
new file mode 100644
index 000000000..2957ce43d
--- /dev/null
+++ b/app/images/open.svg
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="28px" height="28px" viewBox="0 0 28 28" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 47.1 (45422) - http://www.bohemiancoding.com/sketch -->
+ <title>open</title>
+ <desc>Created with Sketch.</desc>
+ <defs></defs>
+ <g id="Mobile-screens" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="MetaMascara-Mobile---structured" transform="translate(-329.000000, -93.000000)">
+ <g id="open" transform="translate(330.000000, 94.000000)">
+ <path d="M26,13 C26,20.1799 20.1799,26 13,26 C5.8201,26 0,20.1799 0,13 C0,5.8201 5.8201,0 13,0 C20.1799,0 26,5.8201 26,13 Z" id="Stroke-3" stroke="#4A4A4A"></path>
+ <path d="M6,17 C6,17 7.78735344,10.8360387 13.7616996,10.8360387 L13.7616996,8 L19,12.3733433 L13.7616996,17 L13.7616996,14.1639613 C13.7616996,14.1639613 9.54083576,13.4629933 6,17" id="Fill-5" fill="#4A4A4A"></path>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/app/images/plus-btn-white.svg b/app/images/plus-btn-white.svg
new file mode 100644
index 000000000..2672d39dd
--- /dev/null
+++ b/app/images/plus-btn-white.svg
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="16px" height="16px" viewBox="0 0 16 16" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 47 (45396) - http://www.bohemiancoding.com/sketch -->
+ <title>plus-btn-white</title>
+ <desc>Created with Sketch.</desc>
+ <defs></defs>
+ <g id="MetaMascara-v2" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="account-dropdown-top-bar-IXD" transform="translate(-24.000000, -669.000000)" fill="#FFFFFF">
+ <g id="Group-6" transform="translate(4.000000, 646.000000)">
+ <g id="plus-btn-white" transform="translate(20.000000, 23.000000)">
+ <rect id="Rectangle-48" x="7.38461538" y="0" width="1.23076923" height="16"></rect>
+ <rect id="Rectangle-48" transform="translate(8.000000, 8.000000) rotate(-90.000000) translate(-8.000000, -8.000000) " x="7.38461538" y="0" width="1.23076923" height="16"></rect>
+ </g>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/app/images/popout.svg b/app/images/popout.svg
new file mode 100644
index 000000000..760fe4379
--- /dev/null
+++ b/app/images/popout.svg
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="22px" height="22px" viewBox="0 0 22 22" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 48.2 (47327) - http://www.bohemiancoding.com/sketch -->
+ <title>popout</title>
+ <desc>Created with Sketch.</desc>
+ <defs>
+ <polygon id="path-1" points="-0.00035 0 10.9999 0 10.9999 10.9997 -0.00035 10.9997"></polygon>
+ </defs>
+ <g id="MetaMascara-Mobile---structured-TOKEN" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" transform="translate(-327.000000, -96.000000)">
+ <g id="popout" transform="translate(327.000000, 96.000000)">
+ <g id="Group-3" transform="translate(11.000000, 0.000000)">
+ <mask id="mask-2" fill="white">
+ <use xlink:href="#path-1"></use>
+ </mask>
+ <g id="Clip-2"></g>
+ <path d="M10.9229,0.6177 C10.8209,0.3737 10.6269,0.1787 10.3819,0.0767 C10.2599,0.0267 10.1309,-0.0003 9.9999,-0.0003 L3.9999,-0.0003 C3.4479,-0.0003 2.9999,0.4477 2.9999,0.9997 C2.9999,1.5527 3.4479,1.9997 3.9999,1.9997 L7.5859,1.9997 L0.2929,9.2927 C-0.0981,9.6837 -0.0981,10.3167 0.2929,10.7067 C0.4879,10.9027 0.7439,10.9997 0.9999,10.9997 C1.2559,10.9997 1.5119,10.9027 1.7069,10.7067 L8.9999,3.4137 L8.9999,6.9997 C8.9999,7.5527 9.4479,7.9997 9.9999,7.9997 C10.5519,7.9997 10.9999,7.5527 10.9999,6.9997 L10.9999,0.9997 C10.9999,0.8697 10.9739,0.7407 10.9229,0.6177" id="Fill-1" fill="#4A4A4A" mask="url(#mask-2)"></path>
+ </g>
+ <path d="M19,10 C18.448,10 18,10.448 18,11 L18,19 C18,19.551 17.551,20 17,20 L3,20 C2.449,20 2,19.551 2,19 L2,5 C2,4.449 2.449,4 3,4 L11,4 C11.552,4 12,3.552 12,3 C12,2.448 11.552,2 11,2 L3,2 C1.346,2 0,3.346 0,5 L0,19 C0,20.654 1.346,22 3,22 L17,22 C18.654,22 20,20.654 20,19 L20,11 C20,10.448 19.552,10 19,10" id="Fill-4" fill="#4A4A4A"></path>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/app/images/settings.svg b/app/images/settings.svg
index fe61320a5..cf9b298dd 100644
--- a/app/images/settings.svg
+++ b/app/images/settings.svg
@@ -1,24 +1,22 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
-<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
- width="24.088px" height="24px" viewBox="0 0 24.088 24" enable-background="new 0 0 24.088 24" xml:space="preserve">
-<path d="M21.525,10.147c-0.41-0.059-0.847-0.428-0.974-0.82l-0.608-1.481c-0.191-0.365-0.146-0.935,0.1-1.264l0.99-1.318
- c0.246-0.33,0.227-0.854-0.047-1.162l-1.084-1.086c-0.31-0.272-0.832-0.293-1.164-0.045l-1.316,0.988
- c-0.33,0.248-0.898,0.293-1.264,0.101l-1.48-0.609c-0.395-0.126-0.764-0.562-0.82-0.971l-0.233-1.629
- c-0.058-0.409-0.44-0.778-0.851-0.822c0,0-0.254-0.026-0.77-0.026c-0.514,0-0.77,0.026-0.77,0.026
- c-0.41,0.044-0.793,0.413-0.852,0.822L10.15,2.48c-0.059,0.409-0.428,0.845-0.82,0.971L7.85,4.06
- C7.484,4.251,6.916,4.207,6.586,3.959L5.268,2.97c-0.33-0.248-0.854-0.228-1.162,0.045L3.021,4.101
- C2.749,4.41,2.727,4.933,2.975,5.263l0.988,1.318c0.249,0.33,0.293,0.899,0.102,1.264l-0.61,1.482
- c-0.125,0.393-0.562,0.762-0.972,0.82l-1.629,0.231c-0.408,0.059-0.776,0.442-0.82,0.853c0,0-0.026,0.255-0.026,0.77
- c0,0.516,0.026,0.77,0.026,0.77c0.044,0.412,0.412,0.793,0.82,0.853l1.629,0.231c0.408,0.06,0.847,0.429,0.972,0.82l0.61,1.48
- c0.191,0.365,0.146,0.936-0.102,1.264l-0.988,1.318c-0.248,0.33-0.308,0.779-0.132,0.994c0.175,0.217,0.677,0.752,0.679,0.754
- c0,0.002,0.17,0.156,0.375,0.344c0.203,0.188,1.041,0.449,1.371,0.203l1.317-0.99c0.33-0.246,0.897-0.293,1.265-0.1l1.479,0.608
- c0.394,0.125,0.763,0.562,0.819,0.972l0.233,1.629c0.058,0.408,0.44,0.779,0.853,0.822c0,0,0.254,0.026,0.769,0.026
- s0.771-0.026,0.771-0.026c0.408-0.043,0.793-0.414,0.85-0.822l0.234-1.629c0.057-0.408,0.426-0.847,0.819-0.972l1.479-0.61
- c0.365-0.191,0.935-0.146,1.265,0.102l1.317,0.99c0.332,0.246,0.854,0.227,1.164-0.047l1.082-1.084
- c0.273-0.312,0.293-0.834,0.047-1.164l-0.989-1.318c-0.246-0.328-0.291-0.898-0.101-1.264l0.609-1.48
- c0.127-0.393,0.562-0.762,0.973-0.82l1.627-0.231c0.41-0.06,0.779-0.44,0.822-0.853c0,0,0.027-0.254,0.027-0.77
- c0-0.515-0.027-0.77-0.027-0.77c-0.043-0.41-0.412-0.794-0.822-0.853L21.525,10.147z M12.004,15.001c-1.657,0-3-1.344-3-3
- c0-1.657,1.343-3,3-3s3,1.344,3,3S13.66,15.001,12.004,15.001z"/>
-</svg>
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="20px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 47 (45396) - http://www.bohemiancoding.com/sketch -->
+ <title>settings</title>
+ <desc>Created with Sketch.</desc>
+ <defs>
+ <polygon id="path-1" points="20 10 20 19.9998 0 19.9998 0 10 0 0.0002 20 0.0002"></polygon>
+ </defs>
+ <g id="MetaMascara-v2" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="account-dropdown-top-bar-IXD" transform="translate(-25.000000, -826.000000)">
+ <g id="Group-6" transform="translate(4.000000, 646.000000)">
+ <g id="settings" transform="translate(21.000000, 180.000000)">
+ <mask id="mask-2" fill="white">
+ <use xlink:href="#path-1"></use>
+ </mask>
+ <g id="Clip-2"></g>
+ <path d="M10,13.6602 C7.979,13.6602 6.34,12.0212 6.34,10.0002 C6.34,7.9782 7.979,6.3402 10,6.3402 C12.021,6.3402 13.66,7.9782 13.66,10.0002 C13.66,12.0212 12.021,13.6602 10,13.6602 L10,13.6602 Z M19.157,11.8112 C19.53,11.8112 19.878,11.5092 19.929,11.1392 C19.929,11.1392 20,10.6182 20,10.0002 C20,9.3822 19.929,8.8622 19.929,8.8622 C19.878,8.4922 19.53,8.1892 19.157,8.1892 L17.228,8.1892 C16.854,8.1892 16.466,7.9512 16.365,7.6602 C16.265,7.3682 16.127,6.4352 16.391,6.1712 L17.755,4.8072 C18.019,4.5432 18.039,4.0922 17.8,3.8052 L16.195,2.2002 C15.908,1.9602 15.458,1.9812 15.193,2.2452 L13.829,3.6092 C13.565,3.8732 13.125,3.9802 12.852,3.8462 C12.578,3.7122 11.812,3.1462 11.812,2.7732 L11.812,0.8432 C11.812,0.4702 11.509,0.1222 11.139,0.0722 C11.139,0.0722 10.619,0.0002 10,0.0002 C9.382,0.0002 8.862,0.0722 8.862,0.0722 C8.492,0.1222 8.189,0.4702 8.189,0.8432 L8.189,2.7732 C8.189,3.1462 7.951,3.5352 7.66,3.6352 C7.369,3.7352 6.435,3.8732 6.171,3.6092 L4.807,2.2452 C4.542,1.9812 4.092,1.9612 3.805,2.2002 L2.2,3.8052 C1.96,4.0922 1.981,4.5432 2.245,4.8072 L3.609,6.1712 C3.873,6.4352 3.98,6.8752 3.846,7.1482 C3.711,7.4222 3.146,8.1892 2.773,8.1892 L0.843,8.1892 C0.47,8.1892 0.123,8.4922 0.072,8.8622 C0.072,8.8622 0,9.3822 0,10.0002 C0,10.6182 0.072,11.1392 0.072,11.1392 C0.123,11.5092 0.47,11.8112 0.843,11.8112 L2.773,11.8112 C3.146,11.8112 3.535,12.0502 3.635,12.3412 C3.735,12.6322 3.874,13.5642 3.609,13.8292 L2.246,15.1932 C1.981,15.4572 1.961,15.9082 2.2,16.1952 L3.805,17.8002 C4.092,18.0392 4.542,18.0192 4.807,17.7552 L6.171,16.3902 C6.435,16.1272 6.875,16.0202 7.148,16.1542 C7.422,16.2882 8.189,16.8532 8.189,17.2272 L8.189,19.1572 C8.189,19.5302 8.492,19.8782 8.862,19.9292 C8.862,19.9292 9.382,20.0002 10,20.0002 C10.619,20.0002 11.139,19.9292 11.139,19.9292 C11.509,19.8772 11.812,19.5302 11.812,19.1572 L11.812,17.2272 C11.812,16.8532 12.05,16.4662 12.341,16.3652 C12.632,16.2642 13.565,16.1272 13.829,16.3902 L15.193,17.7552 C15.458,18.0182 15.908,18.0392 16.195,17.8002 L17.8,16.1952 C18.039,15.9082 18.02,15.4582 17.755,15.1932 L16.391,13.8292 C16.127,13.5652 16.021,13.1252 16.154,12.8512 C16.288,12.5782 16.854,11.8112 17.228,11.8112 L19.157,11.8112 Z" id="Fill-1" fill="#B3B3B3" mask="url(#mask-2)"></path>
+ </g>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/app/images/shapeshift logo.png b/app/images/shapeshift logo.png
new file mode 100644
index 000000000..ac8faba5b
--- /dev/null
+++ b/app/images/shapeshift logo.png
Binary files differ
diff --git a/app/manifest.json b/app/manifest.json
index a3242149b..eab6c7063 100644
--- a/app/manifest.json
+++ b/app/manifest.json
@@ -1,7 +1,7 @@
{
"name": "MetaMask",
"short_name": "Metamask",
- "version": "3.5.2",
+ "version": "4.1.0",
"manifest_version": 2,
"author": "https://metamask.io",
"description": "Ethereum Browser Extension",
@@ -58,8 +58,8 @@
"storage",
"clipboardWrite",
"http://localhost:8545/",
- "https://www.cryptonator.com/"
- ],
+ "https://*.infura.io/"
+ ],
"web_accessible_resources": [
"scripts/inpage.js"
],
diff --git a/app/notification.html b/app/notification.html
index cc485da7f..f10cbbf41 100644
--- a/app/notification.html
+++ b/app/notification.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html>
+<html style="height:600px;">
<head>
<meta charset="utf-8">
<title>MetaMask Notification</title>
@@ -9,7 +9,7 @@
}
</style>
</head>
- <body>
+ <body class="notification" style="height:600px;">
<div id="app-content"></div>
<script src="./scripts/popup.js" type="text/javascript" charset="utf-8"></script>
</body>
diff --git a/app/popup.html b/app/popup.html
index 6d85a9811..bf09b97ca 100644
--- a/app/popup.html
+++ b/app/popup.html
@@ -1,11 +1,12 @@
<!doctype html>
-<html>
+<html style="width:357px; height:600px;">
<head>
<meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1 user-scalable=no">
<title>MetaMask Plugin</title>
</head>
- <body>
+ <body style="width:357px; height:600px;">
<div id="app-content"></div>
<script src="./scripts/popup.js" type="text/javascript" charset="utf-8"></script>
</body>
-</html> \ No newline at end of file
+</html>
diff --git a/app/scripts/account-import-strategies/index.js b/app/scripts/account-import-strategies/index.js
index d5124eb7f..96e2b5912 100644
--- a/app/scripts/account-import-strategies/index.js
+++ b/app/scripts/account-import-strategies/index.js
@@ -4,7 +4,7 @@ const ethUtil = require('ethereumjs-util')
const accountImporter = {
- importAccount(strategy, args) {
+ importAccount (strategy, args) {
try {
const importer = this.strategies[strategy]
const privateKeyHex = importer.apply(null, args)
diff --git a/app/scripts/background.js b/app/scripts/background.js
index 7211f1e0c..476d073d1 100644
--- a/app/scripts/background.js
+++ b/app/scripts/background.js
@@ -1,22 +1,24 @@
const urlUtil = require('url')
const endOfStream = require('end-of-stream')
-const asyncQ = require('async-q')
-const pipe = require('pump')
+const pump = require('pump')
+const log = require('loglevel')
+const extension = require('extensionizer')
const LocalStorageStore = require('obs-store/lib/localStorage')
const storeTransform = require('obs-store/lib/transform')
+const asStream = require('obs-store/lib/asStream')
const ExtensionPlatform = require('./platforms/extension')
const Migrator = require('./lib/migrator/')
const migrations = require('./migrations/')
const PortStream = require('./lib/port-stream.js')
const NotificationManager = require('./lib/notification-manager.js')
const MetamaskController = require('./metamask-controller')
-const extension = require('extensionizer')
const firstTimeState = require('./first-time-state')
+const setupRaven = require('./setupRaven')
+const setupMetamaskMeshMetrics = require('./lib/setupMetamaskMeshMetrics')
const STORAGE_KEY = 'metamask-config'
const METAMASK_DEBUG = 'GULP_METAMASK_DEBUG'
-const log = require('loglevel')
window.log = log
log.setDefaultLevel(METAMASK_DEBUG ? 'debug' : 'warn')
@@ -24,44 +26,46 @@ const platform = new ExtensionPlatform()
const notificationManager = new NotificationManager()
global.METAMASK_NOTIFIER = notificationManager
+// setup sentry error reporting
+const release = platform.getVersion()
+const raven = setupRaven({ release })
+
let popupIsOpen = false
+let openMetamaskTabsIDs = {}
// state persistence
const diskStore = new LocalStorageStore({ storageKey: STORAGE_KEY })
// initialization flow
-asyncQ.waterfall([
- () => loadStateFromPersistence(),
- (initState) => setupController(initState),
-])
-.then(() => console.log('MetaMask initialization complete.'))
-.catch((err) => { console.error(err) })
+initialize().catch(log.error)
+
+// setup metamask mesh testing container
+setupMetamaskMeshMetrics()
+
+async function initialize () {
+ const initState = await loadStateFromPersistence()
+ await setupController(initState)
+ log.debug('MetaMask initialization complete.')
+}
//
// State and Persistence
//
-function loadStateFromPersistence() {
+async function loadStateFromPersistence () {
// migrations
- let migrator = new Migrator({ migrations })
- let initialState = migrator.generateInitialState(firstTimeState)
- return asyncQ.waterfall([
- // read from disk
- () => Promise.resolve(diskStore.getState() || initialState),
- // migrate data
- (versionedData) => migrator.migrateData(versionedData),
- // write to disk
- (versionedData) => {
- diskStore.putState(versionedData)
- return Promise.resolve(versionedData)
- },
- // resolve to just data
- (versionedData) => Promise.resolve(versionedData.data),
- ])
+ const migrator = new Migrator({ migrations })
+ // read from disk
+ let versionedData = diskStore.getState() || migrator.generateInitialState(firstTimeState)
+ // migrate data
+ versionedData = await migrator.migrateData(versionedData)
+ // write to disk
+ diskStore.putState(versionedData)
+ // return just the data
+ return versionedData.data
}
function setupController (initState) {
-
//
// MetaMask Controller
//
@@ -78,15 +82,26 @@ function setupController (initState) {
})
global.metamaskController = controller
+ // report failed transactions to Sentry
+ controller.txController.on(`tx:status-update`, (txId, status) => {
+ if (status !== 'failed') return
+ const txMeta = controller.txController.txStateManager.getTx(txId)
+ const errorMessage = `Transaction Failed: ${txMeta.err.message}`
+ raven.captureMessage(errorMessage, {
+ // "extra" key is required by Sentry
+ extra: txMeta,
+ })
+ })
+
// setup state persistence
- pipe(
- controller.store,
+ pump(
+ asStream(controller.store),
storeTransform(versionifyData),
- diskStore
+ asStream(diskStore)
)
- function versionifyData(state) {
- let versionedData = diskStore.getState()
+ function versionifyData (state) {
+ const versionedData = diskStore.getState()
versionedData.data = state
return versionedData
}
@@ -97,21 +112,27 @@ function setupController (initState) {
extension.runtime.onConnect.addListener(connectRemote)
function connectRemote (remotePort) {
- var isMetaMaskInternalProcess = remotePort.name === 'popup' || remotePort.name === 'notification'
- var portStream = new PortStream(remotePort)
+ const isMetaMaskInternalProcess = remotePort.name === 'popup' || remotePort.name === 'notification'
+ const portStream = new PortStream(remotePort)
if (isMetaMaskInternalProcess) {
// communication with popup
popupIsOpen = popupIsOpen || (remotePort.name === 'popup')
- controller.setupTrustedCommunication(portStream, 'MetaMask', remotePort.name)
+ controller.setupTrustedCommunication(portStream, 'MetaMask')
// record popup as closed
+ if (remotePort.sender.url.match(/home.html$/)) {
+ openMetamaskTabsIDs[remotePort.sender.tab.id] = true
+ }
if (remotePort.name === 'popup') {
endOfStream(portStream, () => {
popupIsOpen = false
+ if (remotePort.sender.url.match(/home.html$/)) {
+ openMetamaskTabsIDs[remotePort.sender.tab.id] = false
+ }
})
}
} else {
// communication with page
- var originDomain = urlUtil.parse(remotePort.sender.url).hostname
+ const originDomain = urlUtil.parse(remotePort.sender.url).hostname
controller.setupUntrustedCommunication(portStream, originDomain)
}
}
@@ -121,15 +142,18 @@ function setupController (initState) {
//
updateBadge()
- controller.txManager.on('updateBadge', updateBadge)
+ controller.txController.on('update:badge', updateBadge)
controller.messageManager.on('updateBadge', updateBadge)
+ controller.personalMessageManager.on('updateBadge', updateBadge)
// plugin badge text
function updateBadge () {
var label = ''
- var unapprovedTxCount = controller.txManager.unapprovedTxCount
+ var unapprovedTxCount = controller.txController.getUnapprovedTxCount()
var unapprovedMsgCount = controller.messageManager.unapprovedMsgCount
- var count = unapprovedTxCount + unapprovedMsgCount
+ var unapprovedPersonalMsgs = controller.personalMessageManager.unapprovedPersonalMsgCount
+ var unapprovedTypedMsgs = controller.typedMessageManager.unapprovedTypedMessagesCount
+ var count = unapprovedTxCount + unapprovedMsgCount + unapprovedPersonalMsgs + unapprovedTypedMsgs
if (count) {
label = String(count)
}
@@ -138,7 +162,6 @@ function setupController (initState) {
}
return Promise.resolve()
-
}
//
@@ -147,7 +170,10 @@ function setupController (initState) {
// popup trigger
function triggerUi () {
- if (!popupIsOpen) notificationManager.showPopup()
+ extension.tabs.query({ active: true }, (tabs) => {
+ const currentlyActiveMetamaskTab = tabs.find(tab => openMetamaskTabsIDs[tab.id])
+ if (!popupIsOpen && !currentlyActiveMetamaskTab) notificationManager.showPopup()
+ })
}
// On first install, open a window to MetaMask website to how-it-works.
diff --git a/app/scripts/config.js b/app/scripts/config.js
index ec421744d..74c5b576e 100644
--- a/app/scripts/config.js
+++ b/app/scripts/config.js
@@ -1,16 +1,44 @@
const MAINET_RPC_URL = 'https://mainnet.infura.io/metamask'
-const TESTNET_RPC_URL = 'https://ropsten.infura.io/metamask'
+const ROPSTEN_RPC_URL = 'https://ropsten.infura.io/metamask'
const KOVAN_RPC_URL = 'https://kovan.infura.io/metamask'
-const DEFAULT_RPC_URL = TESTNET_RPC_URL
+const RINKEBY_RPC_URL = 'https://rinkeby.infura.io/metamask'
+const LOCALHOST_RPC_URL = 'http://localhost:8545'
+
+const MAINET_RPC_URL_BETA = 'https://mainnet.infura.io/metamask2'
+const ROPSTEN_RPC_URL_BETA = 'https://ropsten.infura.io/metamask2'
+const KOVAN_RPC_URL_BETA = 'https://kovan.infura.io/metamask2'
+const RINKEBY_RPC_URL_BETA = 'https://rinkeby.infura.io/metamask2'
+
+const DEFAULT_RPC = 'rinkeby'
+const OLD_UI_NETWORK_TYPE = 'network'
+const BETA_UI_NETWORK_TYPE = 'networkBeta'
global.METAMASK_DEBUG = 'GULP_METAMASK_DEBUG'
module.exports = {
network: {
- default: DEFAULT_RPC_URL,
+ localhost: LOCALHOST_RPC_URL,
mainnet: MAINET_RPC_URL,
- testnet: TESTNET_RPC_URL,
- morden: TESTNET_RPC_URL,
+ ropsten: ROPSTEN_RPC_URL,
kovan: KOVAN_RPC_URL,
+ rinkeby: RINKEBY_RPC_URL,
+ },
+ // Used for beta UI
+ networkBeta: {
+ localhost: LOCALHOST_RPC_URL,
+ mainnet: MAINET_RPC_URL_BETA,
+ ropsten: ROPSTEN_RPC_URL_BETA,
+ kovan: KOVAN_RPC_URL_BETA,
+ rinkeby: RINKEBY_RPC_URL_BETA,
+ },
+ networkNames: {
+ 3: 'Ropsten',
+ 4: 'Rinkeby',
+ 42: 'Kovan',
+ },
+ enums: {
+ DEFAULT_RPC,
+ OLD_UI_NETWORK_TYPE,
+ BETA_UI_NETWORK_TYPE,
},
}
diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js
index 4d7e682d3..2ed7c87b6 100644
--- a/app/scripts/contentscript.js
+++ b/app/scripts/contentscript.js
@@ -1,12 +1,15 @@
+const fs = require('fs')
+const path = require('path')
+const pump = require('pump')
const LocalMessageDuplexStream = require('post-message-stream')
const PongStream = require('ping-pong-stream/pong')
-const PortStream = require('./lib/port-stream.js')
-const ObjectMultiplex = require('./lib/obj-multiplex')
+const ObjectMultiplex = require('obj-multiplex')
const extension = require('extensionizer')
+const PortStream = require('./lib/port-stream.js')
-const fs = require('fs')
-const path = require('path')
-const inpageText = fs.readFileSync(path.join(__dirname, 'inpage.js')).toString()
+const inpageContent = fs.readFileSync(path.join(__dirname, '..', '..', 'dist', 'chrome', 'scripts', 'inpage.js')).toString()
+const inpageSuffix = '//# sourceURL=' + extension.extension.getURL('scripts/inpage.js') + '\n'
+const inpageBundle = inpageContent + inpageSuffix
// Eventually this streaming injection could be replaced with:
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.exportFunction
@@ -24,8 +27,7 @@ function setupInjection () {
try {
// inject in-page script
var scriptTag = document.createElement('script')
- scriptTag.src = extension.extension.getURL('scripts/inpage.js')
- scriptTag.textContent = inpageText
+ scriptTag.textContent = inpageBundle
scriptTag.onload = function () { this.parentNode.removeChild(this) }
var container = document.head || document.documentElement
// append as first child
@@ -37,35 +39,64 @@ function setupInjection () {
function setupStreams () {
// setup communication to page and plugin
- var pageStream = new LocalMessageDuplexStream({
+ const pageStream = new LocalMessageDuplexStream({
name: 'contentscript',
target: 'inpage',
})
- pageStream.on('error', console.error)
- var pluginPort = extension.runtime.connect({name: 'contentscript'})
- var pluginStream = new PortStream(pluginPort)
- pluginStream.on('error', console.error)
+ const pluginPort = extension.runtime.connect({ name: 'contentscript' })
+ const pluginStream = new PortStream(pluginPort)
// forward communication plugin->inpage
- pageStream.pipe(pluginStream).pipe(pageStream)
+ pump(
+ pageStream,
+ pluginStream,
+ pageStream,
+ (err) => logStreamDisconnectWarning('MetaMask Contentscript Forwarding', err)
+ )
// setup local multistream channels
- var mx = ObjectMultiplex()
- mx.on('error', console.error)
- mx.pipe(pageStream).pipe(mx)
+ const mux = new ObjectMultiplex()
+ mux.setMaxListeners(25)
+
+ pump(
+ mux,
+ pageStream,
+ mux,
+ (err) => logStreamDisconnectWarning('MetaMask Inpage', err)
+ )
+ pump(
+ mux,
+ pluginStream,
+ mux,
+ (err) => logStreamDisconnectWarning('MetaMask Background', err)
+ )
// connect ping stream
- var pongStream = new PongStream({ objectMode: true })
- pongStream.pipe(mx.createStream('pingpong')).pipe(pongStream)
+ const pongStream = new PongStream({ objectMode: true })
+ pump(
+ mux,
+ pongStream,
+ mux,
+ (err) => logStreamDisconnectWarning('MetaMask PingPongStream', err)
+ )
+
+ // connect phishing warning stream
+ const phishingStream = mux.createStream('phishing')
+ phishingStream.once('data', redirectToPhishingWarning)
- // ignore unused channels (handled by background)
- mx.ignoreStream('provider')
- mx.ignoreStream('publicConfig')
- mx.ignoreStream('reload')
+ // ignore unused channels (handled by background, inpage)
+ mux.ignoreStream('provider')
+ mux.ignoreStream('publicConfig')
+}
+
+function logStreamDisconnectWarning (remoteLabel, err) {
+ let warningMsg = `MetamaskContentscript - lost connection to ${remoteLabel}`
+ if (err) warningMsg += '\n' + err.stack
+ console.warn(warningMsg)
}
function shouldInjectWeb3 () {
- return doctypeCheck() || suffixCheck()
+ return doctypeCheck() && suffixCheck() && documentElementCheck()
}
function doctypeCheck () {
@@ -73,19 +104,32 @@ function doctypeCheck () {
if (doctype) {
return doctype.name === 'html'
} else {
- return false
+ return true
}
}
-function suffixCheck() {
+function suffixCheck () {
var prohibitedTypes = ['xml', 'pdf']
var currentUrl = window.location.href
var currentRegex
for (let i = 0; i < prohibitedTypes.length; i++) {
- currentRegex = new RegExp(`\.${prohibitedTypes[i]}$`)
+ currentRegex = new RegExp(`\\.${prohibitedTypes[i]}$`)
if (currentRegex.test(currentUrl)) {
return false
}
}
return true
}
+
+function documentElementCheck () {
+ var documentElement = document.documentElement.nodeName
+ if (documentElement) {
+ return documentElement.toLowerCase() === 'html'
+ }
+ return true
+}
+
+function redirectToPhishingWarning () {
+ console.log('MetaMask - redirecting to phishing warning')
+ window.location.href = 'https://metamask.io/phishing.html'
+}
diff --git a/app/scripts/controllers/address-book.js b/app/scripts/controllers/address-book.js
index c66eb2bd4..6fb4ee114 100644
--- a/app/scripts/controllers/address-book.js
+++ b/app/scripts/controllers/address-book.js
@@ -39,11 +39,11 @@ class AddressBookController {
// pushed object is an object of two fields. Current behavior does not set an
// upper limit to the number of addresses.
_addToAddressBook (address, name) {
- let addressBook = this._getAddressBook()
- let identities = this._getIdentities()
+ const addressBook = this._getAddressBook()
+ const identities = this._getIdentities()
- let addressBookIndex = addressBook.findIndex((element) => { return element.address.toLowerCase() === address.toLowerCase() || element.name === name })
- let identitiesIndex = Object.keys(identities).findIndex((element) => { return element.toLowerCase() === address.toLowerCase() })
+ 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)
diff --git a/app/scripts/controllers/balance.js b/app/scripts/controllers/balance.js
new file mode 100644
index 000000000..f83f294cc
--- /dev/null
+++ b/app/scripts/controllers/balance.js
@@ -0,0 +1,80 @@
+const ObservableStore = require('obs-store')
+const PendingBalanceCalculator = require('../lib/pending-balance-calculator')
+const BN = require('ethereumjs-util').BN
+
+class BalanceController {
+
+ constructor (opts = {}) {
+ this._validateParams(opts)
+ const { address, accountTracker, txController, blockTracker } = opts
+
+ this.address = address
+ this.accountTracker = accountTracker
+ this.txController = txController
+ this.blockTracker = blockTracker
+
+ const initState = {
+ ethBalance: undefined,
+ }
+ this.store = new ObservableStore(initState)
+
+ this.balanceCalc = new PendingBalanceCalculator({
+ getBalance: () => this._getBalance(),
+ getPendingTransactions: this._getPendingTransactions.bind(this),
+ })
+
+ this._registerUpdates()
+ }
+
+ async updateBalance () {
+ const balance = await this.balanceCalc.getBalance()
+ this.store.updateState({
+ ethBalance: balance,
+ })
+ }
+
+ _registerUpdates () {
+ const update = this.updateBalance.bind(this)
+
+ this.txController.on('tx:status-update', (txId, status) => {
+ switch (status) {
+ case 'submitted':
+ case 'confirmed':
+ case 'failed':
+ update()
+ return
+ default:
+ return
+ }
+ })
+ this.accountTracker.store.subscribe(update)
+ this.blockTracker.on('block', update)
+ }
+
+ async _getBalance () {
+ const { accounts } = this.accountTracker.store.getState()
+ const entry = accounts[this.address]
+ const balance = entry.balance
+ return balance ? new BN(balance.substring(2), 16) : undefined
+ }
+
+ async _getPendingTransactions () {
+ const pending = this.txController.getFilteredTxList({
+ from: this.address,
+ status: 'submitted',
+ err: undefined,
+ })
+ return pending
+ }
+
+ _validateParams (opts) {
+ const { address, accountTracker, txController, blockTracker } = opts
+ if (!address || !accountTracker || !txController || !blockTracker) {
+ const error = 'Cannot construct a balance checker without address, accountTracker, txController, and blockTracker.'
+ throw new Error(error)
+ }
+ }
+
+}
+
+module.exports = BalanceController
diff --git a/app/scripts/controllers/blacklist.js b/app/scripts/controllers/blacklist.js
new file mode 100644
index 000000000..33c31dab9
--- /dev/null
+++ b/app/scripts/controllers/blacklist.js
@@ -0,0 +1,60 @@
+const ObservableStore = require('obs-store')
+const extend = require('xtend')
+const PhishingDetector = require('eth-phishing-detect/src/detector')
+
+// compute phishing lists
+const PHISHING_DETECTION_CONFIG = require('eth-phishing-detect/src/config.json')
+// every four minutes
+const POLLING_INTERVAL = 4 * 60 * 1000
+
+class BlacklistController {
+
+ constructor (opts = {}) {
+ const initState = extend({
+ phishing: PHISHING_DETECTION_CONFIG,
+ }, opts.initState)
+ this.store = new ObservableStore(initState)
+ // phishing detector
+ this._phishingDetector = null
+ this._setupPhishingDetector(initState.phishing)
+ // polling references
+ this._phishingUpdateIntervalRef = null
+ }
+
+ //
+ // PUBLIC METHODS
+ //
+
+ checkForPhishing (hostname) {
+ if (!hostname) return false
+ const { result } = this._phishingDetector.check(hostname)
+ return result
+ }
+
+ async updatePhishingList () {
+ const response = await fetch('https://api.infura.io/v2/blacklist')
+ const phishing = await response.json()
+ this.store.updateState({ phishing })
+ this._setupPhishingDetector(phishing)
+ return phishing
+ }
+
+ scheduleUpdates () {
+ if (this._phishingUpdateIntervalRef) return
+ this.updatePhishingList()
+ this._phishingUpdateIntervalRef = setInterval(() => {
+ this.updatePhishingList()
+ }, POLLING_INTERVAL)
+ }
+
+ //
+ // PRIVATE METHODS
+ //
+
+ _setupPhishingDetector (config) {
+ this._phishingDetector = new PhishingDetector(config)
+ }
+}
+
+module.exports = BlacklistController
+
diff --git a/app/scripts/controllers/computed-balances.js b/app/scripts/controllers/computed-balances.js
new file mode 100644
index 000000000..907b087cf
--- /dev/null
+++ b/app/scripts/controllers/computed-balances.js
@@ -0,0 +1,77 @@
+const ObservableStore = require('obs-store')
+const extend = require('xtend')
+const BalanceController = require('./balance')
+
+class ComputedbalancesController {
+
+ constructor (opts = {}) {
+ const { accountTracker, txController, blockTracker } = opts
+ this.accountTracker = accountTracker
+ this.txController = txController
+ this.blockTracker = blockTracker
+
+ const initState = extend({
+ computedBalances: {},
+ }, opts.initState)
+ this.store = new ObservableStore(initState)
+ this.balances = {}
+
+ this._initBalanceUpdating()
+ }
+
+ updateAllBalances () {
+ Object.keys(this.balances).forEach((balance) => {
+ const address = balance.address
+ this.balances[address].updateBalance()
+ })
+ }
+
+ _initBalanceUpdating () {
+ const store = this.accountTracker.store.getState()
+ this.syncAllAccountsFromStore(store)
+ this.accountTracker.store.subscribe(this.syncAllAccountsFromStore.bind(this))
+ }
+
+ syncAllAccountsFromStore (store) {
+ const upstream = Object.keys(store.accounts)
+ const balances = Object.keys(this.balances)
+ .map(address => this.balances[address])
+
+ // Follow new addresses
+ for (const address in balances) {
+ this.trackAddressIfNotAlready(address)
+ }
+
+ // Unfollow old ones
+ balances.forEach(({ address }) => {
+ if (!upstream.includes(address)) {
+ delete this.balances[address]
+ }
+ })
+ }
+
+ trackAddressIfNotAlready (address) {
+ const state = this.store.getState()
+ if (!(address in state.computedBalances)) {
+ this.trackAddress(address)
+ }
+ }
+
+ trackAddress (address) {
+ const updater = new BalanceController({
+ address,
+ accountTracker: this.accountTracker,
+ txController: this.txController,
+ blockTracker: this.blockTracker,
+ })
+ updater.store.subscribe((accountBalance) => {
+ const newState = this.store.getState()
+ newState.computedBalances[address] = accountBalance
+ this.store.updateState(newState)
+ })
+ this.balances[address] = updater
+ updater.updateBalance()
+ }
+}
+
+module.exports = ComputedbalancesController
diff --git a/app/scripts/controllers/currency.js b/app/scripts/controllers/currency.js
index c4904f8ac..25a7a942e 100644
--- a/app/scripts/controllers/currency.js
+++ b/app/scripts/controllers/currency.js
@@ -8,7 +8,7 @@ class CurrencyController {
constructor (opts = {}) {
const initState = extend({
- currentCurrency: 'USD',
+ currentCurrency: 'usd',
conversionRate: 0,
conversionDate: 'N/A',
}, opts.initState)
@@ -45,15 +45,17 @@ class CurrencyController {
updateConversionRate () {
const currentCurrency = this.getCurrentCurrency()
- return fetch(`https://www.cryptonator.com/api/ticker/eth-${currentCurrency}`)
+ return fetch(`https://api.infura.io/v1/ticker/eth${currentCurrency.toLowerCase()}`)
.then(response => response.json())
.then((parsedResponse) => {
- this.setConversionRate(Number(parsedResponse.ticker.price))
+ this.setConversionRate(Number(parsedResponse.bid))
this.setConversionDate(Number(parsedResponse.timestamp))
}).catch((err) => {
- console.warn('MetaMask - Failed to query currency conversion.')
- this.setConversionRate(0)
- this.setConversionDate('N/A')
+ if (err) {
+ console.warn('MetaMask - Failed to query currency conversion.')
+ this.setConversionRate(0)
+ this.setConversionDate('N/A')
+ }
})
}
diff --git a/app/scripts/controllers/infura.js b/app/scripts/controllers/infura.js
new file mode 100644
index 000000000..10adb1004
--- /dev/null
+++ b/app/scripts/controllers/infura.js
@@ -0,0 +1,43 @@
+const ObservableStore = require('obs-store')
+const extend = require('xtend')
+
+// every ten minutes
+const POLLING_INTERVAL = 10 * 60 * 1000
+
+class InfuraController {
+
+ constructor (opts = {}) {
+ const initState = extend({
+ infuraNetworkStatus: {},
+ }, opts.initState)
+ this.store = new ObservableStore(initState)
+ }
+
+ //
+ // PUBLIC METHODS
+ //
+
+ // Responsible for retrieving the status of Infura's nodes. Can return either
+ // ok, degraded, or down.
+ checkInfuraNetworkStatus () {
+ return fetch('https://api.infura.io/v1/status/metamask')
+ .then(response => response.json())
+ .then((parsedResponse) => {
+ this.store.updateState({
+ infuraNetworkStatus: parsedResponse,
+ })
+ return parsedResponse
+ })
+ }
+
+ scheduleInfuraNetworkCheck () {
+ if (this.conversionInterval) {
+ clearInterval(this.conversionInterval)
+ }
+ this.conversionInterval = setInterval(() => {
+ this.checkInfuraNetworkStatus()
+ }, POLLING_INTERVAL)
+ }
+}
+
+module.exports = InfuraController
diff --git a/app/scripts/controllers/network.js b/app/scripts/controllers/network.js
new file mode 100644
index 000000000..617456cd7
--- /dev/null
+++ b/app/scripts/controllers/network.js
@@ -0,0 +1,214 @@
+const assert = require('assert')
+const EventEmitter = require('events')
+const createMetamaskProvider = require('web3-provider-engine/zero.js')
+const SubproviderFromProvider = require('web3-provider-engine/subproviders/web3.js')
+const createInfuraProvider = require('eth-json-rpc-infura/src/createProvider')
+const ObservableStore = require('obs-store')
+const ComposedStore = require('obs-store/lib/composed')
+const extend = require('xtend')
+const EthQuery = require('eth-query')
+const createEventEmitterProxy = require('../lib/events-proxy.js')
+const networkConfig = require('../config.js')
+const { OLD_UI_NETWORK_TYPE, DEFAULT_RPC } = networkConfig.enums
+const INFURA_PROVIDER_TYPES = ['ropsten', 'rinkeby', 'kovan', 'mainnet']
+
+module.exports = class NetworkController extends EventEmitter {
+
+ constructor (config) {
+ super()
+
+ this._networkEndpointVersion = OLD_UI_NETWORK_TYPE
+ this._networkEndpoints = this.getNetworkEndpoints(OLD_UI_NETWORK_TYPE)
+ this._defaultRpc = this._networkEndpoints[DEFAULT_RPC]
+
+ config.provider.rpcTarget = this.getRpcAddressForType(config.provider.type, config.provider)
+ this.networkStore = new ObservableStore('loading')
+ this.providerStore = new ObservableStore(config.provider)
+ this.store = new ComposedStore({ provider: this.providerStore, network: this.networkStore })
+ this._proxy = createEventEmitterProxy()
+
+ this.on('networkDidChange', this.lookupNetwork)
+ }
+
+ async setNetworkEndpoints (version) {
+ if (version === this._networkEndpointVersion) {
+ return
+ }
+
+ this._networkEndpointVersion = version
+ this._networkEndpoints = this.getNetworkEndpoints(version)
+ this._defaultRpc = this._networkEndpoints[DEFAULT_RPC]
+ const { type } = this.getProviderConfig()
+
+ return this.setProviderType(type, true)
+ }
+
+ getNetworkEndpoints (version = OLD_UI_NETWORK_TYPE) {
+ return networkConfig[version]
+ }
+
+ initializeProvider (_providerParams) {
+ this._baseProviderParams = _providerParams
+ const { type, rpcTarget } = this.providerStore.getState()
+ // map rpcTarget to rpcUrl
+ const opts = {
+ type,
+ rpcUrl: rpcTarget,
+ }
+ this._configureProvider(opts)
+ this._proxy.on('block', this._logBlock.bind(this))
+ this._proxy.on('error', this.verifyNetwork.bind(this))
+ this.ethQuery = new EthQuery(this._proxy)
+ this.lookupNetwork()
+ return this._proxy
+ }
+
+ verifyNetwork () {
+ // Check network when restoring connectivity:
+ if (this.isNetworkLoading()) this.lookupNetwork()
+ }
+
+ getNetworkState () {
+ return this.networkStore.getState()
+ }
+
+ setNetworkState (network) {
+ return this.networkStore.putState(network)
+ }
+
+ isNetworkLoading () {
+ return this.getNetworkState() === 'loading'
+ }
+
+ lookupNetwork () {
+ // Prevent firing when provider is not defined.
+ if (!this.ethQuery || !this.ethQuery.sendAsync) {
+ return log.warn('NetworkController - lookupNetwork aborted due to missing ethQuery')
+ }
+ this.ethQuery.sendAsync({ method: 'net_version' }, (err, network) => {
+ if (err) return this.setNetworkState('loading')
+ log.info('web3.getNetwork returned ' + network)
+ this.setNetworkState(network)
+ })
+ }
+
+ setRpcTarget (rpcUrl) {
+ this.providerStore.updateState({
+ type: 'rpc',
+ rpcTarget: rpcUrl,
+ })
+ this._switchNetwork({ rpcUrl })
+ }
+
+ getCurrentRpcAddress () {
+ const provider = this.getProviderConfig()
+ if (!provider) return null
+ return this.getRpcAddressForType(provider.type)
+ }
+
+ async setProviderType (type, forceUpdate = false) {
+ assert(type !== 'rpc', `NetworkController.setProviderType - cannot connect by type "rpc"`)
+ // skip if type already matches
+ if (type === this.getProviderConfig().type && !forceUpdate) {
+ return
+ }
+
+ const rpcTarget = this.getRpcAddressForType(type)
+ assert(rpcTarget, `NetworkController - unknown rpc address for type "${type}"`)
+ this.providerStore.updateState({ type, rpcTarget })
+ this._switchNetwork({ type })
+ }
+
+ getProviderConfig () {
+ return this.providerStore.getState()
+ }
+
+ getRpcAddressForType (type, provider = this.getProviderConfig()) {
+ if (this._networkEndpoints[type]) {
+ return this._networkEndpoints[type]
+ }
+
+ return provider && provider.rpcTarget ? provider.rpcTarget : this._defaultRpc
+ }
+
+ //
+ // Private
+ //
+
+ _switchNetwork (opts) {
+ this.setNetworkState('loading')
+ this._configureProvider(opts)
+ this.emit('networkDidChange')
+ }
+
+ _configureProvider (opts) {
+ // type-based rpc endpoints
+ const { type } = opts
+ if (type) {
+ // type-based infura rpc endpoints
+ const isInfura = INFURA_PROVIDER_TYPES.includes(type)
+ opts.rpcUrl = this.getRpcAddressForType(type)
+ if (isInfura) {
+ this._configureInfuraProvider(opts)
+ // other type-based rpc endpoints
+ } else {
+ this._configureStandardProvider(opts)
+ }
+ // url-based rpc endpoints
+ } else {
+ this._configureStandardProvider(opts)
+ }
+ }
+
+ _configureInfuraProvider (opts) {
+ log.info('_configureInfuraProvider', opts)
+ const infuraProvider = createInfuraProvider({
+ network: opts.type,
+ })
+ const infuraSubprovider = new SubproviderFromProvider(infuraProvider)
+ const providerParams = extend(this._baseProviderParams, {
+ rpcUrl: opts.rpcUrl,
+ engineParams: {
+ pollingInterval: 8000,
+ blockTrackerProvider: infuraProvider,
+ },
+ dataSubprovider: infuraSubprovider,
+ })
+ const provider = createMetamaskProvider(providerParams)
+ this._setProvider(provider)
+ }
+
+ _configureStandardProvider ({ rpcUrl }) {
+ const providerParams = extend(this._baseProviderParams, {
+ rpcUrl,
+ engineParams: {
+ pollingInterval: 8000,
+ },
+ })
+ const provider = createMetamaskProvider(providerParams)
+ this._setProvider(provider)
+ }
+
+ _setProvider (provider) {
+ // collect old block tracker events
+ const oldProvider = this._provider
+ let blockTrackerHandlers
+ if (oldProvider) {
+ // capture old block handlers
+ blockTrackerHandlers = oldProvider._blockTracker.proxyEventHandlers
+ // tear down
+ oldProvider.removeAllListeners()
+ oldProvider.stop()
+ }
+ // override block tracler
+ provider._blockTracker = createEventEmitterProxy(provider._blockTracker, blockTrackerHandlers)
+ // set as new provider
+ this._provider = provider
+ this._proxy.setTarget(provider)
+ }
+
+ _logBlock (block) {
+ log.info(`BLOCK CHANGED: #${block.number.toString('hex')} 0x${block.hash.toString('hex')}`)
+ this.verifyNetwork()
+ }
+}
diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js
index c7f675a41..39d15fd83 100644
--- a/app/scripts/controllers/preferences.js
+++ b/app/scripts/controllers/preferences.js
@@ -7,13 +7,22 @@ class PreferencesController {
constructor (opts = {}) {
const initState = extend({
frequentRpcList: [],
+ currentAccountTab: 'history',
+ tokens: [],
+ useBlockie: false,
+ featureFlags: {},
}, opts.initState)
this.store = new ObservableStore(initState)
}
+// PUBLIC METHODS
- //
- // PUBLIC METHODS
- //
+ setUseBlockie (val) {
+ this.store.updateState({ useBlockie: val })
+ }
+
+ getUseBlockie () {
+ return this.store.getState().useBlockie
+ }
setSelectedAddress (_address) {
return new Promise((resolve, reject) => {
@@ -23,10 +32,44 @@ class PreferencesController {
})
}
- getSelectedAddress (_address) {
+ getSelectedAddress () {
return this.store.getState().selectedAddress
}
+ async addToken (rawAddress, symbol, decimals) {
+ const address = normalizeAddress(rawAddress)
+ const newEntry = { address, symbol, decimals }
+
+ const tokens = this.store.getState().tokens
+ const previousEntry = tokens.find((token, index) => {
+ return token.address === address
+ })
+ const previousIndex = tokens.indexOf(previousEntry)
+
+ if (previousEntry) {
+ tokens[previousIndex] = newEntry
+ } else {
+ tokens.push(newEntry)
+ }
+
+ this.store.updateState({ tokens })
+
+ return Promise.resolve(tokens)
+ }
+
+ removeToken (rawAddress) {
+ const tokens = this.store.getState().tokens
+
+ const updatedTokens = tokens.filter(token => token.address !== rawAddress)
+
+ this.store.updateState({ tokens: updatedTokens })
+ return Promise.resolve(updatedTokens)
+ }
+
+ getTokens () {
+ return this.store.getState().tokens
+ }
+
updateFrequentRpcList (_url) {
return this.addToFrequentRpcList(_url)
.then((rpcList) => {
@@ -35,9 +78,16 @@ class PreferencesController {
})
}
+ setCurrentAccountTab (currentAccountTab) {
+ return new Promise((resolve, reject) => {
+ this.store.updateState({ currentAccountTab })
+ resolve()
+ })
+ }
+
addToFrequentRpcList (_url) {
- let rpcList = this.getFrequentRpcList()
- let index = rpcList.findIndex((element) => { return element === _url })
+ const rpcList = this.getFrequentRpcList()
+ const index = rpcList.findIndex((element) => { return element === _url })
if (index !== -1) {
rpcList.splice(index, 1)
}
@@ -54,12 +104,24 @@ class PreferencesController {
return this.store.getState().frequentRpcList
}
- //
- // PRIVATE METHODS
- //
+ setFeatureFlag (feature, activated) {
+ const currentFeatureFlags = this.store.getState().featureFlags
+ const updatedFeatureFlags = {
+ ...currentFeatureFlags,
+ [feature]: activated,
+ }
+ this.store.updateState({ featureFlags: updatedFeatureFlags })
+ return Promise.resolve(updatedFeatureFlags)
+ }
+ getFeatureFlags () {
+ return this.store.getState().featureFlags
+ }
+ //
+ // PRIVATE METHODS
+ //
}
module.exports = PreferencesController
diff --git a/app/scripts/controllers/recent-blocks.js b/app/scripts/controllers/recent-blocks.js
new file mode 100644
index 000000000..4ae3810eb
--- /dev/null
+++ b/app/scripts/controllers/recent-blocks.js
@@ -0,0 +1,110 @@
+const ObservableStore = require('obs-store')
+const extend = require('xtend')
+const BN = require('ethereumjs-util').BN
+const EthQuery = require('eth-query')
+
+class RecentBlocksController {
+
+ constructor (opts = {}) {
+ const { blockTracker, provider } = opts
+ this.blockTracker = blockTracker
+ this.ethQuery = new EthQuery(provider)
+ this.historyLength = opts.historyLength || 40
+
+ const initState = extend({
+ recentBlocks: [],
+ }, opts.initState)
+ this.store = new ObservableStore(initState)
+
+ this.blockTracker.on('block', this.processBlock.bind(this))
+ this.backfill()
+ }
+
+ resetState () {
+ this.store.updateState({
+ recentBlocks: [],
+ })
+ }
+
+ processBlock (newBlock) {
+ const block = this.mapTransactionsToPrices(newBlock)
+
+ const state = this.store.getState()
+ state.recentBlocks.push(block)
+
+ while (state.recentBlocks.length > this.historyLength) {
+ state.recentBlocks.shift()
+ }
+
+ this.store.updateState(state)
+ }
+
+ backfillBlock (newBlock) {
+ const block = this.mapTransactionsToPrices(newBlock)
+
+ const state = this.store.getState()
+
+ if (state.recentBlocks.length < this.historyLength) {
+ state.recentBlocks.unshift(block)
+ }
+
+ this.store.updateState(state)
+ }
+
+ mapTransactionsToPrices (newBlock) {
+ const block = extend(newBlock, {
+ gasPrices: newBlock.transactions.map((tx) => {
+ return tx.gasPrice
+ }),
+ })
+ delete block.transactions
+ return block
+ }
+
+ async backfill() {
+ this.blockTracker.once('block', async (block) => {
+ let blockNum = block.number
+ let recentBlocks
+ let state = this.store.getState()
+ recentBlocks = state.recentBlocks
+
+ while (recentBlocks.length < this.historyLength) {
+ try {
+ let blockNumBn = new BN(blockNum.substr(2), 16)
+ const newNum = blockNumBn.subn(1).toString(10)
+ const newBlock = await this.getBlockByNumber(newNum)
+
+ if (newBlock) {
+ this.backfillBlock(newBlock)
+ blockNum = newBlock.number
+ }
+
+ state = this.store.getState()
+ recentBlocks = state.recentBlocks
+ } catch (e) {
+ log.error(e)
+ }
+ await this.wait()
+ }
+ })
+ }
+
+ async wait () {
+ return new Promise((resolve) => {
+ setTimeout(resolve, 100)
+ })
+ }
+
+ async getBlockByNumber (number) {
+ const bn = new BN(number)
+ return new Promise((resolve, reject) => {
+ this.ethQuery.getBlockByNumber('0x' + bn.toString(16), true, (err, block) => {
+ if (err) reject(err)
+ resolve(block)
+ })
+ })
+ }
+
+}
+
+module.exports = RecentBlocksController
diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js
new file mode 100644
index 000000000..ef5578d5a
--- /dev/null
+++ b/app/scripts/controllers/transactions.js
@@ -0,0 +1,325 @@
+const EventEmitter = require('events')
+const ObservableStore = require('obs-store')
+const ethUtil = require('ethereumjs-util')
+const Transaction = require('ethereumjs-tx')
+const EthQuery = require('ethjs-query')
+const TransactionStateManger = require('../lib/tx-state-manager')
+const TxGasUtil = require('../lib/tx-gas-utils')
+const PendingTransactionTracker = require('../lib/pending-tx-tracker')
+const createId = require('../lib/random-id')
+const NonceTracker = require('../lib/nonce-tracker')
+
+/*
+ Transaction Controller is an aggregate of sub-controllers and trackers
+ composing them in a way to be exposed to the metamask controller
+ - txStateManager
+ responsible for the state of a transaction and
+ storing the transaction
+ - pendingTxTracker
+ watching blocks for transactions to be include
+ and emitting confirmed events
+ - txGasUtil
+ gas calculations and safety buffering
+ - nonceTracker
+ calculating nonces
+*/
+
+module.exports = class TransactionController extends EventEmitter {
+ constructor (opts) {
+ super()
+ this.networkStore = opts.networkStore || new ObservableStore({})
+ this.preferencesStore = opts.preferencesStore || new ObservableStore({})
+ this.provider = opts.provider
+ this.blockTracker = opts.blockTracker
+ this.signEthTx = opts.signTransaction
+ this.getGasPrice = opts.getGasPrice
+
+ this.memStore = new ObservableStore({})
+ this.query = new EthQuery(this.provider)
+ this.txGasUtil = new TxGasUtil(this.provider)
+
+ this.txStateManager = new TransactionStateManger({
+ initState: opts.initState,
+ txHistoryLimit: opts.txHistoryLimit,
+ getNetwork: this.getNetwork.bind(this),
+ })
+
+ this.txStateManager.getFilteredTxList({
+ status: 'unapproved',
+ loadingDefaults: true,
+ }).forEach((tx) => {
+ this.addTxDefaults(tx)
+ .then((txMeta) => {
+ txMeta.loadingDefaults = false
+ this.txStateManager.updateTx(txMeta, 'transactions: gas estimation for tx on boot')
+ }).catch((error) => {
+ this.txStateManager.setTxStatusFailed(tx.id, error)
+ })
+ })
+
+ this.txStateManager.getFilteredTxList({
+ status: 'approved',
+ }).forEach((txMeta) => {
+ const txSignError = new Error('Transaction found as "approved" during boot - possibly stuck during signing')
+ this.txStateManager.setTxStatusFailed(txMeta.id, txSignError)
+ })
+
+
+ this.store = this.txStateManager.store
+ this.txStateManager.on('tx:status-update', this.emit.bind(this, 'tx:status-update'))
+ this.nonceTracker = new NonceTracker({
+ provider: this.provider,
+ getPendingTransactions: this.txStateManager.getPendingTransactions.bind(this.txStateManager),
+ getConfirmedTransactions: (address) => {
+ return this.txStateManager.getFilteredTxList({
+ from: address,
+ status: 'confirmed',
+ err: undefined,
+ })
+ },
+ })
+
+ this.pendingTxTracker = new PendingTransactionTracker({
+ provider: this.provider,
+ nonceTracker: this.nonceTracker,
+ publishTransaction: (rawTx) => this.query.sendRawTransaction(rawTx),
+ getPendingTransactions: this.txStateManager.getPendingTransactions.bind(this.txStateManager),
+ getCompletedTransactions: this.txStateManager.getConfirmedTransactions.bind(this.txStateManager),
+ })
+
+ this.txStateManager.store.subscribe(() => this.emit('update:badge'))
+
+ this.pendingTxTracker.on('tx:warning', (txMeta) => {
+ this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:warning')
+ })
+ this.pendingTxTracker.on('tx:failed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager))
+ this.pendingTxTracker.on('tx:confirmed', this.txStateManager.setTxStatusConfirmed.bind(this.txStateManager))
+ this.pendingTxTracker.on('tx:block-update', (txMeta, latestBlockNumber) => {
+ if (!txMeta.firstRetryBlockNumber) {
+ txMeta.firstRetryBlockNumber = latestBlockNumber
+ this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:block-update')
+ }
+ })
+ this.pendingTxTracker.on('tx:retry', (txMeta) => {
+ if (!('retryCount' in txMeta)) txMeta.retryCount = 0
+ txMeta.retryCount++
+ this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:retry')
+ })
+
+ this.blockTracker.on('block', this.pendingTxTracker.checkForTxInBlock.bind(this.pendingTxTracker))
+ // this is a little messy but until ethstore has been either
+ // removed or redone this is to guard against the race condition
+ this.blockTracker.on('latest', this.pendingTxTracker.resubmitPendingTxs.bind(this.pendingTxTracker))
+ this.blockTracker.on('sync', this.pendingTxTracker.queryPendingTxs.bind(this.pendingTxTracker))
+ // memstore is computed from a few different stores
+ this._updateMemstore()
+ this.txStateManager.store.subscribe(() => this._updateMemstore())
+ this.networkStore.subscribe(() => this._updateMemstore())
+ this.preferencesStore.subscribe(() => this._updateMemstore())
+ }
+
+ getState () {
+ return this.memStore.getState()
+ }
+
+ getNetwork () {
+ return this.networkStore.getState()
+ }
+
+ getSelectedAddress () {
+ return this.preferencesStore.getState().selectedAddress
+ }
+
+ getUnapprovedTxCount () {
+ return Object.keys(this.txStateManager.getUnapprovedTxList()).length
+ }
+
+ getPendingTxCount (account) {
+ return this.txStateManager.getPendingTransactions(account).length
+ }
+
+ getFilteredTxList (opts) {
+ return this.txStateManager.getFilteredTxList(opts)
+ }
+
+ getChainId () {
+ const networkState = this.networkStore.getState()
+ const getChainId = parseInt(networkState)
+ if (Number.isNaN(getChainId)) {
+ return 0
+ } else {
+ return getChainId
+ }
+ }
+
+ wipeTransactions (address) {
+ this.txStateManager.wipeTransactions(address)
+ }
+
+ // Adds a tx to the txlist
+ addTx (txMeta) {
+ this.txStateManager.addTx(txMeta)
+ this.emit(`${txMeta.id}:unapproved`, txMeta)
+ }
+
+ async newUnapprovedTransaction (txParams) {
+ log.debug(`MetaMaskController newUnapprovedTransaction ${JSON.stringify(txParams)}`)
+ const initialTxMeta = await this.addUnapprovedTransaction(txParams)
+ // listen for tx completion (success, fail)
+ return new Promise((resolve, reject) => {
+ this.txStateManager.once(`${initialTxMeta.id}:finished`, (finishedTxMeta) => {
+ switch (finishedTxMeta.status) {
+ case 'submitted':
+ return resolve(finishedTxMeta.hash)
+ case 'rejected':
+ return reject(new Error('MetaMask Tx Signature: User denied transaction signature.'))
+ case 'failed':
+ return reject(new Error(finishedTxMeta.err.message))
+ default:
+ return reject(new Error(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finishedTxMeta.txParams)}`))
+ }
+ })
+ })
+ }
+
+ async addUnapprovedTransaction (txParams) {
+ // validate
+ await this.txGasUtil.validateTxParams(txParams)
+ // construct txMeta
+ const txMeta = {
+ id: createId(),
+ time: (new Date()).getTime(),
+ status: 'unapproved',
+ metamaskNetworkId: this.getNetwork(),
+ txParams: txParams,
+ loadingDefaults: true,
+ }
+ this.addTx(txMeta)
+ this.emit('newUnapprovedTx', txMeta)
+ // add default tx params
+ try {
+ await this.addTxDefaults(txMeta)
+ } catch (error) {
+ console.log(error)
+ this.txStateManager.setTxStatusFailed(txMeta.id, error)
+ throw error
+ }
+ txMeta.loadingDefaults = false
+ // save txMeta
+ this.txStateManager.updateTx(txMeta)
+
+ return txMeta
+ }
+
+ async addTxDefaults (txMeta) {
+ const txParams = txMeta.txParams
+ // ensure value
+ txMeta.gasPriceSpecified = Boolean(txParams.gasPrice)
+ txMeta.nonceSpecified = Boolean(txParams.nonce)
+ let gasPrice = txParams.gasPrice
+ if (!gasPrice) {
+ gasPrice = this.getGasPrice ? this.getGasPrice() : await this.query.gasPrice()
+ }
+ txParams.gasPrice = ethUtil.addHexPrefix(gasPrice.toString(16))
+ txParams.value = txParams.value || '0x0'
+ // set gasLimit
+ return await this.txGasUtil.analyzeGasUsage(txMeta)
+ }
+
+ async retryTransaction (txId) {
+ this.txStateManager.setTxStatusUnapproved(txId)
+ const txMeta = this.txStateManager.getTx(txId)
+ txMeta.lastGasPrice = txMeta.txParams.gasPrice
+ this.txStateManager.updateTx(txMeta, 'retryTransaction: manual retry')
+ }
+
+ async updateTransaction (txMeta) {
+ this.txStateManager.updateTx(txMeta, 'confTx: user updated transaction')
+ }
+
+ async updateAndApproveTransaction (txMeta) {
+ this.txStateManager.updateTx(txMeta, 'confTx: user approved transaction')
+ await this.approveTransaction(txMeta.id)
+ }
+
+ async approveTransaction (txId) {
+ let nonceLock
+ try {
+ // approve
+ this.txStateManager.setTxStatusApproved(txId)
+ // get next nonce
+ const txMeta = this.txStateManager.getTx(txId)
+ const fromAddress = txMeta.txParams.from
+ // wait for a nonce
+ nonceLock = await this.nonceTracker.getNonceLock(fromAddress)
+ // add nonce to txParams
+ const nonce = txMeta.nonceSpecified ? txMeta.txParams.nonce : nonceLock.nextNonce
+ if (nonce > nonceLock.nextNonce) {
+ const message = `Specified nonce may not be larger than account's next valid nonce.`
+ throw new Error(message)
+ }
+ txMeta.txParams.nonce = ethUtil.addHexPrefix(nonce.toString(16))
+ // add nonce debugging information to txMeta
+ txMeta.nonceDetails = nonceLock.nonceDetails
+ this.txStateManager.updateTx(txMeta, 'transactions#approveTransaction')
+ // sign transaction
+ const rawTx = await this.signTransaction(txId)
+ await this.publishTransaction(txId, rawTx)
+ // must set transaction to submitted/failed before releasing lock
+ nonceLock.releaseLock()
+ } catch (err) {
+ this.txStateManager.setTxStatusFailed(txId, err)
+ // must set transaction to submitted/failed before releasing lock
+ if (nonceLock) nonceLock.releaseLock()
+ // continue with error chain
+ throw err
+ }
+ }
+
+ async signTransaction (txId) {
+ const txMeta = this.txStateManager.getTx(txId)
+ const txParams = txMeta.txParams
+ const fromAddress = txParams.from
+ // add network/chain id
+ txParams.chainId = ethUtil.addHexPrefix(this.getChainId().toString(16))
+ const ethTx = new Transaction(txParams)
+ await this.signEthTx(ethTx, fromAddress)
+ this.txStateManager.setTxStatusSigned(txMeta.id)
+ const rawTx = ethUtil.bufferToHex(ethTx.serialize())
+ return rawTx
+ }
+
+ async publishTransaction (txId, rawTx) {
+ const txMeta = this.txStateManager.getTx(txId)
+ txMeta.rawTx = rawTx
+ this.txStateManager.updateTx(txMeta, 'transactions#publishTransaction')
+ const txHash = await this.query.sendRawTransaction(rawTx)
+ this.setTxHash(txId, txHash)
+ this.txStateManager.setTxStatusSubmitted(txId)
+ }
+
+ async cancelTransaction (txId) {
+ this.txStateManager.setTxStatusRejected(txId)
+ }
+
+ // receives a txHash records the tx as signed
+ setTxHash (txId, txHash) {
+ // Add the tx hash to the persisted meta-tx object
+ const txMeta = this.txStateManager.getTx(txId)
+ txMeta.hash = txHash
+ this.txStateManager.updateTx(txMeta, 'transactions#setTxHash')
+ }
+
+//
+// PRIVATE METHODS
+//
+
+ _updateMemstore () {
+ const unapprovedTxs = this.txStateManager.getUnapprovedTxList()
+ const selectedAddressTxList = this.txStateManager.getFilteredTxList({
+ from: this.getSelectedAddress(),
+ metamaskNetworkId: this.getNetwork(),
+ })
+ this.memStore.updateState({ unapprovedTxs, selectedAddressTxList })
+ }
+}
diff --git a/app/scripts/first-time-state.js b/app/scripts/first-time-state.js
index 3196981ba..5e8577100 100644
--- a/app/scripts/first-time-state.js
+++ b/app/scripts/first-time-state.js
@@ -1,11 +1,15 @@
+// test and development environment variables
+const env = process.env.METAMASK_ENV
+const METAMASK_DEBUG = 'GULP_METAMASK_DEBUG'
+
//
// The default state of MetaMask
//
-
module.exports = {
- config: {
+ config: {},
+ NetworkController: {
provider: {
- type: 'testnet',
+ type: (METAMASK_DEBUG || env === 'test') ? 'rinkeby' : 'mainnet',
},
},
-} \ No newline at end of file
+}
diff --git a/app/scripts/inpage.js b/app/scripts/inpage.js
index 419f78cd6..9261e7d64 100644
--- a/app/scripts/inpage.js
+++ b/app/scripts/inpage.js
@@ -1,6 +1,7 @@
/*global Web3*/
cleanContextForImports()
require('web3/dist/web3.min.js')
+const log = require('loglevel')
const LocalMessageDuplexStream = require('post-message-stream')
// const PingStream = require('ping-pong-stream/ping')
// const endOfStream = require('end-of-stream')
@@ -8,6 +9,10 @@ const setupDappAutoReload = require('./lib/auto-reload.js')
const MetamaskInpageProvider = require('./lib/inpage-provider.js')
restoreContextAfterImports()
+const METAMASK_DEBUG = 'GULP_METAMASK_DEBUG'
+window.log = log
+log.setDefaultLevel(METAMASK_DEBUG ? 'debug' : 'warn')
+
//
// setup plugin communication
@@ -26,31 +31,23 @@ var inpageProvider = new MetamaskInpageProvider(metamaskStream)
// setup web3
//
+if (typeof window.web3 !== 'undefined') {
+ throw new Error(`MetaMask detected another web3.
+ MetaMask will not work reliably with another web3 extension.
+ This usually happens if you have two MetaMasks installed,
+ or MetaMask and another web3 extension. Please remove one
+ and try again.`)
+}
var web3 = new Web3(inpageProvider)
web3.setProvider = function () {
- console.log('MetaMask - overrode web3.setProvider')
+ log.debug('MetaMask - overrode web3.setProvider')
}
-console.log('MetaMask - injected web3')
-// export global web3, with usage-detection reload fn
-var triggerReload = setupDappAutoReload(web3)
-
-// listen for reset requests from metamask
-var reloadStream = inpageProvider.multiStream.createStream('reload')
-reloadStream.once('data', triggerReload)
-
-// setup ping timeout autoreload
-// LocalMessageDuplexStream does not self-close, so reload if pingStream fails
-// var pingChannel = inpageProvider.multiStream.createStream('pingpong')
-// var pingStream = new PingStream({ objectMode: true })
-// wait for first successful reponse
-
-// disable pingStream until https://github.com/MetaMask/metamask-plugin/issues/746 is resolved more gracefully
-// metamaskStream.once('data', function(){
-// pingStream.pipe(pingChannel).pipe(pingStream)
-// })
-// endOfStream(pingStream, triggerReload)
+log.debug('MetaMask - injected web3')
+// export global web3, with usage-detection
+setupDappAutoReload(web3, inpageProvider.publicConfigStore)
// set web3 defaultAccount
+
inpageProvider.publicConfigStore.subscribe(function (state) {
web3.eth.defaultAccount = state.selectedAddress
})
diff --git a/app/scripts/keyring-controller.js b/app/scripts/keyring-controller.js
deleted file mode 100644
index 16df6efa6..000000000
--- a/app/scripts/keyring-controller.js
+++ /dev/null
@@ -1,594 +0,0 @@
-const ethUtil = require('ethereumjs-util')
-const BN = ethUtil.BN
-const bip39 = require('bip39')
-const EventEmitter = require('events').EventEmitter
-const ObservableStore = require('obs-store')
-const filter = require('promise-filter')
-const encryptor = require('browser-passworder')
-const sigUtil = require('eth-sig-util')
-const normalizeAddress = sigUtil.normalize
-// Keyrings:
-const SimpleKeyring = require('eth-simple-keyring')
-const HdKeyring = require('eth-hd-keyring')
-const keyringTypes = [
- SimpleKeyring,
- HdKeyring,
-]
-
-class KeyringController extends EventEmitter {
-
- // PUBLIC METHODS
- //
- // THE FIRST SECTION OF METHODS ARE PUBLIC-FACING,
- // MEANING THEY ARE USED BY CONSUMERS OF THIS CLASS.
- //
- // THEIR SURFACE AREA SHOULD BE CHANGED WITH GREAT CARE.
-
- constructor (opts) {
- super()
- const initState = opts.initState || {}
- this.keyringTypes = keyringTypes
- this.store = new ObservableStore(initState)
- this.memStore = new ObservableStore({
- isUnlocked: false,
- keyringTypes: this.keyringTypes.map(krt => krt.type),
- keyrings: [],
- identities: {},
- })
- this.ethStore = opts.ethStore
- this.encryptor = encryptor
- this.keyrings = []
- this.getNetwork = opts.getNetwork
- }
-
- // Full Update
- // returns Promise( @object state )
- //
- // Emits the `update` event and
- // returns a Promise that resolves to the current state.
- //
- // Frequently used to end asynchronous chains in this class,
- // indicating consumers can often either listen for updates,
- // or accept a state-resolving promise to consume their results.
- //
- // Not all methods end with this, that might be a nice refactor.
- fullUpdate () {
- this.emit('update')
- return Promise.resolve(this.memStore.getState())
- }
-
- // Create New Vault And Keychain
- // @string password - The password to encrypt the vault with
- //
- // returns Promise( @object state )
- //
- // Destroys any old encrypted storage,
- // creates a new encrypted store with the given password,
- // randomly creates a new HD wallet with 1 account,
- // faucets that account on the testnet.
- createNewVaultAndKeychain (password) {
- return this.persistAllKeyrings(password)
- .then(this.createFirstKeyTree.bind(this))
- .then(this.fullUpdate.bind(this))
- }
-
- // CreateNewVaultAndRestore
- // @string password - The password to encrypt the vault with
- // @string seed - The BIP44-compliant seed phrase.
- //
- // returns Promise( @object state )
- //
- // Destroys any old encrypted storage,
- // creates a new encrypted store with the given password,
- // creates a new HD wallet from the given seed with 1 account.
- createNewVaultAndRestore (password, seed) {
- if (typeof password !== 'string') {
- return Promise.reject('Password must be text.')
- }
-
- if (!bip39.validateMnemonic(seed)) {
- return Promise.reject('Seed phrase is invalid.')
- }
-
- this.clearKeyrings()
-
- return this.persistAllKeyrings(password)
- .then(() => {
- return this.addNewKeyring('HD Key Tree', {
- mnemonic: seed,
- numberOfAccounts: 1,
- })
- })
- .then((firstKeyring) => {
- return firstKeyring.getAccounts()
- })
- .then((accounts) => {
- const firstAccount = accounts[0]
- if (!firstAccount) throw new Error('KeyringController - First Account not found.')
- const hexAccount = normalizeAddress(firstAccount)
- this.emit('newAccount', hexAccount)
- return this.setupAccounts(accounts)
- })
- .then(this.persistAllKeyrings.bind(this, password))
- .then(this.fullUpdate.bind(this))
- }
-
- // Set Locked
- // returns Promise( @object state )
- //
- // This method deallocates all secrets, and effectively locks metamask.
- setLocked () {
- // set locked
- this.password = null
- this.memStore.updateState({ isUnlocked: false })
- // remove keyrings
- this.keyrings = []
- this._updateMemStoreKeyrings()
- return this.fullUpdate()
- }
-
- // Submit Password
- // @string password
- //
- // returns Promise( @object state )
- //
- // Attempts to decrypt the current vault and load its keyrings
- // into memory.
- //
- // Temporarily also migrates any old-style vaults first, as well.
- // (Pre MetaMask 3.0.0)
- submitPassword (password) {
- return this.unlockKeyrings(password)
- .then((keyrings) => {
- this.keyrings = keyrings
- return this.fullUpdate()
- })
- }
-
- // Add New Keyring
- // @string type
- // @object opts
- //
- // returns Promise( @Keyring keyring )
- //
- // Adds a new Keyring of the given `type` to the vault
- // and the current decrypted Keyrings array.
- //
- // All Keyring classes implement a unique `type` string,
- // and this is used to retrieve them from the keyringTypes array.
- addNewKeyring (type, opts) {
- const Keyring = this.getKeyringClassForType(type)
- const keyring = new Keyring(opts)
- return keyring.deserialize(opts)
- .then(() => {
- return keyring.getAccounts()
- })
- .then((accounts) => {
- return this.checkForDuplicate(type, accounts)
- })
- .then((checkedAccounts) => {
- this.keyrings.push(keyring)
- return this.setupAccounts(checkedAccounts)
- })
- .then(() => this.persistAllKeyrings())
- .then(() => this.fullUpdate())
- .then(() => {
- this._updateMemStoreKeyrings()
- return keyring
- })
- }
-
- // For now just checks for simple key pairs
- // but in the future
- // should possibly add HD and other types
- //
- checkForDuplicate (type, newAccount) {
- return this.getAccounts()
- .then((accounts) => {
- switch (type) {
- case 'Simple Key Pair':
- let isNotIncluded = !accounts.find((key) => key === newAccount[0] || key === ethUtil.stripHexPrefix(newAccount[0]))
- return (isNotIncluded) ? Promise.resolve(newAccount) : Promise.reject(new Error('The account you\'re are trying to import is a duplicate'))
- default:
- return Promise.resolve(newAccount)
- }
- })
- }
-
-
- // Add New Account
- // @number keyRingNum
- //
- // returns Promise( @object state )
- //
- // Calls the `addAccounts` method on the Keyring
- // in the kryings array at index `keyringNum`,
- // and then saves those changes.
- addNewAccount (selectedKeyring) {
- return selectedKeyring.addAccounts(1)
- .then(this.setupAccounts.bind(this))
- .then(this.persistAllKeyrings.bind(this))
- .then(this.fullUpdate.bind(this))
- }
-
- // Save Account Label
- // @string account
- // @string label
- //
- // returns Promise( @string label )
- //
- // Persists a nickname equal to `label` for the specified account.
- saveAccountLabel (account, label) {
- try {
- const hexAddress = normalizeAddress(account)
- // update state on diskStore
- const state = this.store.getState()
- const walletNicknames = state.walletNicknames || {}
- walletNicknames[hexAddress] = label
- this.store.updateState({ walletNicknames })
- // update state on memStore
- const identities = this.memStore.getState().identities
- identities[hexAddress].name = label
- this.memStore.updateState({ identities })
- return Promise.resolve(label)
- } catch (err) {
- return Promise.reject(err)
- }
- }
-
- // Export Account
- // @string address
- //
- // returns Promise( @string privateKey )
- //
- // Requests the private key from the keyring controlling
- // the specified address.
- //
- // Returns a Promise that may resolve with the private key string.
- exportAccount (address) {
- try {
- return this.getKeyringForAccount(address)
- .then((keyring) => {
- return keyring.exportAccount(normalizeAddress(address))
- })
- } catch (e) {
- return Promise.reject(e)
- }
- }
-
-
- // SIGNING METHODS
- //
- // This method signs tx and returns a promise for
- // TX Manager to update the state after signing
-
- signTransaction (ethTx, _fromAddress) {
- const fromAddress = normalizeAddress(_fromAddress)
- return this.getKeyringForAccount(fromAddress)
- .then((keyring) => {
- return keyring.signTransaction(fromAddress, ethTx)
- })
- }
-
- // Sign Message
- // @object msgParams
- //
- // returns Promise(@buffer rawSig)
- //
- // Attempts to sign the provided @object msgParams.
- signMessage (msgParams) {
- const address = normalizeAddress(msgParams.from)
- return this.getKeyringForAccount(address)
- .then((keyring) => {
- return keyring.signMessage(address, msgParams.data)
- })
- }
-
- // Sign Personal Message
- // @object msgParams
- //
- // returns Promise(@buffer rawSig)
- //
- // Attempts to sign the provided @object msgParams.
- // Prefixes the hash before signing as per the new geth behavior.
- signPersonalMessage (msgParams) {
- const address = normalizeAddress(msgParams.from)
- return this.getKeyringForAccount(address)
- .then((keyring) => {
- return keyring.signPersonalMessage(address, msgParams.data)
- })
- }
-
- // PRIVATE METHODS
- //
- // THESE METHODS ARE ONLY USED INTERNALLY TO THE KEYRING-CONTROLLER
- // AND SO MAY BE CHANGED MORE LIBERALLY THAN THE ABOVE METHODS.
-
- // Create First Key Tree
- // returns @Promise
- //
- // Clears the vault,
- // creates a new one,
- // creates a random new HD Keyring with 1 account,
- // makes that account the selected account,
- // faucets that account on testnet,
- // puts the current seed words into the state tree.
- createFirstKeyTree () {
- this.clearKeyrings()
- return this.addNewKeyring('HD Key Tree', { numberOfAccounts: 1 })
- .then((keyring) => {
- return keyring.getAccounts()
- })
- .then((accounts) => {
- const firstAccount = accounts[0]
- if (!firstAccount) throw new Error('KeyringController - No account found on keychain.')
- const hexAccount = normalizeAddress(firstAccount)
- this.emit('newAccount', hexAccount)
- this.emit('newVault', hexAccount)
- return this.setupAccounts(accounts)
- })
- .then(this.persistAllKeyrings.bind(this))
- }
-
- // Setup Accounts
- // @array accounts
- //
- // returns @Promise(@object account)
- //
- // Initializes the provided account array
- // Gives them numerically incremented nicknames,
- // and adds them to the ethStore for regular balance checking.
- setupAccounts (accounts) {
- return this.getAccounts()
- .then((loadedAccounts) => {
- const arr = accounts || loadedAccounts
- return Promise.all(arr.map((account) => {
- return this.getBalanceAndNickname(account)
- }))
- })
- }
-
- // Get Balance And Nickname
- // @string account
- //
- // returns Promise( @string label )
- //
- // Takes an account address and an iterator representing
- // the current number of named accounts.
- getBalanceAndNickname (account) {
- if (!account) {
- throw new Error('Problem loading account.')
- }
- const address = normalizeAddress(account)
- this.ethStore.addAccount(address)
- return this.createNickname(address)
- }
-
- // Create Nickname
- // @string address
- //
- // returns Promise( @string label )
- //
- // Takes an address, and assigns it an incremented nickname, persisting it.
- createNickname (address) {
- const hexAddress = normalizeAddress(address)
- const identities = this.memStore.getState().identities
- const currentIdentityCount = Object.keys(identities).length + 1
- const nicknames = this.store.getState().walletNicknames || {}
- const existingNickname = nicknames[hexAddress]
- const name = existingNickname || `Account ${currentIdentityCount}`
- identities[hexAddress] = {
- address: hexAddress,
- name,
- }
- this.memStore.updateState({ identities })
- return this.saveAccountLabel(hexAddress, name)
- }
-
- // Persist All Keyrings
- // @password string
- //
- // returns Promise
- //
- // Iterates the current `keyrings` array,
- // serializes each one into a serialized array,
- // encrypts that array with the provided `password`,
- // and persists that encrypted string to storage.
- persistAllKeyrings (password = this.password) {
- if (typeof password === 'string') {
- this.password = password
- this.memStore.updateState({ isUnlocked: true })
- }
- return Promise.all(this.keyrings.map((keyring) => {
- return Promise.all([keyring.type, keyring.serialize()])
- .then((serializedKeyringArray) => {
- // Label the output values on each serialized Keyring:
- return {
- type: serializedKeyringArray[0],
- data: serializedKeyringArray[1],
- }
- })
- }))
- .then((serializedKeyrings) => {
- return this.encryptor.encrypt(this.password, serializedKeyrings)
- })
- .then((encryptedString) => {
- this.store.updateState({ vault: encryptedString })
- return true
- })
- }
-
- // Unlock Keyrings
- // @string password
- //
- // returns Promise( @array keyrings )
- //
- // Attempts to unlock the persisted encrypted storage,
- // initializing the persisted keyrings to RAM.
- unlockKeyrings (password) {
- const encryptedVault = this.store.getState().vault
- if (!encryptedVault) {
- throw new Error('Cannot unlock without a previous vault.')
- }
-
- return this.encryptor.decrypt(password, encryptedVault)
- .then((vault) => {
- this.password = password
- this.memStore.updateState({ isUnlocked: true })
- vault.forEach(this.restoreKeyring.bind(this))
- return this.keyrings
- })
- }
-
- // Restore Keyring
- // @object serialized
- //
- // returns Promise( @Keyring deserialized )
- //
- // Attempts to initialize a new keyring from the provided
- // serialized payload.
- //
- // On success, returns the resulting @Keyring instance.
- restoreKeyring (serialized) {
- const { type, data } = serialized
-
- const Keyring = this.getKeyringClassForType(type)
- const keyring = new Keyring()
- return keyring.deserialize(data)
- .then(() => {
- return keyring.getAccounts()
- })
- .then((accounts) => {
- return this.setupAccounts(accounts)
- })
- .then(() => {
- this.keyrings.push(keyring)
- this._updateMemStoreKeyrings()
- return keyring
- })
- }
-
- // Get Keyring Class For Type
- // @string type
- //
- // Returns @class Keyring
- //
- // Searches the current `keyringTypes` array
- // for a Keyring class whose unique `type` property
- // matches the provided `type`,
- // returning it if it exists.
- getKeyringClassForType (type) {
- return this.keyringTypes.find(kr => kr.type === type)
- }
-
- getKeyringsByType (type) {
- return this.keyrings.filter((keyring) => keyring.type === type)
- }
-
- // Get Accounts
- // returns Promise( @Array[ @string accounts ] )
- //
- // Returns the public addresses of all current accounts
- // managed by all currently unlocked keyrings.
- getAccounts () {
- const keyrings = this.keyrings || []
- return Promise.all(keyrings.map(kr => kr.getAccounts()))
- .then((keyringArrays) => {
- return keyringArrays.reduce((res, arr) => {
- return res.concat(arr)
- }, [])
- })
- }
-
- // Get Keyring For Account
- // @string address
- //
- // returns Promise(@Keyring keyring)
- //
- // Returns the currently initialized keyring that manages
- // the specified `address` if one exists.
- getKeyringForAccount (address) {
- const hexed = normalizeAddress(address)
- log.debug(`KeyringController - getKeyringForAccount: ${hexed}`)
-
- return Promise.all(this.keyrings.map((keyring) => {
- return Promise.all([
- keyring,
- keyring.getAccounts(),
- ])
- }))
- .then(filter((candidate) => {
- const accounts = candidate[1].map(normalizeAddress)
- return accounts.includes(hexed)
- }))
- .then((winners) => {
- if (winners && winners.length > 0) {
- return winners[0][0]
- } else {
- throw new Error('No keyring found for the requested account.')
- }
- })
- }
-
- // Display For Keyring
- // @Keyring keyring
- //
- // returns Promise( @Object { type:String, accounts:Array } )
- //
- // Is used for adding the current keyrings to the state object.
- displayForKeyring (keyring) {
- return keyring.getAccounts()
- .then((accounts) => {
- return {
- type: keyring.type,
- accounts: accounts,
- }
- })
- }
-
- // Add Gas Buffer
- // @string gas (as hexadecimal value)
- //
- // returns @string bufferedGas (as hexadecimal value)
- //
- // Adds a healthy buffer of gas to an initial gas estimate.
- addGasBuffer (gas) {
- const gasBuffer = new BN('100000', 10)
- const bnGas = new BN(ethUtil.stripHexPrefix(gas), 16)
- const correct = bnGas.add(gasBuffer)
- return ethUtil.addHexPrefix(correct.toString(16))
- }
-
- // Clear Keyrings
- //
- // Deallocates all currently managed keyrings and accounts.
- // Used before initializing a new vault.
- clearKeyrings () {
- let accounts
- try {
- accounts = Object.keys(this.ethStore.getState())
- } catch (e) {
- accounts = []
- }
- accounts.forEach((address) => {
- this.ethStore.removeAccount(address)
- })
-
- // clear keyrings from memory
- this.keyrings = []
- this.memStore.updateState({
- keyrings: [],
- identities: {},
- })
- }
-
- _updateMemStoreKeyrings() {
- Promise.all(this.keyrings.map(this.displayForKeyring))
- .then((keyrings) => {
- this.memStore.updateState({ keyrings })
- })
- }
-
-}
-
-module.exports = KeyringController
diff --git a/app/scripts/lib/account-tracker.js b/app/scripts/lib/account-tracker.js
new file mode 100644
index 000000000..8c3dd8c71
--- /dev/null
+++ b/app/scripts/lib/account-tracker.js
@@ -0,0 +1,125 @@
+/* Account Tracker
+ *
+ * This module is responsible for tracking any number of accounts
+ * and caching their current balances & transaction counts.
+ *
+ * It also tracks transaction hashes, and checks their inclusion status
+ * on each new block.
+ */
+
+const async = require('async')
+const EthQuery = require('eth-query')
+const ObservableStore = require('obs-store')
+const EventEmitter = require('events').EventEmitter
+function noop () {}
+
+
+class AccountTracker extends EventEmitter {
+
+ constructor (opts = {}) {
+ super()
+
+ const initState = {
+ accounts: {},
+ currentBlockGasLimit: '',
+ }
+ this.store = new ObservableStore(initState)
+
+ this._provider = opts.provider
+ this._query = new EthQuery(this._provider)
+ this._blockTracker = opts.blockTracker
+ // subscribe to latest block
+ this._blockTracker.on('block', this._updateForBlock.bind(this))
+ // blockTracker.currentBlock may be null
+ this._currentBlockNumber = this._blockTracker.currentBlock
+ }
+
+ //
+ // public
+ //
+
+ syncWithAddresses (addresses) {
+ const accounts = this.store.getState().accounts
+ const locals = Object.keys(accounts)
+
+ const toAdd = []
+ addresses.forEach((upstream) => {
+ if (!locals.includes(upstream)) {
+ toAdd.push(upstream)
+ }
+ })
+
+ const toRemove = []
+ locals.forEach((local) => {
+ if (!addresses.includes(local)) {
+ toRemove.push(local)
+ }
+ })
+
+ toAdd.forEach(upstream => this.addAccount(upstream))
+ toRemove.forEach(local => this.removeAccount(local))
+ this._updateAccounts()
+ }
+
+ addAccount (address) {
+ const accounts = this.store.getState().accounts
+ accounts[address] = {}
+ this.store.updateState({ accounts })
+ if (!this._currentBlockNumber) return
+ this._updateAccount(address)
+ }
+
+ removeAccount (address) {
+ const accounts = this.store.getState().accounts
+ delete accounts[address]
+ this.store.updateState({ accounts })
+ }
+
+ //
+ // private
+ //
+
+ _updateForBlock (block) {
+ this._currentBlockNumber = block.number
+ const currentBlockGasLimit = block.gasLimit
+
+ this.store.updateState({ currentBlockGasLimit })
+
+ async.parallel([
+ this._updateAccounts.bind(this),
+ ], (err) => {
+ if (err) return console.error(err)
+ this.emit('block', this.store.getState())
+ })
+ }
+
+ _updateAccounts (cb = noop) {
+ const accounts = this.store.getState().accounts
+ const addresses = Object.keys(accounts)
+ async.each(addresses, this._updateAccount.bind(this), cb)
+ }
+
+ _updateAccount (address, cb = noop) {
+ this._getAccount(address, (err, result) => {
+ if (err) return cb(err)
+ result.address = address
+ const accounts = this.store.getState().accounts
+ // only populate if the entry is still present
+ if (accounts[address]) {
+ accounts[address] = result
+ this.store.updateState({ accounts })
+ }
+ cb(null, result)
+ })
+ }
+
+ _getAccount (address, cb = noop) {
+ const query = this._query
+ async.parallel({
+ balance: query.getBalance.bind(query, address),
+ }, cb)
+ }
+
+}
+
+module.exports = AccountTracker
diff --git a/app/scripts/lib/auto-faucet.js b/app/scripts/lib/auto-faucet.js
deleted file mode 100644
index 38d54ba5e..000000000
--- a/app/scripts/lib/auto-faucet.js
+++ /dev/null
@@ -1,20 +0,0 @@
-const uri = 'https://faucet.metamask.io/'
-const METAMASK_DEBUG = 'GULP_METAMASK_DEBUG'
-const env = process.env.METAMASK_ENV
-
-module.exports = function (address) {
- // Don't faucet in development or test
- if (METAMASK_DEBUG === true || env === 'test') return
- global.log.info('auto-fauceting:', address)
- const data = address
- const headers = new Headers()
- headers.append('Content-type', 'application/rawdata')
- fetch(uri, {
- method: 'POST',
- headers,
- body: data,
- })
- .catch((err) => {
- console.error(err)
- })
-}
diff --git a/app/scripts/lib/auto-reload.js b/app/scripts/lib/auto-reload.js
index 1302df35f..cce31c3d2 100644
--- a/app/scripts/lib/auto-reload.js
+++ b/app/scripts/lib/auto-reload.js
@@ -1,30 +1,58 @@
-const once = require('once')
-const ensnare = require('ensnare')
-
module.exports = setupDappAutoReload
-function setupDappAutoReload (web3) {
+function setupDappAutoReload (web3, observable) {
// export web3 as a global, checking for usage
- var pageIsUsingWeb3 = false
- var resetWasRequested = false
- global.web3 = ensnare(web3, once(function () {
- // if web3 usage happened after a reset request, trigger reset late
- if (resetWasRequested) return triggerReset()
- // mark web3 as used
- pageIsUsingWeb3 = true
- // reset web3 reference
- global.web3 = web3
- }))
-
- return handleResetRequest
-
- function handleResetRequest () {
- resetWasRequested = true
- // ignore if web3 was not used
- if (!pageIsUsingWeb3) return
- // reload after short timeout
- setTimeout(triggerReset, 500)
- }
+ let hasBeenWarned = false
+ let reloadInProgress = false
+ let lastTimeUsed
+ let lastSeenNetwork
+
+ global.web3 = new Proxy(web3, {
+ get: (_web3, key) => {
+ // show warning once on web3 access
+ if (!hasBeenWarned && key !== 'currentProvider') {
+ console.warn('MetaMask: web3 will be deprecated in the near future in favor of the ethereumProvider \nhttps://github.com/MetaMask/faq/blob/master/detecting_metamask.md#web3-deprecation')
+ hasBeenWarned = true
+ }
+ // get the time of use
+ lastTimeUsed = Date.now()
+ // return value normally
+ return _web3[key]
+ },
+ set: (_web3, key, value) => {
+ // set value normally
+ _web3[key] = value
+ },
+ })
+
+ observable.subscribe(function (state) {
+ // if reload in progress, no need to check reload logic
+ if (reloadInProgress) return
+
+ const currentNetwork = state.networkVersion
+
+ // set the initial network
+ if (!lastSeenNetwork) {
+ lastSeenNetwork = currentNetwork
+ return
+ }
+
+ // skip reload logic if web3 not used
+ if (!lastTimeUsed) return
+
+ // if network did not change, exit
+ if (currentNetwork === lastSeenNetwork) return
+
+ // initiate page reload
+ reloadInProgress = true
+ const timeSinceUse = Date.now() - lastTimeUsed
+ // if web3 was recently used then delay the reloading of the page
+ if (timeSinceUse > 500) {
+ triggerReset()
+ } else {
+ setTimeout(triggerReset, 500)
+ }
+ })
}
// reload the page
diff --git a/app/scripts/lib/buy-eth-url.js b/app/scripts/lib/buy-eth-url.js
index 91a1ec322..b9dde3c28 100644
--- a/app/scripts/lib/buy-eth-url.js
+++ b/app/scripts/lib/buy-eth-url.js
@@ -1,6 +1,6 @@
module.exports = getBuyEthUrl
-function getBuyEthUrl({ network, amount, address }){
+function getBuyEthUrl ({ network, amount, address }) {
let url
switch (network) {
case '1':
@@ -11,9 +11,13 @@ function getBuyEthUrl({ network, amount, address }){
url = 'https://faucet.metamask.io/'
break
+ case '4':
+ url = 'https://www.rinkeby.io/'
+ break
+
case '42':
url = 'https://github.com/kovan-testnet/faucet'
break
}
return url
-} \ No newline at end of file
+}
diff --git a/app/scripts/lib/config-manager.js b/app/scripts/lib/config-manager.js
index e31cb45ed..34b603b96 100644
--- a/app/scripts/lib/config-manager.js
+++ b/app/scripts/lib/config-manager.js
@@ -1,11 +1,12 @@
-const MetamaskConfig = require('../config.js')
const ethUtil = require('ethereumjs-util')
const normalize = require('eth-sig-util').normalize
+const MetamaskConfig = require('../config.js')
+
-const TESTNET_RPC = MetamaskConfig.network.testnet
const MAINNET_RPC = MetamaskConfig.network.mainnet
-const MORDEN_RPC = MetamaskConfig.network.morden
+const ROPSTEN_RPC = MetamaskConfig.network.ropsten
const KOVAN_RPC = MetamaskConfig.network.kovan
+const RINKEBY_RPC = MetamaskConfig.network.rinkeby
/* The config-manager is a convenience object
* wrapping a pojo-migrator.
@@ -33,36 +34,6 @@ ConfigManager.prototype.getConfig = function () {
return data.config
}
-ConfigManager.prototype.setRpcTarget = function (rpcUrl) {
- var config = this.getConfig()
- config.provider = {
- type: 'rpc',
- rpcTarget: rpcUrl,
- }
- this.setConfig(config)
-}
-
-ConfigManager.prototype.setProviderType = function (type) {
- var config = this.getConfig()
- config.provider = {
- type: type,
- }
- this.setConfig(config)
-}
-
-ConfigManager.prototype.useEtherscanProvider = function () {
- var config = this.getConfig()
- config.provider = {
- type: 'etherscan',
- }
- this.setConfig(config)
-}
-
-ConfigManager.prototype.getProvider = function () {
- var config = this.getConfig()
- return config.provider
-}
-
ConfigManager.prototype.setData = function (data) {
this.store.putState(data)
}
@@ -71,6 +42,17 @@ ConfigManager.prototype.getData = function () {
return this.store.getState()
}
+ConfigManager.prototype.setPasswordForgotten = function (passwordForgottenState) {
+ const data = this.getData()
+ data.forgottenPassword = passwordForgottenState
+ this.setData(data)
+}
+
+ConfigManager.prototype.getPasswordForgotten = function (passwordForgottenState) {
+ const data = this.getData()
+ return data.forgottenPassword
+}
+
ConfigManager.prototype.setWallet = function (wallet) {
var data = this.getData()
data.wallet = wallet
@@ -136,6 +118,35 @@ ConfigManager.prototype.getSeedWords = function () {
var data = this.getData()
return data.seedWords
}
+ConfigManager.prototype.setRpcTarget = function (rpcUrl) {
+ var config = this.getConfig()
+ config.provider = {
+ type: 'rpc',
+ rpcTarget: rpcUrl,
+ }
+ this.setConfig(config)
+}
+
+ConfigManager.prototype.setProviderType = function (type) {
+ var config = this.getConfig()
+ config.provider = {
+ type: type,
+ }
+ this.setConfig(config)
+}
+
+ConfigManager.prototype.useEtherscanProvider = function () {
+ var config = this.getConfig()
+ config.provider = {
+ type: 'etherscan',
+ }
+ this.setConfig(config)
+}
+
+ConfigManager.prototype.getProvider = function () {
+ var config = this.getConfig()
+ return config.provider
+}
ConfigManager.prototype.getCurrentRpcAddress = function () {
var provider = this.getProvider()
@@ -145,17 +156,17 @@ ConfigManager.prototype.getCurrentRpcAddress = function () {
case 'mainnet':
return MAINNET_RPC
- case 'testnet':
- return TESTNET_RPC
-
- case 'morden':
- return MORDEN_RPC
+ case 'ropsten':
+ return ROPSTEN_RPC
case 'kovan':
return KOVAN_RPC
+ case 'rinkeby':
+ return RINKEBY_RPC
+
default:
- return provider && provider.rpcTarget ? provider.rpcTarget : TESTNET_RPC
+ return provider && provider.rpcTarget ? provider.rpcTarget : RINKEBY_RPC
}
}
diff --git a/app/scripts/lib/createLoggerMiddleware.js b/app/scripts/lib/createLoggerMiddleware.js
new file mode 100644
index 000000000..2707cbd9e
--- /dev/null
+++ b/app/scripts/lib/createLoggerMiddleware.js
@@ -0,0 +1,15 @@
+// log rpc activity
+module.exports = createLoggerMiddleware
+
+function createLoggerMiddleware ({ origin }) {
+ return function loggerMiddleware (req, res, next, end) {
+ next((cb) => {
+ if (res.error) {
+ log.error('Error in RPC response:\n', res)
+ }
+ if (req.isMetamaskInternal) return
+ log.info(`RPC (${origin}):`, req, '->', res)
+ cb()
+ })
+ }
+}
diff --git a/app/scripts/lib/createOriginMiddleware.js b/app/scripts/lib/createOriginMiddleware.js
new file mode 100644
index 000000000..f8bdb2dc2
--- /dev/null
+++ b/app/scripts/lib/createOriginMiddleware.js
@@ -0,0 +1,9 @@
+// append dapp origin domain to request
+module.exports = createOriginMiddleware
+
+function createOriginMiddleware ({ origin }) {
+ return function originMiddleware (req, res, next, end) {
+ req.origin = origin
+ next()
+ }
+}
diff --git a/app/scripts/lib/createProviderMiddleware.js b/app/scripts/lib/createProviderMiddleware.js
new file mode 100644
index 000000000..4e667bac2
--- /dev/null
+++ b/app/scripts/lib/createProviderMiddleware.js
@@ -0,0 +1,12 @@
+module.exports = createProviderMiddleware
+
+// forward requests to provider
+function createProviderMiddleware ({ provider }) {
+ return (req, res, next, end) => {
+ provider.sendAsync(req, (err, _res) => {
+ if (err) return end(err)
+ res.result = _res.result
+ end()
+ })
+ }
+}
diff --git a/app/scripts/lib/environment-type.js b/app/scripts/lib/environment-type.js
new file mode 100644
index 000000000..7966926eb
--- /dev/null
+++ b/app/scripts/lib/environment-type.js
@@ -0,0 +1,10 @@
+module.exports = function environmentType () {
+ const url = window.location.href
+ if (url.match(/popup.html$/)) {
+ return 'popup'
+ } else if (url.match(/home.html$/)) {
+ return 'responsive'
+ } else {
+ return 'notification'
+ }
+}
diff --git a/app/scripts/lib/eth-store.js b/app/scripts/lib/eth-store.js
deleted file mode 100644
index 243253df2..000000000
--- a/app/scripts/lib/eth-store.js
+++ /dev/null
@@ -1,136 +0,0 @@
-/* Ethereum Store
- *
- * This module is responsible for tracking any number of accounts
- * and caching their current balances & transaction counts.
- *
- * It also tracks transaction hashes, and checks their inclusion status
- * on each new block.
- */
-
-const async = require('async')
-const EthQuery = require('eth-query')
-const ObservableStore = require('obs-store')
-function noop() {}
-
-
-class EthereumStore extends ObservableStore {
-
- constructor (opts = {}) {
- super({
- accounts: {},
- transactions: {},
- currentBlockNumber: '0',
- currentBlockHash: '',
- })
- this._provider = opts.provider
- this._query = new EthQuery(this._provider)
- this._blockTracker = opts.blockTracker
- // subscribe to latest block
- this._blockTracker.on('block', this._updateForBlock.bind(this))
- // blockTracker.currentBlock may be null
- this._currentBlockNumber = this._blockTracker.currentBlock
- }
-
- //
- // public
- //
-
- addAccount (address) {
- const accounts = this.getState().accounts
- accounts[address] = {}
- this.updateState({ accounts })
- if (!this._currentBlockNumber) return
- this._updateAccount(address)
- }
-
- removeAccount (address) {
- const accounts = this.getState().accounts
- delete accounts[address]
- this.updateState({ accounts })
- }
-
- addTransaction (txHash) {
- const transactions = this.getState().transactions
- transactions[txHash] = {}
- this.updateState({ transactions })
- if (!this._currentBlockNumber) return
- this._updateTransaction(this._currentBlockNumber, txHash, noop)
- }
-
- removeTransaction (txHash) {
- const transactions = this.getState().transactions
- delete transactions[txHash]
- this.updateState({ transactions })
- }
-
-
- //
- // private
- //
-
- _updateForBlock (block) {
- const blockNumber = '0x' + block.number.toString('hex')
- this._currentBlockNumber = blockNumber
- this.updateState({ currentBlockNumber: parseInt(blockNumber) })
- this.updateState({ currentBlockHash: `0x${block.hash.toString('hex')}`})
- async.parallel([
- this._updateAccounts.bind(this),
- this._updateTransactions.bind(this, blockNumber),
- ], (err) => {
- if (err) return console.error(err)
- this.emit('block', this.getState())
- })
- }
-
- _updateAccounts (cb = noop) {
- const accounts = this.getState().accounts
- const addresses = Object.keys(accounts)
- async.each(addresses, this._updateAccount.bind(this), cb)
- }
-
- _updateAccount (address, cb = noop) {
- const accounts = this.getState().accounts
- this._getAccount(address, (err, result) => {
- if (err) return cb(err)
- result.address = address
- // only populate if the entry is still present
- if (accounts[address]) {
- accounts[address] = result
- this.updateState({ accounts })
- }
- cb(null, result)
- })
- }
-
- _updateTransactions (block, cb = noop) {
- const transactions = this.getState().transactions
- const txHashes = Object.keys(transactions)
- async.each(txHashes, this._updateTransaction.bind(this, block), cb)
- }
-
- _updateTransaction (block, txHash, cb = noop) {
- // would use the block here to determine how many confirmations the tx has
- const transactions = this.getState().transactions
- this._query.getTransaction(txHash, (err, result) => {
- if (err) return cb(err)
- // only populate if the entry is still present
- if (transactions[txHash]) {
- transactions[txHash] = result
- this.updateState({ transactions })
- }
- cb(null, result)
- })
- }
-
- _getAccount (address, cb = noop) {
- const query = this._query
- async.parallel({
- balance: query.getBalance.bind(query, address),
- nonce: query.getTransactionCount.bind(query, address),
- code: query.getCode.bind(query, address),
- }, cb)
- }
-
-}
-
-module.exports = EthereumStore
diff --git a/app/scripts/lib/events-proxy.js b/app/scripts/lib/events-proxy.js
new file mode 100644
index 000000000..c0a490b05
--- /dev/null
+++ b/app/scripts/lib/events-proxy.js
@@ -0,0 +1,31 @@
+module.exports = function createEventEmitterProxy (eventEmitter, listeners) {
+ let target = eventEmitter
+ const eventHandlers = listeners || {}
+ const proxy = new Proxy({}, {
+ get: (obj, name) => {
+ // intercept listeners
+ if (name === 'on') return addListener
+ if (name === 'setTarget') return setTarget
+ if (name === 'proxyEventHandlers') return eventHandlers
+ return target[name]
+ },
+ set: (obj, name, value) => {
+ target[name] = value
+ return true
+ },
+ })
+ function setTarget (eventEmitter) {
+ target = eventEmitter
+ // migrate listeners
+ Object.keys(eventHandlers).forEach((name) => {
+ eventHandlers[name].forEach((handler) => target.on(name, handler))
+ })
+ }
+ function addListener (name, handler) {
+ if (!eventHandlers[name]) eventHandlers[name] = []
+ eventHandlers[name].push(handler)
+ target.on(name, handler)
+ }
+ if (listeners) proxy.setTarget(eventEmitter)
+ return proxy
+}
diff --git a/app/scripts/lib/inpage-provider.js b/app/scripts/lib/inpage-provider.js
index 92936de2f..99cc5d2cf 100644
--- a/app/scripts/lib/inpage-provider.js
+++ b/app/scripts/lib/inpage-provider.js
@@ -1,8 +1,10 @@
-const pipe = require('pump')
-const StreamProvider = require('web3-stream-provider')
+const pump = require('pump')
+const RpcEngine = require('json-rpc-engine')
+const createIdRemapMiddleware = require('json-rpc-engine/src/idRemapMiddleware')
+const createStreamMiddleware = require('json-rpc-middleware-stream')
const LocalStorageStore = require('obs-store')
-const ObjectMultiplex = require('./obj-multiplex')
-const createRandomId = require('./random-id')
+const asStream = require('obs-store/lib/asStream')
+const ObjectMultiplex = require('obj-multiplex')
module.exports = MetamaskInpageProvider
@@ -10,56 +12,50 @@ function MetamaskInpageProvider (connectionStream) {
const self = this
// setup connectionStream multiplexing
- var multiStream = self.multiStream = ObjectMultiplex()
- pipe(
+ const mux = self.mux = new ObjectMultiplex()
+ pump(
connectionStream,
- multiStream,
+ mux,
connectionStream,
(err) => logStreamDisconnectWarning('MetaMask', err)
)
// subscribe to metamask public config (one-way)
self.publicConfigStore = new LocalStorageStore({ storageKey: 'MetaMask-Config' })
- pipe(
- multiStream.createStream('publicConfig'),
- self.publicConfigStore,
+
+ pump(
+ mux.createStream('publicConfig'),
+ asStream(self.publicConfigStore),
(err) => logStreamDisconnectWarning('MetaMask PublicConfigStore', err)
)
+ // ignore phishing warning message (handled elsewhere)
+ mux.ignoreStream('phishing')
+
// connect to async provider
- const asyncProvider = self.asyncProvider = new StreamProvider()
- pipe(
- asyncProvider,
- multiStream.createStream('provider'),
- asyncProvider,
+ const streamMiddleware = createStreamMiddleware()
+ pump(
+ streamMiddleware.stream,
+ mux.createStream('provider'),
+ streamMiddleware.stream,
(err) => logStreamDisconnectWarning('MetaMask RpcProvider', err)
)
- self.idMap = {}
- // handle sendAsync requests via asyncProvider
- self.sendAsync = function (payload, cb) {
- // rewrite request ids
- var request = eachJsonMessage(payload, (message) => {
- var newId = createRandomId()
- self.idMap[newId] = message.id
- message.id = newId
- return message
- })
- // forward to asyncProvider
- asyncProvider.sendAsync(request, function (err, res) {
- if (err) return cb(err)
- // transform messages to original ids
- eachJsonMessage(res, (message) => {
- var oldId = self.idMap[message.id]
- delete self.idMap[message.id]
- message.id = oldId
- return message
- })
- cb(null, res)
- })
- }
+ // handle sendAsync requests via dapp-side rpc engine
+ const rpcEngine = new RpcEngine()
+ rpcEngine.push(createIdRemapMiddleware())
+ rpcEngine.push(streamMiddleware)
+ self.rpcEngine = rpcEngine
+}
+
+// handle sendAsync requests via asyncProvider
+// also remap ids inbound and outbound
+MetamaskInpageProvider.prototype.sendAsync = function (payload, cb) {
+ const self = this
+ self.rpcEngine.handle(payload, cb)
}
+
MetamaskInpageProvider.prototype.send = function (payload) {
const self = this
@@ -76,7 +72,7 @@ MetamaskInpageProvider.prototype.send = function (payload) {
case 'eth_coinbase':
// read from localStorage
selectedAddress = self.publicConfigStore.getState().selectedAddress
- result = selectedAddress
+ result = selectedAddress || null
break
case 'eth_uninstallFilter':
@@ -85,8 +81,8 @@ MetamaskInpageProvider.prototype.send = function (payload) {
break
case 'net_version':
- let networkVersion = self.publicConfigStore.getState().networkVersion
- result = networkVersion
+ const networkVersion = self.publicConfigStore.getState().networkVersion
+ result = networkVersion || null
break
// throw not-supported Error
@@ -105,10 +101,6 @@ MetamaskInpageProvider.prototype.send = function (payload) {
}
}
-MetamaskInpageProvider.prototype.sendAsync = function () {
- throw new Error('MetamaskInpageProvider - sendAsync not overwritten')
-}
-
MetamaskInpageProvider.prototype.isConnected = function () {
return true
}
@@ -117,15 +109,7 @@ MetamaskInpageProvider.prototype.isMetaMask = true
// util
-function eachJsonMessage (payload, transformFn) {
- if (Array.isArray(payload)) {
- return payload.map(transformFn)
- } else {
- return transformFn(payload)
- }
-}
-
-function logStreamDisconnectWarning(remoteLabel, err){
+function logStreamDisconnectWarning (remoteLabel, err) {
let warningMsg = `MetamaskInpageProvider - lost connection to ${remoteLabel}`
if (err) warningMsg += '\n' + err.stack
console.warn(warningMsg)
diff --git a/app/scripts/lib/is-popup-or-notification.js b/app/scripts/lib/is-popup-or-notification.js
index 693fa8751..e2999411f 100644
--- a/app/scripts/lib/is-popup-or-notification.js
+++ b/app/scripts/lib/is-popup-or-notification.js
@@ -1,6 +1,9 @@
module.exports = function isPopupOrNotification () {
const url = window.location.href
- if (url.match(/popup.html$/)) {
+ // if (url.match(/popup.html$/) || url.match(/home.html$/)) {
+ // Below regexes needed for feature toggles (e.g. see line ~340 in ui/app/app.js)
+ // Revert below regexes to above commented out regexes before merge to master
+ if (url.match(/popup.html(?:\?.+)*$/) || url.match(/home.html(?:\?.+)*$/)) {
return 'popup'
} else {
return 'notification'
diff --git a/app/scripts/lib/message-manager.js b/app/scripts/lib/message-manager.js
index 711d5f159..f52e048e0 100644
--- a/app/scripts/lib/message-manager.js
+++ b/app/scripts/lib/message-manager.js
@@ -4,7 +4,7 @@ const ethUtil = require('ethereumjs-util')
const createId = require('./random-id')
-module.exports = class MessageManager extends EventEmitter{
+module.exports = class MessageManager extends EventEmitter {
constructor (opts) {
super()
this.memStore = new ObservableStore({
@@ -108,7 +108,7 @@ module.exports = class MessageManager extends EventEmitter{
}
-function normalizeMsgData(data) {
+function normalizeMsgData (data) {
if (data.slice(0, 2) === '0x') {
// data is already hex
return data
diff --git a/app/scripts/lib/migrator/index.js b/app/scripts/lib/migrator/index.js
index 312345263..4fd2cae92 100644
--- a/app/scripts/lib/migrator/index.js
+++ b/app/scripts/lib/migrator/index.js
@@ -1,42 +1,35 @@
-const asyncQ = require('async-q')
-
class Migrator {
constructor (opts = {}) {
- let migrations = opts.migrations || []
+ const migrations = opts.migrations || []
+ // sort migrations by version
this.migrations = migrations.sort((a, b) => a.version - b.version)
- let lastMigration = this.migrations.slice(-1)[0]
+ // grab migration with highest version
+ const lastMigration = this.migrations.slice(-1)[0]
// use specified defaultVersion or highest migration version
this.defaultVersion = opts.defaultVersion || (lastMigration && lastMigration.version) || 0
}
// run all pending migrations on meta in place
- migrateData (versionedData = this.generateInitialState()) {
- let remaining = this.migrations.filter(migrationIsPending)
-
- return (
- asyncQ.eachSeries(remaining, (migration) => this.runMigration(versionedData, migration))
- .then(() => versionedData)
- )
-
- // migration is "pending" if hit has a higher
+ async migrateData (versionedData = this.generateInitialState()) {
+ const pendingMigrations = this.migrations.filter(migrationIsPending)
+
+ for (const index in pendingMigrations) {
+ const migration = pendingMigrations[index]
+ versionedData = await migration.migrate(versionedData)
+ if (!versionedData.data) throw new Error('Migrator - migration returned empty data')
+ if (versionedData.version !== undefined && versionedData.meta.version !== migration.version) throw new Error('Migrator - Migration did not update version number correctly')
+ }
+
+ return versionedData
+
+ // migration is "pending" if it has a higher
// version number than currentVersion
- function migrationIsPending(migration) {
+ function migrationIsPending (migration) {
return migration.version > versionedData.meta.version
}
}
- runMigration(versionedData, migration) {
- return (
- migration.migrate(versionedData)
- .then((versionedData) => {
- if (!versionedData.data) return Promise.reject(new Error('Migrator - Migration returned empty data'))
- if (migration.version !== undefined && versionedData.meta.version !== migration.version) return Promise.reject(new Error('Migrator - Migration did not update version number correctly'))
- return Promise.resolve(versionedData)
- })
- )
- }
-
generateInitialState (initState) {
return {
meta: {
diff --git a/app/scripts/lib/nodeify.js b/app/scripts/lib/nodeify.js
index 51d89a8fb..9b595d93c 100644
--- a/app/scripts/lib/nodeify.js
+++ b/app/scripts/lib/nodeify.js
@@ -1,24 +1,18 @@
-module.exports = function (promiseFn) {
- return function () {
- var args = []
- for (var i = 0; i < arguments.length - 1; i++) {
- args.push(arguments[i])
- }
- var cb = arguments[arguments.length - 1]
-
- const nodeified = promiseFn.apply(this, args)
+const promiseToCallback = require('promise-to-callback')
+const noop = function () {}
- if (!nodeified) {
- const methodName = String(promiseFn).split('(')[0]
- throw new Error(`The ${methodName} did not return a Promise, but was nodeified.`)
+module.exports = function nodeify (fn, context) {
+ return function () {
+ const args = [].slice.call(arguments)
+ const lastArg = args[args.length - 1]
+ const lastArgIsCallback = typeof lastArg === 'function'
+ let callback
+ if (lastArgIsCallback) {
+ callback = lastArg
+ args.pop()
+ } else {
+ callback = noop
}
- nodeified.then(function (result) {
- cb(null, result)
- })
- .catch(function (reason) {
- cb(reason)
- })
-
- return nodeified
+ promiseToCallback(fn.apply(context, args))(callback)
}
}
diff --git a/app/scripts/lib/nonce-tracker.js b/app/scripts/lib/nonce-tracker.js
new file mode 100644
index 000000000..ed9dd3f11
--- /dev/null
+++ b/app/scripts/lib/nonce-tracker.js
@@ -0,0 +1,149 @@
+const EthQuery = require('ethjs-query')
+const assert = require('assert')
+const Mutex = require('await-semaphore').Mutex
+
+class NonceTracker {
+
+ constructor ({ provider, getPendingTransactions, getConfirmedTransactions }) {
+ this.provider = provider
+ this.ethQuery = new EthQuery(provider)
+ this.getPendingTransactions = getPendingTransactions
+ this.getConfirmedTransactions = getConfirmedTransactions
+ this.lockMap = {}
+ }
+
+ async getGlobalLock () {
+ const globalMutex = this._lookupMutex('global')
+ // await global mutex free
+ const releaseLock = await globalMutex.acquire()
+ return { releaseLock }
+ }
+
+ // releaseLock must be called
+ // releaseLock must be called after adding signed tx to pending transactions (or discarding)
+ async getNonceLock (address) {
+ // await global mutex free
+ await this._globalMutexFree()
+ // await lock free, then take lock
+ const releaseLock = await this._takeMutex(address)
+ // evaluate multiple nextNonce strategies
+ const nonceDetails = {}
+ const networkNonceResult = await this._getNetworkNextNonce(address)
+ const highestLocallyConfirmed = this._getHighestLocallyConfirmed(address)
+ const nextNetworkNonce = networkNonceResult.nonce
+ const highestLocalNonce = highestLocallyConfirmed
+ const highestSuggested = Math.max(nextNetworkNonce, highestLocalNonce)
+
+ const pendingTxs = this.getPendingTransactions(address)
+ const localNonceResult = this._getHighestContinuousFrom(pendingTxs, highestSuggested) || 0
+
+ nonceDetails.params = {
+ highestLocalNonce,
+ highestSuggested,
+ nextNetworkNonce,
+ }
+ nonceDetails.local = localNonceResult
+ nonceDetails.network = networkNonceResult
+
+ const nextNonce = Math.max(networkNonceResult.nonce, localNonceResult.nonce)
+ assert(Number.isInteger(nextNonce), `nonce-tracker - nextNonce is not an integer - got: (${typeof nextNonce}) "${nextNonce}"`)
+
+ // return nonce and release cb
+ return { nextNonce, nonceDetails, releaseLock }
+ }
+
+ async _getCurrentBlock () {
+ const blockTracker = this._getBlockTracker()
+ const currentBlock = blockTracker.getCurrentBlock()
+ if (currentBlock) return currentBlock
+ return await new Promise((reject, resolve) => {
+ blockTracker.once('latest', resolve)
+ })
+ }
+
+ async _globalMutexFree () {
+ const globalMutex = this._lookupMutex('global')
+ const release = await globalMutex.acquire()
+ release()
+ }
+
+ async _takeMutex (lockId) {
+ const mutex = this._lookupMutex(lockId)
+ const releaseLock = await mutex.acquire()
+ return releaseLock
+ }
+
+ _lookupMutex (lockId) {
+ let mutex = this.lockMap[lockId]
+ if (!mutex) {
+ mutex = new Mutex()
+ this.lockMap[lockId] = mutex
+ }
+ return mutex
+ }
+
+ async _getNetworkNextNonce (address) {
+ // calculate next nonce
+ // we need to make sure our base count
+ // and pending count are from the same block
+ const currentBlock = await this._getCurrentBlock()
+ const blockNumber = currentBlock.blockNumber
+ const baseCountBN = await this.ethQuery.getTransactionCount(address, blockNumber || 'latest')
+ const baseCount = baseCountBN.toNumber()
+ assert(Number.isInteger(baseCount), `nonce-tracker - baseCount is not an integer - got: (${typeof baseCount}) "${baseCount}"`)
+ const nonceDetails = { blockNumber, baseCount }
+ return { name: 'network', nonce: baseCount, details: nonceDetails }
+ }
+
+ _getHighestLocallyConfirmed (address) {
+ const confirmedTransactions = this.getConfirmedTransactions(address)
+ const highest = this._getHighestNonce(confirmedTransactions)
+ return Number.isInteger(highest) ? highest + 1 : 0
+ }
+
+ _reduceTxListToUniqueNonces (txList) {
+ const reducedTxList = txList.reduce((reducedList, txMeta, index) => {
+ if (!index) return [txMeta]
+ const nonceMatches = txList.filter((txData) => {
+ return txMeta.txParams.nonce === txData.txParams.nonce
+ })
+ if (nonceMatches.length > 1) return reducedList
+ reducedList.push(txMeta)
+ return reducedList
+ }, [])
+ return reducedTxList
+ }
+
+ _getHighestNonce (txList) {
+ const nonces = txList.map((txMeta) => {
+ const nonce = txMeta.txParams.nonce
+ assert(typeof nonce, 'string', 'nonces should be hex strings')
+ return parseInt(nonce, 16)
+ })
+ const highestNonce = Math.max.apply(null, nonces)
+ return highestNonce
+ }
+
+ _getHighestContinuousFrom (txList, startPoint) {
+ const nonces = txList.map((txMeta) => {
+ const nonce = txMeta.txParams.nonce
+ assert(typeof nonce, 'string', 'nonces should be hex strings')
+ return parseInt(nonce, 16)
+ })
+
+ let highest = startPoint
+ while (nonces.includes(highest)) {
+ highest++
+ }
+
+ return { name: 'local', nonce: highest, details: { startPoint, highest } }
+ }
+
+ // this is a hotfix for the fact that the blockTracker will
+ // change when the network changes
+ _getBlockTracker () {
+ return this.provider._blockTracker
+ }
+}
+
+module.exports = NonceTracker
diff --git a/app/scripts/lib/notification-manager.js b/app/scripts/lib/notification-manager.js
index 55e5b8dd2..adaf60c65 100644
--- a/app/scripts/lib/notification-manager.js
+++ b/app/scripts/lib/notification-manager.js
@@ -1,5 +1,5 @@
const extension = require('extensionizer')
-const height = 520
+const height = 620
const width = 360
@@ -24,9 +24,6 @@ class NotificationManager {
width,
height,
})
- .catch((reason) => {
- log.error('failed to create poupup', reason)
- })
}
})
}
@@ -71,4 +68,4 @@ class NotificationManager {
}
-module.exports = NotificationManager \ No newline at end of file
+module.exports = NotificationManager
diff --git a/app/scripts/lib/obj-multiplex.js b/app/scripts/lib/obj-multiplex.js
deleted file mode 100644
index bd114c394..000000000
--- a/app/scripts/lib/obj-multiplex.js
+++ /dev/null
@@ -1,44 +0,0 @@
-const through = require('through2')
-
-module.exports = ObjectMultiplex
-
-function ObjectMultiplex (opts) {
- opts = opts || {}
- // create multiplexer
- var mx = through.obj(function (chunk, enc, cb) {
- var name = chunk.name
- var data = chunk.data
- var substream = mx.streams[name]
- if (!substream) {
- console.warn(`orphaned data for stream "${name}"`)
- } else {
- if (substream.push) substream.push(data)
- }
- return cb()
- })
- mx.streams = {}
- // create substreams
- mx.createStream = function (name) {
- var substream = mx.streams[name] = through.obj(function (chunk, enc, cb) {
- mx.push({
- name: name,
- data: chunk,
- })
- return cb()
- })
- mx.on('end', function () {
- return substream.emit('end')
- })
- if (opts.error) {
- mx.on('error', function () {
- return substream.emit('error')
- })
- }
- return substream
- }
- // ignore streams (dont display orphaned data warning)
- mx.ignoreStream = function (name) {
- mx.streams[name] = true
- }
- return mx
-}
diff --git a/app/scripts/lib/pending-balance-calculator.js b/app/scripts/lib/pending-balance-calculator.js
new file mode 100644
index 000000000..6ae526463
--- /dev/null
+++ b/app/scripts/lib/pending-balance-calculator.js
@@ -0,0 +1,51 @@
+const BN = require('ethereumjs-util').BN
+const normalize = require('eth-sig-util').normalize
+
+class PendingBalanceCalculator {
+
+ // Must be initialized with two functions:
+ // getBalance => Returns a promise of a BN of the current balance in Wei
+ // getPendingTransactions => Returns an array of TxMeta Objects,
+ // which have txParams properties, which include value, gasPrice, and gas,
+ // all in a base=16 hex format.
+ constructor ({ getBalance, getPendingTransactions }) {
+ this.getPendingTransactions = getPendingTransactions
+ this.getNetworkBalance = getBalance
+ }
+
+ async getBalance () {
+ const results = await Promise.all([
+ this.getNetworkBalance(),
+ this.getPendingTransactions(),
+ ])
+
+ const [ balance, pending ] = results
+ if (!balance) return undefined
+
+ const pendingValue = pending.reduce((total, tx) => {
+ return total.add(this.calculateMaxCost(tx))
+ }, new BN(0))
+
+ return `0x${balance.sub(pendingValue).toString(16)}`
+ }
+
+ calculateMaxCost (tx) {
+ const txValue = tx.txParams.value
+ const value = this.hexToBn(txValue)
+ const gasPrice = this.hexToBn(tx.txParams.gasPrice)
+
+ const gas = tx.txParams.gas
+ const gasLimit = tx.txParams.gasLimit
+ const gasLimitBn = this.hexToBn(gas || gasLimit)
+
+ const gasCost = gasPrice.mul(gasLimitBn)
+ return value.add(gasCost)
+ }
+
+ hexToBn (hex) {
+ return new BN(normalize(hex).substring(2), 16)
+ }
+
+}
+
+module.exports = PendingBalanceCalculator
diff --git a/app/scripts/lib/pending-tx-tracker.js b/app/scripts/lib/pending-tx-tracker.js
new file mode 100644
index 000000000..e8869e6b8
--- /dev/null
+++ b/app/scripts/lib/pending-tx-tracker.js
@@ -0,0 +1,189 @@
+const EventEmitter = require('events')
+const EthQuery = require('ethjs-query')
+/*
+
+ Utility class for tracking the transactions as they
+ go from a pending state to a confirmed (mined in a block) state
+
+ As well as continues broadcast while in the pending state
+
+ ~config is not optional~
+ requires a: {
+ provider: //,
+ nonceTracker: //see nonce tracker,
+ getPendingTransactions: //() a function for getting an array of transactions,
+ publishTransaction: //(rawTx) a async function for publishing raw transactions,
+ }
+
+*/
+
+module.exports = class PendingTransactionTracker extends EventEmitter {
+ constructor (config) {
+ super()
+ this.query = new EthQuery(config.provider)
+ this.nonceTracker = config.nonceTracker
+ // default is one day
+ this.getPendingTransactions = config.getPendingTransactions
+ this.getCompletedTransactions = config.getCompletedTransactions
+ this.publishTransaction = config.publishTransaction
+ this._checkPendingTxs()
+ }
+
+ // checks if a signed tx is in a block and
+ // if included sets the tx status as 'confirmed'
+ checkForTxInBlock (block) {
+ const signedTxList = this.getPendingTransactions()
+ if (!signedTxList.length) return
+ signedTxList.forEach((txMeta) => {
+ const txHash = txMeta.hash
+ const txId = txMeta.id
+
+ if (!txHash) {
+ const noTxHashErr = new Error('We had an error while submitting this transaction, please try again.')
+ noTxHashErr.name = 'NoTxHashError'
+ this.emit('tx:failed', txId, noTxHashErr)
+ return
+ }
+
+
+ block.transactions.forEach((tx) => {
+ if (tx.hash === txHash) this.emit('tx:confirmed', txId)
+ })
+ })
+ }
+
+ queryPendingTxs ({ oldBlock, newBlock }) {
+ // check pending transactions on start
+ if (!oldBlock) {
+ this._checkPendingTxs()
+ return
+ }
+ // if we synced by more than one block, check for missed pending transactions
+ const diff = Number.parseInt(newBlock.number, 16) - Number.parseInt(oldBlock.number, 16)
+ if (diff > 1) this._checkPendingTxs()
+ }
+
+
+ resubmitPendingTxs (block) {
+ const pending = this.getPendingTransactions()
+ // only try resubmitting if their are transactions to resubmit
+ if (!pending.length) return
+ pending.forEach((txMeta) => this._resubmitTx(txMeta, block.number).catch((err) => {
+ /*
+ Dont marked as failed if the error is a "known" transaction warning
+ "there is already a transaction with the same sender-nonce
+ but higher/same gas price"
+
+ Also don't mark as failed if it has ever been broadcast successfully.
+ A successful broadcast means it may still be mined.
+ */
+ const errorMessage = err.message.toLowerCase()
+ const isKnownTx = (
+ // geth
+ errorMessage.includes('replacement transaction underpriced') ||
+ errorMessage.includes('known transaction') ||
+ // parity
+ errorMessage.includes('gas price too low to replace') ||
+ errorMessage.includes('transaction with the same hash was already imported') ||
+ // other
+ errorMessage.includes('gateway timeout') ||
+ errorMessage.includes('nonce too low')
+ )
+ // ignore resubmit warnings, return early
+ if (isKnownTx) return
+ // encountered real error - transition to error state
+ txMeta.warning = {
+ error: errorMessage,
+ message: 'There was an error when resubmitting this transaction.',
+ }
+ this.emit('tx:warning', txMeta, err)
+ }))
+ }
+
+ async _resubmitTx (txMeta, latestBlockNumber) {
+ if (!txMeta.firstRetryBlockNumber) {
+ this.emit('tx:block-update', txMeta, latestBlockNumber)
+ }
+
+ const firstRetryBlockNumber = txMeta.firstRetryBlockNumber || latestBlockNumber
+ const txBlockDistance = Number.parseInt(latestBlockNumber, 16) - Number.parseInt(firstRetryBlockNumber, 16)
+
+ const retryCount = txMeta.retryCount || 0
+
+ // Exponential backoff to limit retries at publishing
+ if (txBlockDistance <= Math.pow(2, retryCount) - 1) return
+
+ // Only auto-submit already-signed txs:
+ if (!('rawTx' in txMeta)) return
+
+ const rawTx = txMeta.rawTx
+ const txHash = await this.publishTransaction(rawTx)
+
+ // Increment successful tries:
+ this.emit('tx:retry', txMeta)
+ return txHash
+ }
+
+ async _checkPendingTx (txMeta) {
+ const txHash = txMeta.hash
+ const txId = txMeta.id
+
+ // extra check in case there was an uncaught error during the
+ // signature and submission process
+ if (!txHash) {
+ const noTxHashErr = new Error('We had an error while submitting this transaction, please try again.')
+ noTxHashErr.name = 'NoTxHashError'
+ this.emit('tx:failed', txId, noTxHashErr)
+ return
+ }
+
+ // If another tx with the same nonce is mined, set as failed.
+ const taken = await this._checkIfNonceIsTaken(txMeta)
+ if (taken) {
+ const nonceTakenErr = new Error('Another transaction with this nonce has been mined.')
+ nonceTakenErr.name = 'NonceTakenErr'
+ return this.emit('tx:failed', txId, nonceTakenErr)
+ }
+
+ // get latest transaction status
+ let txParams
+ try {
+ txParams = await this.query.getTransactionByHash(txHash)
+ if (!txParams) return
+ if (txParams.blockNumber) {
+ this.emit('tx:confirmed', txId)
+ }
+ } catch (err) {
+ txMeta.warning = {
+ error: err.message,
+ message: 'There was a problem loading this transaction.',
+ }
+ this.emit('tx:warning', txMeta, err)
+ }
+ }
+
+ // checks the network for signed txs and
+ // if confirmed sets the tx status as 'confirmed'
+ async _checkPendingTxs () {
+ const signedTxList = this.getPendingTransactions()
+ // in order to keep the nonceTracker accurate we block it while updating pending transactions
+ const nonceGlobalLock = await this.nonceTracker.getGlobalLock()
+ try {
+ await Promise.all(signedTxList.map((txMeta) => this._checkPendingTx(txMeta)))
+ } catch (err) {
+ console.error('PendingTransactionWatcher - Error updating pending transactions')
+ console.error(err)
+ }
+ nonceGlobalLock.releaseLock()
+ }
+
+ async _checkIfNonceIsTaken (txMeta) {
+ const address = txMeta.txParams.from
+ const completed = this.getCompletedTransactions(address)
+ const sameNonce = completed.filter((otherMeta) => {
+ return otherMeta.txParams.nonce === txMeta.txParams.nonce
+ })
+ return sameNonce.length > 0
+ }
+
+}
diff --git a/app/scripts/lib/personal-message-manager.js b/app/scripts/lib/personal-message-manager.js
index bbc978446..6602f5aa8 100644
--- a/app/scripts/lib/personal-message-manager.js
+++ b/app/scripts/lib/personal-message-manager.js
@@ -5,7 +5,7 @@ const createId = require('./random-id')
const hexRe = /^[0-9A-Fa-f]+$/g
-module.exports = class PersonalMessageManager extends EventEmitter{
+module.exports = class PersonalMessageManager extends EventEmitter {
constructor (opts) {
super()
this.memStore = new ObservableStore({
@@ -108,7 +108,7 @@ module.exports = class PersonalMessageManager extends EventEmitter{
this.emit('updateBadge')
}
- normalizeMsgData(data) {
+ normalizeMsgData (data) {
try {
const stripped = ethUtil.stripHexPrefix(data)
if (stripped.match(hexRe)) {
diff --git a/app/scripts/lib/port-stream.js b/app/scripts/lib/port-stream.js
index 607a9c9ed..a9716fb00 100644
--- a/app/scripts/lib/port-stream.js
+++ b/app/scripts/lib/port-stream.js
@@ -1,5 +1,6 @@
const Duplex = require('readable-stream').Duplex
const inherits = require('util').inherits
+const noop = function () {}
module.exports = PortDuplexStream
@@ -20,20 +21,14 @@ PortDuplexStream.prototype._onMessage = function (msg) {
if (Buffer.isBuffer(msg)) {
delete msg._isBuffer
var data = new Buffer(msg)
- // console.log('PortDuplexStream - saw message as buffer', data)
this.push(data)
} else {
- // console.log('PortDuplexStream - saw message', msg)
this.push(msg)
}
}
PortDuplexStream.prototype._onDisconnect = function () {
- try {
- this.push(null)
- } catch (err) {
- this.emit('error', err)
- }
+ this.destroy()
}
// stream plumbing
@@ -45,19 +40,12 @@ PortDuplexStream.prototype._write = function (msg, encoding, cb) {
if (Buffer.isBuffer(msg)) {
var data = msg.toJSON()
data._isBuffer = true
- // console.log('PortDuplexStream - sent message as buffer', data)
this._port.postMessage(data)
} else {
- // console.log('PortDuplexStream - sent message', msg)
this._port.postMessage(msg)
}
} catch (err) {
- // console.error(err)
return cb(new Error('PortDuplexStream - disconnected'))
}
cb()
}
-
-// util
-
-function noop () {}
diff --git a/app/scripts/lib/setupMetamaskMeshMetrics.js b/app/scripts/lib/setupMetamaskMeshMetrics.js
new file mode 100644
index 000000000..40343f017
--- /dev/null
+++ b/app/scripts/lib/setupMetamaskMeshMetrics.js
@@ -0,0 +1,9 @@
+
+module.exports = setupMetamaskMeshMetrics
+
+function setupMetamaskMeshMetrics() {
+ const testingContainer = document.createElement('iframe')
+ testingContainer.src = 'https://metamask.github.io/mesh-testing/'
+ console.log('Injecting MetaMask Mesh testing client')
+ document.head.appendChild(testingContainer)
+}
diff --git a/app/scripts/lib/stream-utils.js b/app/scripts/lib/stream-utils.js
index ba79990cc..8bb0b4f3c 100644
--- a/app/scripts/lib/stream-utils.js
+++ b/app/scripts/lib/stream-utils.js
@@ -1,6 +1,6 @@
const Through = require('through2')
-const endOfStream = require('end-of-stream')
-const ObjectMultiplex = require('./obj-multiplex')
+const ObjectMultiplex = require('obj-multiplex')
+const pump = require('pump')
module.exports = {
jsonParseStream: jsonParseStream,
@@ -23,14 +23,14 @@ function jsonStringifyStream () {
}
function setupMultiplex (connectionStream) {
- var mx = ObjectMultiplex()
- connectionStream.pipe(mx).pipe(connectionStream)
- endOfStream(mx, function (err) {
- if (err) console.error(err)
- })
- endOfStream(connectionStream, function (err) {
- if (err) console.error(err)
- mx.destroy()
- })
- return mx
+ const mux = new ObjectMultiplex()
+ pump(
+ connectionStream,
+ mux,
+ connectionStream,
+ (err) => {
+ if (err) console.error(err)
+ }
+ )
+ return mux
}
diff --git a/app/scripts/lib/tx-gas-utils.js b/app/scripts/lib/tx-gas-utils.js
new file mode 100644
index 000000000..6f6ff7852
--- /dev/null
+++ b/app/scripts/lib/tx-gas-utils.js
@@ -0,0 +1,125 @@
+const EthQuery = require('ethjs-query')
+const {
+ hexToBn,
+ BnMultiplyByFraction,
+ bnToHex,
+} = require('./util')
+const addHexPrefix = require('ethereumjs-util').addHexPrefix
+const SIMPLE_GAS_COST = '0x5208' // Hex for 21000, cost of a simple send.
+
+/*
+tx-utils are utility methods for Transaction manager
+its passed ethquery
+and used to do things like calculate gas of a tx.
+*/
+
+module.exports = class TxGasUtil {
+
+ constructor (provider) {
+ this.query = new EthQuery(provider)
+ }
+
+ async analyzeGasUsage (txMeta) {
+ const block = await this.query.getBlockByNumber('latest', true)
+ let estimatedGasHex
+ try {
+ estimatedGasHex = await this.estimateTxGas(txMeta, block.gasLimit)
+ } catch (err) {
+ const simulationFailed = (
+ err.message.includes('Transaction execution error.') ||
+ err.message.includes('gas required exceeds allowance or always failing transaction')
+ )
+ if (simulationFailed) {
+ txMeta.simulationFails = true
+ return txMeta
+ }
+ }
+ this.setTxGas(txMeta, block.gasLimit, estimatedGasHex)
+ return txMeta
+ }
+
+ async estimateTxGas (txMeta, blockGasLimitHex) {
+ const txParams = txMeta.txParams
+
+ // check if gasLimit is already specified
+ txMeta.gasLimitSpecified = Boolean(txParams.gas)
+
+ // if it is, use that value
+ if (txMeta.gasLimitSpecified) {
+ return txParams.gas
+ }
+
+ // if recipient has no code, gas is 21k max:
+ const recipient = txParams.to
+ const hasRecipient = Boolean(recipient)
+ const code = await this.query.getCode(recipient)
+ if (hasRecipient && (!code || code === '0x')) {
+ txParams.gas = SIMPLE_GAS_COST
+ txMeta.simpleSend = true // Prevents buffer addition
+ return SIMPLE_GAS_COST
+ }
+
+ // if not, fall back to block gasLimit
+ const blockGasLimitBN = hexToBn(blockGasLimitHex)
+ const saferGasLimitBN = BnMultiplyByFraction(blockGasLimitBN, 19, 20)
+ txParams.gas = bnToHex(saferGasLimitBN)
+
+ // run tx
+ return await this.query.estimateGas(txParams)
+ }
+
+ setTxGas (txMeta, blockGasLimitHex, estimatedGasHex) {
+ txMeta.estimatedGas = addHexPrefix(estimatedGasHex)
+ const txParams = txMeta.txParams
+
+ // if gasLimit was specified and doesnt OOG,
+ // use original specified amount
+ if (txMeta.gasLimitSpecified || txMeta.simpleSend) {
+ txMeta.estimatedGas = txParams.gas
+ return
+ }
+ // if gasLimit not originally specified,
+ // try adding an additional gas buffer to our estimation for safety
+ const recommendedGasHex = this.addGasBuffer(txMeta.estimatedGas, blockGasLimitHex)
+ txParams.gas = recommendedGasHex
+ return
+ }
+
+ addGasBuffer (initialGasLimitHex, blockGasLimitHex) {
+ const initialGasLimitBn = hexToBn(initialGasLimitHex)
+ const blockGasLimitBn = hexToBn(blockGasLimitHex)
+ const upperGasLimitBn = blockGasLimitBn.muln(0.9)
+ const bufferedGasLimitBn = initialGasLimitBn.muln(1.5)
+
+ // if initialGasLimit is above blockGasLimit, dont modify it
+ if (initialGasLimitBn.gt(upperGasLimitBn)) return bnToHex(initialGasLimitBn)
+ // if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit
+ if (bufferedGasLimitBn.lt(upperGasLimitBn)) return bnToHex(bufferedGasLimitBn)
+ // otherwise use blockGasLimit
+ return bnToHex(upperGasLimitBn)
+ }
+
+ async validateTxParams (txParams) {
+ this.validateRecipient(txParams)
+ if ('value' in txParams) {
+ const value = txParams.value.toString()
+ if (value.includes('-')) {
+ throw new Error(`Invalid transaction value of ${txParams.value} not a positive number.`)
+ }
+
+ if (value.includes('.')) {
+ throw new Error(`Invalid transaction value of ${txParams.value} number must be in wei`)
+ }
+ }
+ }
+ validateRecipient (txParams) {
+ if (txParams.to === '0x') {
+ if (txParams.data) {
+ delete txParams.to
+ } else {
+ throw new Error('Invalid recipient address')
+ }
+ }
+ return txParams
+ }
+}
diff --git a/app/scripts/lib/tx-state-history-helper.js b/app/scripts/lib/tx-state-history-helper.js
new file mode 100644
index 000000000..94c7b6792
--- /dev/null
+++ b/app/scripts/lib/tx-state-history-helper.js
@@ -0,0 +1,41 @@
+const jsonDiffer = require('fast-json-patch')
+const clone = require('clone')
+
+module.exports = {
+ generateHistoryEntry,
+ replayHistory,
+ snapshotFromTxMeta,
+ migrateFromSnapshotsToDiffs,
+}
+
+
+function migrateFromSnapshotsToDiffs (longHistory) {
+ return (
+ longHistory
+ // convert non-initial history entries into diffs
+ .map((entry, index) => {
+ if (index === 0) return entry
+ return generateHistoryEntry(longHistory[index - 1], entry)
+ })
+ )
+}
+
+function generateHistoryEntry (previousState, newState, note) {
+ const entry = jsonDiffer.compare(previousState, newState)
+ // Add a note to the first op, since it breaks if we append it to the entry
+ if (note && entry[0]) entry[0].note = note
+ return entry
+}
+
+function replayHistory (_shortHistory) {
+ const shortHistory = clone(_shortHistory)
+ return shortHistory.reduce((val, entry) => jsonDiffer.applyPatch(val, entry).newDocument)
+}
+
+function snapshotFromTxMeta (txMeta) {
+ // create txMeta snapshot for history
+ const snapshot = clone(txMeta)
+ // dont include previous history in this snapshot
+ delete snapshot.history
+ return snapshot
+}
diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js
new file mode 100644
index 000000000..051efd247
--- /dev/null
+++ b/app/scripts/lib/tx-state-manager.js
@@ -0,0 +1,266 @@
+const extend = require('xtend')
+const EventEmitter = require('events')
+const ObservableStore = require('obs-store')
+const ethUtil = require('ethereumjs-util')
+const txStateHistoryHelper = require('./tx-state-history-helper')
+
+module.exports = class TransactionStateManger extends EventEmitter {
+ constructor ({ initState, txHistoryLimit, getNetwork }) {
+ super()
+
+ this.store = new ObservableStore(
+ extend({
+ transactions: [],
+ }, initState))
+ this.txHistoryLimit = txHistoryLimit
+ this.getNetwork = getNetwork
+ }
+
+ // Returns the number of txs for the current network.
+ getTxCount () {
+ return this.getTxList().length
+ }
+
+ getTxList () {
+ const network = this.getNetwork()
+ const fullTxList = this.getFullTxList()
+ return fullTxList.filter((txMeta) => txMeta.metamaskNetworkId === network)
+ }
+
+ getFullTxList () {
+ return this.store.getState().transactions
+ }
+
+ // Returns the tx list
+ getUnapprovedTxList () {
+ const txList = this.getTxsByMetaData('status', 'unapproved')
+ return txList.reduce((result, tx) => {
+ result[tx.id] = tx
+ return result
+ }, {})
+ }
+
+ getPendingTransactions (address) {
+ const opts = { status: 'submitted' }
+ if (address) opts.from = address
+ return this.getFilteredTxList(opts)
+ }
+
+ getConfirmedTransactions (address) {
+ const opts = { status: 'confirmed' }
+ if (address) opts.from = address
+ return this.getFilteredTxList(opts)
+ }
+
+ addTx (txMeta) {
+ this.once(`${txMeta.id}:signed`, function (txId) {
+ this.removeAllListeners(`${txMeta.id}:rejected`)
+ })
+ this.once(`${txMeta.id}:rejected`, function (txId) {
+ this.removeAllListeners(`${txMeta.id}:signed`)
+ })
+ // initialize history
+ txMeta.history = []
+ // capture initial snapshot of txMeta for history
+ const snapshot = txStateHistoryHelper.snapshotFromTxMeta(txMeta)
+ txMeta.history.push(snapshot)
+
+ const transactions = this.getFullTxList()
+ const txCount = this.getTxCount()
+ const txHistoryLimit = this.txHistoryLimit
+
+ // checks if the length of the tx history is
+ // longer then desired persistence limit
+ // and then if it is removes only confirmed
+ // or rejected tx's.
+ // not tx's that are pending or unapproved
+ if (txCount > txHistoryLimit - 1) {
+ const index = transactions.findIndex((metaTx) => metaTx.status === 'confirmed' || metaTx.status === 'rejected')
+ transactions.splice(index, 1)
+ }
+ transactions.push(txMeta)
+ this._saveTxList(transactions)
+ return txMeta
+ }
+ // gets tx by Id and returns it
+ getTx (txId) {
+ const txMeta = this.getTxsByMetaData('id', txId)[0]
+ return txMeta
+ }
+
+ updateTx (txMeta, note) {
+ if (txMeta.txParams) {
+ Object.keys(txMeta.txParams).forEach((key) => {
+ const value = txMeta.txParams[key]
+ if (typeof value !== 'string') console.error(`${key}: ${value} in txParams is not a string`)
+ if (!ethUtil.isHexPrefixed(value)) console.error('is not hex prefixed, anything on txParams must be hex prefixed')
+ })
+ }
+
+ // create txMeta snapshot for history
+ const currentState = txStateHistoryHelper.snapshotFromTxMeta(txMeta)
+ // recover previous tx state obj
+ const previousState = txStateHistoryHelper.replayHistory(txMeta.history)
+ // generate history entry and add to history
+ const entry = txStateHistoryHelper.generateHistoryEntry(previousState, currentState, note)
+ txMeta.history.push(entry)
+
+ // commit txMeta to state
+ const txId = txMeta.id
+ const txList = this.getFullTxList()
+ const index = txList.findIndex(txData => txData.id === txId)
+ txList[index] = txMeta
+ this._saveTxList(txList)
+ }
+
+
+ // merges txParams obj onto txData.txParams
+ // use extend to ensure that all fields are filled
+ updateTxParams (txId, txParams) {
+ const txMeta = this.getTx(txId)
+ txMeta.txParams = extend(txMeta.txParams, txParams)
+ this.updateTx(txMeta, `txStateManager#updateTxParams`)
+ }
+
+/*
+ Takes an object of fields to search for eg:
+ let thingsToLookFor = {
+ to: '0x0..',
+ from: '0x0..',
+ status: 'signed',
+ err: undefined,
+ }
+ and returns a list of tx with all
+ options matching
+
+ ****************HINT****************
+ | `err: undefined` is like looking |
+ | for a tx with no err |
+ | so you can also search txs that |
+ | dont have something as well by |
+ | setting the value as undefined |
+ ************************************
+
+ this is for things like filtering a the tx list
+ for only tx's from 1 account
+ or for filltering for all txs from one account
+ and that have been 'confirmed'
+ */
+ getFilteredTxList (opts, initialList) {
+ let filteredTxList = initialList
+ Object.keys(opts).forEach((key) => {
+ filteredTxList = this.getTxsByMetaData(key, opts[key], filteredTxList)
+ })
+ return filteredTxList
+ }
+
+ getTxsByMetaData (key, value, txList = this.getTxList()) {
+ return txList.filter((txMeta) => {
+ if (txMeta.txParams[key]) {
+ return txMeta.txParams[key] === value
+ } else {
+ return txMeta[key] === value
+ }
+ })
+ }
+
+ // STATUS METHODS
+ // statuses:
+ // - `'unapproved'` the user has not responded
+ // - `'rejected'` the user has responded no!
+ // - `'approved'` the user has approved the tx
+ // - `'signed'` the tx is signed
+ // - `'submitted'` the tx is sent to a server
+ // - `'confirmed'` the tx has been included in a block.
+ // - `'failed'` the tx failed for some reason, included on tx data.
+
+ // get::set status
+
+ // should return the status of the tx.
+ getTxStatus (txId) {
+ const txMeta = this.getTx(txId)
+ return txMeta.status
+ }
+
+ // should update the status of the tx to 'rejected'.
+ setTxStatusRejected (txId) {
+ this._setTxStatus(txId, 'rejected')
+ }
+
+ // should update the status of the tx to 'unapproved'.
+ setTxStatusUnapproved (txId) {
+ this._setTxStatus(txId, 'unapproved')
+ }
+ // should update the status of the tx to 'approved'.
+ setTxStatusApproved (txId) {
+ this._setTxStatus(txId, 'approved')
+ }
+
+ // should update the status of the tx to 'signed'.
+ setTxStatusSigned (txId) {
+ this._setTxStatus(txId, 'signed')
+ }
+
+ // should update the status of the tx to 'submitted'.
+ setTxStatusSubmitted (txId) {
+ this._setTxStatus(txId, 'submitted')
+ }
+
+ // should update the status of the tx to 'confirmed'.
+ setTxStatusConfirmed (txId) {
+ this._setTxStatus(txId, 'confirmed')
+ }
+
+ setTxStatusFailed (txId, err) {
+ const txMeta = this.getTx(txId)
+ txMeta.err = {
+ message: err.toString(),
+ stack: err.stack,
+ }
+ this.updateTx(txMeta)
+ this._setTxStatus(txId, 'failed')
+ }
+
+ wipeTransactions (address) {
+ // network only tx
+ const txs = this.getFullTxList()
+ const network = this.getNetwork()
+
+ // Filter out the ones from the current account and network
+ const otherAccountTxs = txs.filter((txMeta) => !(txMeta.txParams.from === address && txMeta.metamaskNetworkId === network))
+
+ // Update state
+ this._saveTxList(otherAccountTxs)
+ }
+//
+// PRIVATE METHODS
+//
+
+ // Should find the tx in the tx list and
+ // update it.
+ // should set the status in txData
+ // - `'unapproved'` the user has not responded
+ // - `'rejected'` the user has responded no!
+ // - `'approved'` the user has approved the tx
+ // - `'signed'` the tx is signed
+ // - `'submitted'` the tx is sent to a server
+ // - `'confirmed'` the tx has been included in a block.
+ // - `'failed'` the tx failed for some reason, included on tx data.
+ _setTxStatus (txId, status) {
+ const txMeta = this.getTx(txId)
+ txMeta.status = status
+ this.emit(`${txMeta.id}:${status}`, txId)
+ this.emit(`tx:status-update`, txId, status)
+ if (['submitted', 'rejected', 'failed'].includes(status)) {
+ this.emit(`${txMeta.id}:finished`, txMeta)
+ }
+ this.updateTx(txMeta, `txStateManager: setting status to ${status}`)
+ this.emit('update:badge')
+ }
+
+ // Saves the new/updated txList.
+ // Function is intended only for internal use
+ _saveTxList (transactions) {
+ this.store.updateState({ transactions })
+ }
+}
diff --git a/app/scripts/lib/tx-utils.js b/app/scripts/lib/tx-utils.js
deleted file mode 100644
index e8e23f8b5..000000000
--- a/app/scripts/lib/tx-utils.js
+++ /dev/null
@@ -1,136 +0,0 @@
-const async = require('async')
-const EthQuery = require('eth-query')
-const ethUtil = require('ethereumjs-util')
-const Transaction = require('ethereumjs-tx')
-const normalize = require('eth-sig-util').normalize
-const BN = ethUtil.BN
-
-/*
-tx-utils are utility methods for Transaction manager
-its passed a provider and that is passed to ethquery
-and used to do things like calculate gas of a tx.
-*/
-
-module.exports = class txProviderUtils {
-
- constructor (provider) {
- this.provider = provider
- this.query = new EthQuery(provider)
- }
-
- analyzeGasUsage (txMeta, cb) {
- var self = this
- this.query.getBlockByNumber('latest', true, (err, block) => {
- if (err) return cb(err)
- async.waterfall([
- self.estimateTxGas.bind(self, txMeta, block.gasLimit),
- self.setTxGas.bind(self, txMeta, block.gasLimit),
- ], cb)
- })
- }
-
- estimateTxGas (txMeta, blockGasLimitHex, cb) {
- const txParams = txMeta.txParams
- // check if gasLimit is already specified
- txMeta.gasLimitSpecified = Boolean(txParams.gas)
- // if not, fallback to block gasLimit
- if (!txMeta.gasLimitSpecified) {
- txParams.gas = blockGasLimitHex
- }
- // run tx, see if it will OOG
- this.query.estimateGas(txParams, cb)
- }
-
- setTxGas (txMeta, blockGasLimitHex, estimatedGasHex, cb) {
- txMeta.estimatedGas = estimatedGasHex
- const txParams = txMeta.txParams
-
- // if gasLimit was specified and doesnt OOG,
- // use original specified amount
- if (txMeta.gasLimitSpecified) {
- txMeta.estimatedGas = txParams.gas
- cb()
- return
- }
- // if gasLimit not originally specified,
- // try adding an additional gas buffer to our estimation for safety
- const recommendedGasHex = this.addGasBuffer(txMeta.estimatedGas, blockGasLimitHex)
- txParams.gas = recommendedGasHex
- cb()
- return
- }
-
- addGasBuffer (initialGasLimitHex, blockGasLimitHex) {
- const initialGasLimitBn = hexToBn(initialGasLimitHex)
- const blockGasLimitBn = hexToBn(blockGasLimitHex)
- const upperGasLimitBn = blockGasLimitBn.muln(0.9)
- const bufferedGasLimitBn = initialGasLimitBn.muln(1.5)
-
- // if initialGasLimit is above blockGasLimit, dont modify it
- if (initialGasLimitBn.gt(upperGasLimitBn)) return bnToHex(initialGasLimitBn)
- // if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit
- if (bufferedGasLimitBn.lt(upperGasLimitBn)) return bnToHex(bufferedGasLimitBn)
- // otherwise use blockGasLimit
- return bnToHex(upperGasLimitBn)
- }
-
- fillInTxParams (txParams, cb) {
- let fromAddress = txParams.from
- let reqs = {}
-
- if (isUndef(txParams.gas)) reqs.gas = (cb) => this.query.estimateGas(txParams, cb)
- if (isUndef(txParams.gasPrice)) reqs.gasPrice = (cb) => this.query.gasPrice(cb)
- if (isUndef(txParams.nonce)) reqs.nonce = (cb) => this.query.getTransactionCount(fromAddress, 'pending', cb)
-
- async.parallel(reqs, function(err, result) {
- if (err) return cb(err)
- // write results to txParams obj
- Object.assign(txParams, result)
- cb()
- })
- }
-
- // builds ethTx from txParams object
- buildEthTxFromParams (txParams) {
- // normalize values
- txParams.to = normalize(txParams.to)
- txParams.from = normalize(txParams.from)
- txParams.value = normalize(txParams.value)
- txParams.data = normalize(txParams.data)
- txParams.gas = normalize(txParams.gas || txParams.gasLimit)
- txParams.gasPrice = normalize(txParams.gasPrice)
- txParams.nonce = normalize(txParams.nonce)
- // build ethTx
- log.info(`Prepared tx for signing: ${JSON.stringify(txParams)}`)
- const ethTx = new Transaction(txParams)
- return ethTx
- }
-
- publishTransaction (rawTx, cb) {
- this.query.sendRawTransaction(rawTx, cb)
- }
-
- validateTxParams (txParams, cb) {
- if (('value' in txParams) && txParams.value.indexOf('-') === 0) {
- cb(new Error(`Invalid transaction value of ${txParams.value} not a positive number.`))
- } else {
- cb()
- }
- }
-
-
-}
-
-// util
-
-function isUndef(value) {
- return value === undefined
-}
-
-function bnToHex(inputBn) {
- return ethUtil.addHexPrefix(inputBn.toString(16))
-}
-
-function hexToBn(inputHex) {
- return new BN(ethUtil.stripHexPrefix(inputHex), 16)
-}
diff --git a/app/scripts/lib/typed-message-manager.js b/app/scripts/lib/typed-message-manager.js
new file mode 100644
index 000000000..8b760790e
--- /dev/null
+++ b/app/scripts/lib/typed-message-manager.js
@@ -0,0 +1,123 @@
+const EventEmitter = require('events')
+const ObservableStore = require('obs-store')
+const createId = require('./random-id')
+const assert = require('assert')
+const sigUtil = require('eth-sig-util')
+
+
+module.exports = class TypedMessageManager extends EventEmitter {
+ constructor (opts) {
+ super()
+ this.memStore = new ObservableStore({
+ unapprovedTypedMessages: {},
+ unapprovedTypedMessagesCount: 0,
+ })
+ this.messages = []
+ }
+
+ get unapprovedTypedMessagesCount () {
+ return Object.keys(this.getUnapprovedMsgs()).length
+ }
+
+ getUnapprovedMsgs () {
+ return this.messages.filter(msg => msg.status === 'unapproved')
+ .reduce((result, msg) => { result[msg.id] = msg; return result }, {})
+ }
+
+ addUnapprovedMessage (msgParams) {
+ this.validateParams(msgParams)
+
+ log.debug(`TypedMessageManager addUnapprovedMessage: ${JSON.stringify(msgParams)}`)
+ // create txData obj with parameters and meta data
+ var time = (new Date()).getTime()
+ var msgId = createId()
+ var msgData = {
+ id: msgId,
+ msgParams: msgParams,
+ time: time,
+ status: 'unapproved',
+ type: 'eth_signTypedData',
+ }
+ this.addMsg(msgData)
+
+ // signal update
+ this.emit('update')
+ return msgId
+ }
+
+ validateParams (params) {
+ assert.equal(typeof params, 'object', 'Params should ben an object.')
+ assert.ok('data' in params, 'Params must include a data field.')
+ assert.ok('from' in params, 'Params must include a from field.')
+ assert.ok(Array.isArray(params.data), 'Data should be an array.')
+ assert.equal(typeof params.from, 'string', 'From field must be a string.')
+ assert.doesNotThrow(() => {
+ sigUtil.typedSignatureHash(params.data)
+ }, 'Expected EIP712 typed data')
+ }
+
+ addMsg (msg) {
+ this.messages.push(msg)
+ this._saveMsgList()
+ }
+
+ getMsg (msgId) {
+ return this.messages.find(msg => msg.id === msgId)
+ }
+
+ approveMessage (msgParams) {
+ this.setMsgStatusApproved(msgParams.metamaskId)
+ return this.prepMsgForSigning(msgParams)
+ }
+
+ setMsgStatusApproved (msgId) {
+ this._setMsgStatus(msgId, 'approved')
+ }
+
+ setMsgStatusSigned (msgId, rawSig) {
+ const msg = this.getMsg(msgId)
+ msg.rawSig = rawSig
+ this._updateMsg(msg)
+ this._setMsgStatus(msgId, 'signed')
+ }
+
+ prepMsgForSigning (msgParams) {
+ delete msgParams.metamaskId
+ return Promise.resolve(msgParams)
+ }
+
+ rejectMsg (msgId) {
+ this._setMsgStatus(msgId, 'rejected')
+ }
+
+ //
+ // PRIVATE METHODS
+ //
+
+ _setMsgStatus (msgId, status) {
+ const msg = this.getMsg(msgId)
+ if (!msg) throw new Error('TypedMessageManager - Message not found for id: "${msgId}".')
+ msg.status = status
+ this._updateMsg(msg)
+ this.emit(`${msgId}:${status}`, msg)
+ if (status === 'rejected' || status === 'signed') {
+ this.emit(`${msgId}:finished`, msg)
+ }
+ }
+
+ _updateMsg (msg) {
+ const index = this.messages.findIndex((message) => message.id === msg.id)
+ if (index !== -1) {
+ this.messages[index] = msg
+ }
+ this._saveMsgList()
+ }
+
+ _saveMsgList () {
+ const unapprovedTypedMessages = this.getUnapprovedMsgs()
+ const unapprovedTypedMessagesCount = Object.keys(unapprovedTypedMessages).length
+ this.memStore.updateState({ unapprovedTypedMessages, unapprovedTypedMessagesCount })
+ this.emit('updateBadge')
+ }
+
+}
diff --git a/app/scripts/lib/util.js b/app/scripts/lib/util.js
new file mode 100644
index 000000000..6dee9edf0
--- /dev/null
+++ b/app/scripts/lib/util.js
@@ -0,0 +1,44 @@
+const ethUtil = require('ethereumjs-util')
+const assert = require('assert')
+const BN = require('bn.js')
+
+module.exports = {
+ getStack,
+ sufficientBalance,
+ hexToBn,
+ bnToHex,
+ BnMultiplyByFraction,
+}
+
+function getStack () {
+ const stack = new Error('Stack trace generator - not an error').stack
+ return stack
+}
+
+function sufficientBalance (txParams, hexBalance) {
+ // validate hexBalance is a hex string
+ assert.equal(typeof hexBalance, 'string', 'sufficientBalance - hexBalance is not a hex string')
+ assert.equal(hexBalance.slice(0, 2), '0x', 'sufficientBalance - hexBalance is not a hex string')
+
+ const balance = hexToBn(hexBalance)
+ const value = hexToBn(txParams.value)
+ const gasLimit = hexToBn(txParams.gas)
+ const gasPrice = hexToBn(txParams.gasPrice)
+
+ const maxCost = value.add(gasLimit.mul(gasPrice))
+ return balance.gte(maxCost)
+}
+
+function bnToHex (inputBn) {
+ return ethUtil.addHexPrefix(inputBn.toString(16))
+}
+
+function hexToBn (inputHex) {
+ return new BN(ethUtil.stripHexPrefix(inputHex), 16)
+}
+
+function BnMultiplyByFraction (targetBN, numerator, denominator) {
+ const numBN = new BN(numerator)
+ const denomBN = new BN(denominator)
+ return targetBN.mul(numBN).div(denomBN)
+}
diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 2b8fc9cb8..ad4e71792 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -1,38 +1,55 @@
const EventEmitter = require('events')
const extend = require('xtend')
-const promiseToCallback = require('promise-to-callback')
-const pipe = require('pump')
+const pump = require('pump')
const Dnode = require('dnode')
const ObservableStore = require('obs-store')
-const storeTransform = require('obs-store/lib/transform')
-const EthStore = require('./lib/eth-store')
-const EthQuery = require('eth-query')
-const streamIntoProvider = require('web3-stream-provider/handler')
-const MetaMaskProvider = require('web3-provider-engine/zero.js')
+const asStream = require('obs-store/lib/asStream')
+const AccountTracker = require('./lib/account-tracker')
+const RpcEngine = require('json-rpc-engine')
+const debounce = require('debounce')
+const createEngineStream = require('json-rpc-middleware-stream/engineStream')
+const createFilterMiddleware = require('eth-json-rpc-filters')
+const createOriginMiddleware = require('./lib/createOriginMiddleware')
+const createLoggerMiddleware = require('./lib/createLoggerMiddleware')
+const createProviderMiddleware = require('./lib/createProviderMiddleware')
const setupMultiplex = require('./lib/stream-utils.js').setupMultiplex
-const KeyringController = require('./keyring-controller')
+const KeyringController = require('eth-keyring-controller')
+const NetworkController = require('./controllers/network')
const PreferencesController = require('./controllers/preferences')
const CurrencyController = require('./controllers/currency')
const NoticeController = require('./notice-controller')
const ShapeShiftController = require('./controllers/shapeshift')
const AddressBookController = require('./controllers/address-book')
+const InfuraController = require('./controllers/infura')
+const BlacklistController = require('./controllers/blacklist')
+const RecentBlocksController = require('./controllers/recent-blocks')
const MessageManager = require('./lib/message-manager')
const PersonalMessageManager = require('./lib/personal-message-manager')
-const TxManager = require('./transaction-manager')
+const TypedMessageManager = require('./lib/typed-message-manager')
+const TransactionController = require('./controllers/transactions')
+const BalancesController = require('./controllers/computed-balances')
const ConfigManager = require('./lib/config-manager')
-const autoFaucet = require('./lib/auto-faucet')
const nodeify = require('./lib/nodeify')
const accountImporter = require('./account-import-strategies')
const getBuyEthUrl = require('./lib/buy-eth-url')
-
+const Mutex = require('await-semaphore').Mutex
const version = require('../manifest.json').version
+const BN = require('ethereumjs-util').BN
+const GWEI_BN = new BN('1000000000')
+const percentile = require('percentile')
module.exports = class MetamaskController extends EventEmitter {
constructor (opts) {
super()
+
+ this.defaultMaxListeners = 20
+
+ this.sendUpdate = debounce(this.privateSendUpdate.bind(this), 200)
+
this.opts = opts
- let initState = opts.initState || {}
+ const initState = opts.initState || {}
+ this.recordFirstTimeInfo(initState)
// platform-specific api
this.platform = opts.platform
@@ -40,8 +57,11 @@ module.exports = class MetamaskController extends EventEmitter {
// observable state store
this.store = new ObservableStore(initState)
+ // lock to ensure only one vault created at once
+ this.createVaultMutex = new Mutex()
+
// network store
- this.networkStore = new ObservableStore({ network: 'loading' })
+ this.networkController = new NetworkController(initState.NetworkController)
// config manager
this.configManager = new ConfigManager({
@@ -60,29 +80,47 @@ module.exports = class MetamaskController extends EventEmitter {
this.currencyController.updateConversionRate()
this.currencyController.scheduleConversionInterval()
+ // infura controller
+ this.infuraController = new InfuraController({
+ initState: initState.InfuraController,
+ })
+ this.infuraController.scheduleInfuraNetworkCheck()
+
+ this.blacklistController = new BlacklistController()
+ this.blacklistController.scheduleUpdates()
+
// rpc provider
this.provider = this.initializeProvider()
- this.provider.on('block', this.logBlock.bind(this))
- this.provider.on('error', this.verifyNetwork.bind(this))
+ this.blockTracker = this.provider._blockTracker
+
+ this.recentBlocksController = new RecentBlocksController({
+ blockTracker: this.blockTracker,
+ provider: this.provider,
+ })
- // eth data query tools
- this.ethQuery = new EthQuery(this.provider)
- this.ethStore = new EthStore({
+ // account tracker watches balances, nonces, and any code at their address.
+ this.accountTracker = new AccountTracker({
provider: this.provider,
- blockTracker: this.provider,
+ blockTracker: this.blockTracker,
})
// key mgmt
this.keyringController = new KeyringController({
initState: initState.KeyringController,
- ethStore: this.ethStore,
- getNetwork: this.getNetworkState.bind(this),
- })
- this.keyringController.on('newAccount', (address) => {
- this.preferencesController.setSelectedAddress(address)
+ getNetwork: this.networkController.getNetworkState.bind(this.networkController),
+ encryptor: opts.encryptor || undefined,
})
- this.keyringController.on('newVault', (address) => {
- autoFaucet(address)
+
+ // If only one account exists, make sure it is selected.
+ this.keyringController.memStore.subscribe((state) => {
+ const addresses = state.keyrings.reduce((res, keyring) => {
+ return res.concat(keyring.accounts)
+ }, [])
+ if (addresses.length === 1) {
+ const address = addresses[0]
+ this.preferencesController.setSelectedAddress(address)
+ }
+ this.accountTracker.syncWithAddresses(addresses)
})
// address book controller
@@ -91,20 +129,35 @@ module.exports = class MetamaskController extends EventEmitter {
}, this.keyringController)
// tx mgmt
- this.txManager = new TxManager({
- initState: initState.TransactionManager,
- networkStore: this.networkStore,
+ this.txController = new TransactionController({
+ initState: initState.TransactionController || initState.TransactionManager,
+ networkStore: this.networkController.networkStore,
preferencesStore: this.preferencesController.store,
txHistoryLimit: 40,
- getNetwork: this.getNetworkState.bind(this),
+ getNetwork: this.networkController.getNetworkState.bind(this),
signTransaction: this.keyringController.signTransaction.bind(this.keyringController),
provider: this.provider,
- blockTracker: this.provider,
+ blockTracker: this.blockTracker,
+ getGasPrice: this.getGasPrice.bind(this),
})
+ this.txController.on('newUnapprovedTx', opts.showUnapprovedTx.bind(opts))
+
+ // computed balances (accounting for pending transactions)
+ this.balancesController = new BalancesController({
+ accountTracker: this.accountTracker,
+ txController: this.txController,
+ blockTracker: this.blockTracker,
+ })
+ this.networkController.on('networkDidChange', () => {
+ this.balancesController.updateAllBalances()
+ })
+ this.balancesController.updateAllBalances()
// notices
this.noticeController = new NoticeController({
initState: initState.NoticeController,
+ version,
+ firstVersion: initState.firstTimeInfo.version,
})
this.noticeController.updateNoticesList()
// to be uncommented when retrieving notices from a remote server.
@@ -114,14 +167,15 @@ module.exports = class MetamaskController extends EventEmitter {
initState: initState.ShapeShiftController,
})
- this.lookupNetwork()
+ this.networkController.lookupNetwork()
this.messageManager = new MessageManager()
this.personalMessageManager = new PersonalMessageManager()
+ this.typedMessageManager = new TypedMessageManager()
this.publicConfigStore = this.initPublicConfigStore()
// manual disk state subscriptions
- this.txManager.store.subscribe((state) => {
- this.store.updateState({ TransactionManager: state })
+ this.txController.store.subscribe((state) => {
+ this.store.updateState({ TransactionController: state })
})
this.keyringController.store.subscribe((state) => {
this.store.updateState({ KeyringController: state })
@@ -141,19 +195,31 @@ module.exports = class MetamaskController extends EventEmitter {
this.shapeshiftController.store.subscribe((state) => {
this.store.updateState({ ShapeShiftController: state })
})
+ this.networkController.store.subscribe((state) => {
+ this.store.updateState({ NetworkController: state })
+ })
+
+ this.infuraController.store.subscribe((state) => {
+ this.store.updateState({ InfuraController: state })
+ })
// manual mem state subscriptions
- this.networkStore.subscribe(this.sendUpdate.bind(this))
- this.ethStore.subscribe(this.sendUpdate.bind(this))
- this.txManager.memStore.subscribe(this.sendUpdate.bind(this))
- this.messageManager.memStore.subscribe(this.sendUpdate.bind(this))
- this.personalMessageManager.memStore.subscribe(this.sendUpdate.bind(this))
- this.keyringController.memStore.subscribe(this.sendUpdate.bind(this))
- this.preferencesController.store.subscribe(this.sendUpdate.bind(this))
- this.addressBookController.store.subscribe(this.sendUpdate.bind(this))
- this.currencyController.store.subscribe(this.sendUpdate.bind(this))
- this.noticeController.memStore.subscribe(this.sendUpdate.bind(this))
- this.shapeshiftController.store.subscribe(this.sendUpdate.bind(this))
+ const sendUpdate = this.sendUpdate.bind(this)
+ this.networkController.store.subscribe(sendUpdate)
+ this.accountTracker.store.subscribe(sendUpdate)
+ this.txController.memStore.subscribe(sendUpdate)
+ this.balancesController.store.subscribe(sendUpdate)
+ this.messageManager.memStore.subscribe(sendUpdate)
+ this.personalMessageManager.memStore.subscribe(sendUpdate)
+ this.typedMessageManager.memStore.subscribe(sendUpdate)
+ this.keyringController.memStore.subscribe(sendUpdate)
+ this.preferencesController.store.subscribe(sendUpdate)
+ this.recentBlocksController.store.subscribe(sendUpdate)
+ this.addressBookController.store.subscribe(sendUpdate)
+ this.currencyController.store.subscribe(sendUpdate)
+ this.noticeController.memStore.subscribe(sendUpdate)
+ this.shapeshiftController.store.subscribe(sendUpdate)
+ this.infuraController.store.subscribe(sendUpdate)
}
//
@@ -161,47 +227,50 @@ module.exports = class MetamaskController extends EventEmitter {
//
initializeProvider () {
-
- let provider = MetaMaskProvider({
+ const providerOpts = {
static: {
eth_syncing: false,
web3_clientVersion: `MetaMask/v${version}`,
},
- rpcUrl: this.configManager.getCurrentRpcAddress(),
// account mgmt
getAccounts: (cb) => {
- let selectedAddress = this.preferencesController.getSelectedAddress()
- let result = selectedAddress ? [selectedAddress] : []
+ const isUnlocked = this.keyringController.memStore.getState().isUnlocked
+ const result = []
+ const selectedAddress = this.preferencesController.getSelectedAddress()
+
+ // only show address if account is unlocked
+ if (isUnlocked && selectedAddress) {
+ result.push(selectedAddress)
+ }
cb(null, result)
},
// tx signing
- processTransaction: (txParams, cb) => this.newUnapprovedTransaction(txParams, cb),
+ processTransaction: nodeify(async (txParams) => await this.txController.newUnapprovedTransaction(txParams), this),
// old style msg signing
processMessage: this.newUnsignedMessage.bind(this),
-
- // new style msg signing
+ // personal_sign msg signing
processPersonalMessage: this.newUnsignedPersonalMessage.bind(this),
- })
- return provider
+ processTypedMessage: this.newUnsignedTypedMessage.bind(this),
+ }
+ const providerProxy = this.networkController.initializeProvider(providerOpts)
+ return providerProxy
}
initPublicConfigStore () {
// get init state
const publicConfigStore = new ObservableStore()
- // sync publicConfigStore with transform
- pipe(
- this.store,
- storeTransform(selectPublicState.bind(this)),
- publicConfigStore
- )
+ // memStore -> transform -> publicConfigStore
+ this.on('update', (memState) => {
+ const publicState = selectPublicState(memState)
+ publicConfigStore.putState(publicState)
+ })
- function selectPublicState(state) {
- const result = { selectedAddress: undefined }
- try {
- result.selectedAddress = state.PreferencesController.selectedAddress
- result.networkVersion = this.getNetworkState()
- } catch (_) {}
+ function selectPublicState (memState) {
+ const result = {
+ selectedAddress: memState.isUnlocked ? memState.selectedAddress : undefined,
+ networkVersion: memState.network,
+ }
return result
}
@@ -216,26 +285,32 @@ module.exports = class MetamaskController extends EventEmitter {
const wallet = this.configManager.getWallet()
const vault = this.keyringController.store.getState().vault
const isInitialized = (!!wallet || !!vault)
+
return extend(
{
isInitialized,
},
- this.networkStore.getState(),
- this.ethStore.getState(),
- this.txManager.memStore.getState(),
+ this.networkController.store.getState(),
+ this.accountTracker.store.getState(),
+ this.txController.memStore.getState(),
this.messageManager.memStore.getState(),
this.personalMessageManager.memStore.getState(),
+ this.typedMessageManager.memStore.getState(),
this.keyringController.memStore.getState(),
+ this.balancesController.store.getState(),
this.preferencesController.store.getState(),
this.addressBookController.store.getState(),
this.currencyController.store.getState(),
this.noticeController.memStore.getState(),
+ this.infuraController.store.getState(),
+ this.recentBlocksController.store.getState(),
// config manager
this.configManager.getConfig(),
this.shapeshiftController.store.getState(),
{
lostAccounts: this.configManager.getLostAccounts(),
seedWords: this.configManager.getSeedWords(),
+ forgottenPassword: this.configManager.getPasswordForgotten(),
}
)
}
@@ -247,86 +322,122 @@ module.exports = class MetamaskController extends EventEmitter {
getApi () {
const keyringController = this.keyringController
const preferencesController = this.preferencesController
- const txManager = this.txManager
+ const txController = this.txController
const noticeController = this.noticeController
const addressBookController = this.addressBookController
+ const networkController = this.networkController
return {
// etc
- getState: (cb) => cb(null, this.getState()),
- setProviderType: this.setProviderType.bind(this),
- useEtherscanProvider: this.useEtherscanProvider.bind(this),
- setCurrentCurrency: this.setCurrentCurrency.bind(this),
- markAccountsFound: this.markAccountsFound.bind(this),
+ getState: (cb) => cb(null, this.getState()),
+ setCurrentCurrency: this.setCurrentCurrency.bind(this),
+ setUseBlockie: this.setUseBlockie.bind(this),
+ markAccountsFound: this.markAccountsFound.bind(this),
+ markPasswordForgotten: this.markPasswordForgotten.bind(this),
+ unMarkPasswordForgotten: this.unMarkPasswordForgotten.bind(this),
+
// coinbase
buyEth: this.buyEth.bind(this),
// shapeshift
createShapeShiftTx: this.createShapeShiftTx.bind(this),
// primary HD keyring management
- addNewAccount: this.addNewAccount.bind(this),
- placeSeedWords: this.placeSeedWords.bind(this),
- clearSeedWordCache: this.clearSeedWordCache.bind(this),
- importAccountWithStrategy: this.importAccountWithStrategy.bind(this),
+ addNewAccount: nodeify(this.addNewAccount, this),
+ placeSeedWords: this.placeSeedWords.bind(this),
+ clearSeedWordCache: this.clearSeedWordCache.bind(this),
+ resetAccount: this.resetAccount.bind(this),
+ importAccountWithStrategy: this.importAccountWithStrategy.bind(this),
// vault management
- submitPassword: this.submitPassword.bind(this),
+ submitPassword: nodeify(keyringController.submitPassword, keyringController),
+
+ // network management
+ setNetworkEndpoints: nodeify(networkController.setNetworkEndpoints, networkController),
+ setProviderType: nodeify(networkController.setProviderType, networkController),
+ setCustomRpc: nodeify(this.setCustomRpc, this),
// PreferencesController
- setSelectedAddress: nodeify(preferencesController.setSelectedAddress).bind(preferencesController),
- setDefaultRpc: nodeify(this.setDefaultRpc).bind(this),
- setCustomRpc: nodeify(this.setCustomRpc).bind(this),
+ setSelectedAddress: nodeify(preferencesController.setSelectedAddress, preferencesController),
+ addToken: nodeify(preferencesController.addToken, preferencesController),
+ removeToken: nodeify(preferencesController.removeToken, preferencesController),
+ setCurrentAccountTab: nodeify(preferencesController.setCurrentAccountTab, preferencesController),
+ setFeatureFlag: nodeify(preferencesController.setFeatureFlag, preferencesController),
// AddressController
- setAddressBook: nodeify(addressBookController.setAddressBook).bind(addressBookController),
+ setAddressBook: nodeify(addressBookController.setAddressBook, addressBookController),
// KeyringController
- setLocked: nodeify(keyringController.setLocked).bind(keyringController),
- createNewVaultAndKeychain: nodeify(keyringController.createNewVaultAndKeychain).bind(keyringController),
- createNewVaultAndRestore: nodeify(keyringController.createNewVaultAndRestore).bind(keyringController),
- addNewKeyring: nodeify(keyringController.addNewKeyring).bind(keyringController),
- saveAccountLabel: nodeify(keyringController.saveAccountLabel).bind(keyringController),
- exportAccount: nodeify(keyringController.exportAccount).bind(keyringController),
-
- // txManager
- approveTransaction: txManager.approveTransaction.bind(txManager),
- cancelTransaction: txManager.cancelTransaction.bind(txManager),
- updateAndApproveTransaction: this.updateAndApproveTx.bind(this),
+ setLocked: nodeify(keyringController.setLocked, keyringController),
+ createNewVaultAndKeychain: nodeify(this.createNewVaultAndKeychain, this),
+ createNewVaultAndRestore: nodeify(this.createNewVaultAndRestore, this),
+ addNewKeyring: nodeify(keyringController.addNewKeyring, keyringController),
+ saveAccountLabel: nodeify(keyringController.saveAccountLabel, keyringController),
+ exportAccount: nodeify(keyringController.exportAccount, keyringController),
+
+ // txController
+ cancelTransaction: nodeify(txController.cancelTransaction, txController),
+ updateTransaction: nodeify(txController.updateTransaction, txController),
+ updateAndApproveTransaction: nodeify(txController.updateAndApproveTransaction, txController),
+ retryTransaction: nodeify(this.retryTransaction, this),
// messageManager
- signMessage: nodeify(this.signMessage).bind(this),
- cancelMessage: this.cancelMessage.bind(this),
+ signMessage: nodeify(this.signMessage, this),
+ cancelMessage: this.cancelMessage.bind(this),
// personalMessageManager
- signPersonalMessage: nodeify(this.signPersonalMessage).bind(this),
- cancelPersonalMessage: this.cancelPersonalMessage.bind(this),
+ signPersonalMessage: nodeify(this.signPersonalMessage, this),
+ cancelPersonalMessage: this.cancelPersonalMessage.bind(this),
+
+ // personalMessageManager
+ signTypedMessage: nodeify(this.signTypedMessage, this),
+ cancelTypedMessage: this.cancelTypedMessage.bind(this),
// notices
- checkNotices: noticeController.updateNoticesList.bind(noticeController),
+ checkNotices: noticeController.updateNoticesList.bind(noticeController),
markNoticeRead: noticeController.markNoticeRead.bind(noticeController),
}
}
setupUntrustedCommunication (connectionStream, originDomain) {
+ // Check if new connection is blacklisted
+ if (this.blacklistController.checkForPhishing(originDomain)) {
+ log.debug('MetaMask - sending phishing warning for', originDomain)
+ this.sendPhishingWarning(connectionStream, originDomain)
+ return
+ }
+
// setup multiplexing
- var mx = setupMultiplex(connectionStream)
+ const mux = setupMultiplex(connectionStream)
// connect features
- this.setupProviderConnection(mx.createStream('provider'), originDomain)
- this.setupPublicConfig(mx.createStream('publicConfig'))
+ this.setupProviderConnection(mux.createStream('provider'), originDomain)
+ this.setupPublicConfig(mux.createStream('publicConfig'))
}
setupTrustedCommunication (connectionStream, originDomain) {
// setup multiplexing
- var mx = setupMultiplex(connectionStream)
+ const mux = setupMultiplex(connectionStream)
// connect features
- this.setupControllerConnection(mx.createStream('controller'))
- this.setupProviderConnection(mx.createStream('provider'), originDomain)
+ this.setupControllerConnection(mux.createStream('controller'))
+ this.setupProviderConnection(mux.createStream('provider'), originDomain)
+ }
+
+ sendPhishingWarning (connectionStream, hostname) {
+ const mux = setupMultiplex(connectionStream)
+ const phishingStream = mux.createStream('phishing')
+ phishingStream.write({ hostname })
}
setupControllerConnection (outStream) {
const api = this.getApi()
const dnode = Dnode(api)
- outStream.pipe(dnode).pipe(outStream)
+ pump(
+ outStream,
+ dnode,
+ outStream,
+ (err) => {
+ if (err) log.error(err)
+ }
+ )
dnode.on('remote', (remote) => {
// push updates to popup
const sendUpdate = remote.sendUpdate.bind(remote)
@@ -334,49 +445,141 @@ module.exports = class MetamaskController extends EventEmitter {
})
}
- setupProviderConnection (outStream, originDomain) {
- streamIntoProvider(outStream, this.provider, logger)
- function logger (err, request, response) {
- if (err) return console.error(err)
- if (response.error) {
- console.error('Error in RPC response:\n', response.error)
- }
- if (request.isMetamaskInternal) return
- if (global.METAMASK_DEBUG) {
- console.log(`RPC (${originDomain}):`, request, '->', response)
+ setupProviderConnection (outStream, origin) {
+ // setup json rpc engine stack
+ const engine = new RpcEngine()
+
+ // create filter polyfill middleware
+ const filterMiddleware = createFilterMiddleware({
+ provider: this.provider,
+ blockTracker: this.provider._blockTracker,
+ })
+
+ engine.push(createOriginMiddleware({ origin }))
+ engine.push(createLoggerMiddleware({ origin }))
+ engine.push(filterMiddleware)
+ engine.push(createProviderMiddleware({ provider: this.provider }))
+
+ // setup connection
+ const providerStream = createEngineStream({ engine })
+ pump(
+ outStream,
+ providerStream,
+ outStream,
+ (err) => {
+ // cleanup filter polyfill middleware
+ filterMiddleware.destroy()
+ if (err) log.error(err)
}
- }
+ )
}
setupPublicConfig (outStream) {
- pipe(
- this.publicConfigStore,
- outStream
+ pump(
+ asStream(this.publicConfigStore),
+ outStream,
+ (err) => {
+ if (err) log.error(err)
+ }
)
}
- sendUpdate () {
+ privateSendUpdate () {
this.emit('update', this.getState())
}
+ getGasPrice () {
+ const { recentBlocksController } = this
+ const { recentBlocks } = recentBlocksController.store.getState()
+
+ // Return 1 gwei if no blocks have been observed:
+ if (recentBlocks.length === 0) {
+ return '0x' + GWEI_BN.toString(16)
+ }
+
+ const lowestPrices = recentBlocks.map((block) => {
+ if (!block.gasPrices || block.gasPrices.length < 1) {
+ return GWEI_BN
+ }
+ return block.gasPrices
+ .map(hexPrefix => hexPrefix.substr(2))
+ .map(hex => new BN(hex, 16))
+ .sort((a, b) => {
+ return a.gt(b) ? 1 : -1
+ })[0]
+ })
+ .map(number => number.div(GWEI_BN).toNumber())
+
+ const percentileNum = percentile(50, lowestPrices)
+ const percentileNumBn = new BN(percentileNum)
+ return '0x' + percentileNumBn.mul(GWEI_BN).toString(16)
+ }
+
//
// Vault Management
//
- submitPassword (password, cb) {
- return this.keyringController.submitPassword(password)
- .then((newState) => { cb(null, newState) })
- .catch((reason) => { cb(reason) })
+ async createNewVaultAndKeychain (password) {
+ const release = await this.createVaultMutex.acquire()
+ let vault
+
+ try {
+ const accounts = await this.keyringController.getAccounts()
+
+ if (accounts.length > 0) {
+ vault = await this.keyringController.fullUpdate()
+
+ } else {
+ vault = await this.keyringController.createNewVaultAndKeychain(password)
+ this.selectFirstIdentity(vault)
+ }
+ release()
+ } catch (err) {
+ release()
+ throw err
+ }
+
+ return vault
+ }
+
+ async createNewVaultAndRestore (password, seed) {
+ const release = await this.createVaultMutex.acquire()
+ try {
+ const vault = await this.keyringController.createNewVaultAndRestore(password, seed)
+ this.selectFirstIdentity(vault)
+ release()
+ return vault
+ } catch (err) {
+ release()
+ throw err
+ }
+ }
+
+ selectFirstIdentity (vault) {
+ const { identities } = vault
+ const address = Object.keys(identities)[0]
+ this.preferencesController.setSelectedAddress(address)
}
//
// Opinionated Keyring Management
//
- addNewAccount (cb) {
+ async addNewAccount (cb) {
const primaryKeyring = this.keyringController.getKeyringsByType('HD Key Tree')[0]
if (!primaryKeyring) return cb(new Error('MetamaskController - No HD Key Tree found'))
- promiseToCallback(this.keyringController.addNewAccount(primaryKeyring))(cb)
+ const keyringController = this.keyringController
+ const oldAccounts = await keyringController.getAccounts()
+ const keyState = await keyringController.addNewAccount(primaryKeyring)
+ const newAccounts = await keyringController.getAccounts()
+
+ newAccounts.forEach((address) => {
+ if (!oldAccounts.includes(address)) {
+ this.preferencesController.setSelectedAddress(address)
+ }
+ })
+
+ return keyState
}
// Adds the current vault's seed words to the UI's state tree.
@@ -403,6 +606,13 @@ module.exports = class MetamaskController extends EventEmitter {
cb(null, this.preferencesController.getSelectedAddress())
}
+ resetAccount (cb) {
+ const selectedAddress = this.preferencesController.getSelectedAddress()
+ this.txController.wipeTransactions(selectedAddress)
+ cb(null, selectedAddress)
+ }
+
+
importAccountWithStrategy (strategy, args, cb) {
accountImporter.importAccount(strategy, args)
.then((privateKey) => {
@@ -418,30 +628,17 @@ module.exports = class MetamaskController extends EventEmitter {
//
// Identity Management
//
+ //
- newUnapprovedTransaction (txParams, cb) {
- log.debug(`MetaMaskController newUnapprovedTransaction ${JSON.stringify(txParams)}`)
- const self = this
- self.txManager.addUnapprovedTransaction(txParams, (err, txMeta) => {
- if (err) return cb(err)
- self.sendUpdate()
- self.opts.showUnapprovedTx(txMeta)
- // listen for tx completion (success, fail)
- self.txManager.once(`${txMeta.id}:finished`, (completedTx) => {
- switch (completedTx.status) {
- case 'submitted':
- return cb(null, completedTx.hash)
- case 'rejected':
- return cb(new Error('MetaMask Tx Signature: User denied transaction signature.'))
- default:
- return cb(new Error(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(completedTx.txParams)}`))
- }
- })
- })
+ async retryTransaction (txId, cb) {
+ await this.txController.retryTransaction(txId)
+ const state = await this.getState()
+ return state
}
+
newUnsignedMessage (msgParams, cb) {
- let msgId = this.messageManager.addUnapprovedMessage(msgParams)
+ const msgId = this.messageManager.addUnapprovedMessage(msgParams)
this.sendUpdate()
this.opts.showUnconfirmedMessage()
this.messageManager.once(`${msgId}:finished`, (data) => {
@@ -461,7 +658,7 @@ module.exports = class MetamaskController extends EventEmitter {
return cb(new Error('MetaMask Message Signature: from field is required.'))
}
- let msgId = this.personalMessageManager.addUnapprovedMessage(msgParams)
+ const msgId = this.personalMessageManager.addUnapprovedMessage(msgParams)
this.sendUpdate()
this.opts.showUnconfirmedMessage()
this.personalMessageManager.once(`${msgId}:finished`, (data) => {
@@ -476,11 +673,26 @@ module.exports = class MetamaskController extends EventEmitter {
})
}
- updateAndApproveTx(txMeta, cb) {
- log.debug(`MetaMaskController - updateAndApproveTx: ${JSON.stringify(txMeta)}`)
- const txManager = this.txManager
- txManager.updateTx(txMeta)
- txManager.approveTransaction(txMeta.id, cb)
+ newUnsignedTypedMessage (msgParams, cb) {
+ let msgId
+ try {
+ msgId = this.typedMessageManager.addUnapprovedMessage(msgParams)
+ this.sendUpdate()
+ this.opts.showUnconfirmedMessage()
+ } catch (e) {
+ return cb(e)
+ }
+
+ this.typedMessageManager.once(`${msgId}:finished`, (data) => {
+ switch (data.status) {
+ case 'signed':
+ return cb(null, data.rawSig)
+ case 'rejected':
+ return cb(new Error('MetaMask Message Signature: User denied message signature.'))
+ default:
+ return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`))
+ }
+ })
}
signMessage (msgParams, cb) {
@@ -502,7 +714,7 @@ module.exports = class MetamaskController extends EventEmitter {
})
}
- cancelMessage(msgId, cb) {
+ cancelMessage (msgId, cb) {
const messageManager = this.messageManager
messageManager.rejectMsg(msgId)
if (cb && typeof cb === 'function') {
@@ -512,7 +724,7 @@ module.exports = class MetamaskController extends EventEmitter {
// Prefixed Style Message Signing Methods:
approvePersonalMessage (msgParams, cb) {
- let msgId = this.personalMessageManager.addUnapprovedMessage(msgParams)
+ const msgId = this.personalMessageManager.addUnapprovedMessage(msgParams)
this.sendUpdate()
this.opts.showUnconfirmedMessage()
this.personalMessageManager.once(`${msgId}:finished`, (data) => {
@@ -545,7 +757,25 @@ module.exports = class MetamaskController extends EventEmitter {
})
}
- cancelPersonalMessage(msgId, cb) {
+ signTypedMessage (msgParams) {
+ log.info('MetaMaskController - signTypedMessage')
+ const msgId = msgParams.metamaskId
+ // sets the status op the message to 'approved'
+ // and removes the metamaskId for signing
+ return this.typedMessageManager.approveMessage(msgParams)
+ .then((cleanMsgParams) => {
+ // signs the message
+ return this.keyringController.signTypedMessage(cleanMsgParams)
+ })
+ .then((rawSig) => {
+ // tells the listener that the message has been signed
+ // and can be returned to the dapp
+ this.typedMessageManager.setMsgStatusSigned(msgId, rawSig)
+ return this.getState()
+ })
+ }
+
+ cancelPersonalMessage (msgId, cb) {
const messageManager = this.personalMessageManager
messageManager.rejectMsg(msgId)
if (cb && typeof cb === 'function') {
@@ -553,19 +783,39 @@ module.exports = class MetamaskController extends EventEmitter {
}
}
+ cancelTypedMessage (msgId, cb) {
+ const messageManager = this.typedMessageManager
+ messageManager.rejectMsg(msgId)
+ if (cb && typeof cb === 'function') {
+ cb(null, this.getState())
+ }
+ }
+
markAccountsFound (cb) {
this.configManager.setLostAccounts([])
this.sendUpdate()
cb(null, this.getState())
}
- restoreOldVaultAccounts(migratorOutput) {
+ markPasswordForgotten(cb) {
+ this.configManager.setPasswordForgotten(true)
+ this.sendUpdate()
+ cb()
+ }
+
+ unMarkPasswordForgotten(cb) {
+ this.configManager.setPasswordForgotten(false)
+ this.sendUpdate()
+ cb()
+ }
+
+ restoreOldVaultAccounts (migratorOutput) {
const { serialized } = migratorOutput
return this.keyringController.restoreKeyring(serialized)
.then(() => migratorOutput)
}
- restoreOldLostAccounts(migratorOutput) {
+ restoreOldLostAccounts (migratorOutput) {
const { lostAccounts } = migratorOutput
if (lostAccounts) {
this.configManager.setLostAccounts(lostAccounts.map(acct => acct.address))
@@ -591,12 +841,6 @@ module.exports = class MetamaskController extends EventEmitter {
//
// Log blocks
- logBlock (block) {
- if (global.METAMASK_DEBUG) {
- console.log(`BLOCK CHANGED: #${block.number.toString('hex')} 0x${block.hash.toString('hex')}`)
- }
- this.verifyNetwork()
- }
setCurrentCurrency (currencyCode, cb) {
try {
@@ -615,7 +859,7 @@ module.exports = class MetamaskController extends EventEmitter {
buyEth (address, amount) {
if (!amount) amount = '5'
- const network = this.getNetworkState()
+ const network = this.networkController.getNetworkState()
const url = getBuyEthUrl({ network, address, amount })
if (url) this.platform.openWindow({ url })
}
@@ -624,70 +868,30 @@ module.exports = class MetamaskController extends EventEmitter {
this.shapeshiftController.createShapeShiftTx(depositAddress, depositType)
}
- //
// network
- //
- verifyNetwork () {
- // Check network when restoring connectivity:
- if (this.isNetworkLoading()) this.lookupNetwork()
- }
-
- setDefaultRpc () {
- this.configManager.setRpcTarget('http://localhost:8545')
- this.platform.reload()
- this.lookupNetwork()
- return Promise.resolve('http://localhost:8545')
- }
-
- setCustomRpc (rpcTarget, rpcList) {
- this.configManager.setRpcTarget(rpcTarget)
- return this.preferencesController.updateFrequentRpcList(rpcTarget)
- .then(() => {
- this.platform.reload()
- this.lookupNetwork()
- return Promise.resolve(rpcTarget)
- })
+ async setCustomRpc (rpcTarget, rpcList) {
+ this.networkController.setRpcTarget(rpcTarget)
+ await this.preferencesController.updateFrequentRpcList(rpcTarget)
+ return rpcTarget
}
- setProviderType (type) {
- this.configManager.setProviderType(type)
- this.platform.reload()
- this.lookupNetwork()
- }
-
- useEtherscanProvider () {
- this.configManager.useEtherscanProvider()
- this.platform.reload()
- }
-
- getNetworkState () {
- return this.networkStore.getState().network
- }
-
- setNetworkState (network) {
- return this.networkStore.updateState({ network })
- }
-
- isNetworkLoading () {
- return this.getNetworkState() === 'loading'
- }
-
- lookupNetwork (err) {
- if (err) {
- this.setNetworkState('loading')
+ setUseBlockie (val, cb) {
+ try {
+ this.preferencesController.setUseBlockie(val)
+ cb(null)
+ } catch (err) {
+ cb(err)
}
+ }
- this.ethQuery.sendAsync({ method: 'net_version' }, (err, network) => {
- if (err) {
- this.setNetworkState('loading')
- return
- }
- if (global.METAMASK_DEBUG) {
- console.log('web3.getNetwork returned ' + network)
+ recordFirstTimeInfo (initState) {
+ if (!('firstTimeInfo' in initState)) {
+ initState.firstTimeInfo = {
+ version,
+ date: Date.now(),
}
- this.setNetworkState(network)
- })
+ }
}
}
diff --git a/app/scripts/migrations/002.js b/app/scripts/migrations/002.js
index 36a870342..b1d88f2ef 100644
--- a/app/scripts/migrations/002.js
+++ b/app/scripts/migrations/002.js
@@ -7,7 +7,7 @@ module.exports = {
version,
migrate: function (originalVersionedData) {
- let versionedData = clone(originalVersionedData)
+ const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
try {
if (versionedData.data.config.provider.type === 'etherscan') {
diff --git a/app/scripts/migrations/003.js b/app/scripts/migrations/003.js
index 1893576ad..140f81d40 100644
--- a/app/scripts/migrations/003.js
+++ b/app/scripts/migrations/003.js
@@ -8,7 +8,7 @@ module.exports = {
version,
migrate: function (originalVersionedData) {
- let versionedData = clone(originalVersionedData)
+ const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
try {
if (versionedData.data.config.provider.rpcTarget === oldTestRpc) {
diff --git a/app/scripts/migrations/004.js b/app/scripts/migrations/004.js
index 405d932f8..cd558300c 100644
--- a/app/scripts/migrations/004.js
+++ b/app/scripts/migrations/004.js
@@ -6,7 +6,7 @@ module.exports = {
version,
migrate: function (versionedData) {
- let safeVersionedData = clone(versionedData)
+ const safeVersionedData = clone(versionedData)
safeVersionedData.meta.version = version
try {
if (safeVersionedData.data.config.provider.type !== 'rpc') return Promise.resolve(safeVersionedData)
diff --git a/app/scripts/migrations/005.js b/app/scripts/migrations/005.js
index e4b84f460..f7b68dfe4 100644
--- a/app/scripts/migrations/005.js
+++ b/app/scripts/migrations/005.js
@@ -14,7 +14,7 @@ module.exports = {
version,
migrate: function (originalVersionedData) {
- let versionedData = clone(originalVersionedData)
+ const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
try {
const state = versionedData.data
diff --git a/app/scripts/migrations/006.js b/app/scripts/migrations/006.js
index 94d1b6ecd..51ea6e3e7 100644
--- a/app/scripts/migrations/006.js
+++ b/app/scripts/migrations/006.js
@@ -13,7 +13,7 @@ module.exports = {
version,
migrate: function (originalVersionedData) {
- let versionedData = clone(originalVersionedData)
+ const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
try {
const state = versionedData.data
diff --git a/app/scripts/migrations/007.js b/app/scripts/migrations/007.js
index 236e35224..d9887b9c8 100644
--- a/app/scripts/migrations/007.js
+++ b/app/scripts/migrations/007.js
@@ -13,7 +13,7 @@ module.exports = {
version,
migrate: function (originalVersionedData) {
- let versionedData = clone(originalVersionedData)
+ const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
try {
const state = versionedData.data
diff --git a/app/scripts/migrations/008.js b/app/scripts/migrations/008.js
index cd5e95d22..da7cb2e60 100644
--- a/app/scripts/migrations/008.js
+++ b/app/scripts/migrations/008.js
@@ -13,7 +13,7 @@ module.exports = {
version,
migrate: function (originalVersionedData) {
- let versionedData = clone(originalVersionedData)
+ const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
try {
const state = versionedData.data
diff --git a/app/scripts/migrations/009.js b/app/scripts/migrations/009.js
index 4612fefdc..f47db55ac 100644
--- a/app/scripts/migrations/009.js
+++ b/app/scripts/migrations/009.js
@@ -13,7 +13,7 @@ module.exports = {
version,
migrate: function (originalVersionedData) {
- let versionedData = clone(originalVersionedData)
+ const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
try {
const state = versionedData.data
diff --git a/app/scripts/migrations/010.js b/app/scripts/migrations/010.js
index c0cc56ae4..e4b9ac07e 100644
--- a/app/scripts/migrations/010.js
+++ b/app/scripts/migrations/010.js
@@ -13,7 +13,7 @@ module.exports = {
version,
migrate: function (originalVersionedData) {
- let versionedData = clone(originalVersionedData)
+ const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
try {
const state = versionedData.data
diff --git a/app/scripts/migrations/011.js b/app/scripts/migrations/011.js
index 0d5d6d307..782ec809d 100644
--- a/app/scripts/migrations/011.js
+++ b/app/scripts/migrations/011.js
@@ -12,7 +12,7 @@ module.exports = {
version,
migrate: function (originalVersionedData) {
- let versionedData = clone(originalVersionedData)
+ const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
try {
const state = versionedData.data
diff --git a/app/scripts/migrations/012.js b/app/scripts/migrations/012.js
index 8361b3793..f69ccbb02 100644
--- a/app/scripts/migrations/012.js
+++ b/app/scripts/migrations/012.js
@@ -12,7 +12,7 @@ module.exports = {
version,
migrate: function (originalVersionedData) {
- let versionedData = clone(originalVersionedData)
+ const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
try {
const state = versionedData.data
diff --git a/app/scripts/migrations/013.js b/app/scripts/migrations/013.js
new file mode 100644
index 000000000..8f11e510e
--- /dev/null
+++ b/app/scripts/migrations/013.js
@@ -0,0 +1,34 @@
+const version = 13
+
+/*
+
+This migration modifies the network config from ambiguous 'testnet' to explicit 'ropsten'
+
+*/
+
+const clone = require('clone')
+
+module.exports = {
+ version,
+
+ migrate: function (originalVersionedData) {
+ const versionedData = clone(originalVersionedData)
+ versionedData.meta.version = version
+ try {
+ const state = versionedData.data
+ const newState = transformState(state)
+ versionedData.data = newState
+ } catch (err) {
+ console.warn(`MetaMask Migration #${version}` + err.stack)
+ }
+ return Promise.resolve(versionedData)
+ },
+}
+
+function transformState (state) {
+ const newState = state
+ if (newState.config.provider.type === 'testnet') {
+ newState.config.provider.type = 'ropsten'
+ }
+ return newState
+}
diff --git a/app/scripts/migrations/014.js b/app/scripts/migrations/014.js
new file mode 100644
index 000000000..0fe92125b
--- /dev/null
+++ b/app/scripts/migrations/014.js
@@ -0,0 +1,34 @@
+const version = 14
+
+/*
+
+This migration removes provider from config and moves it too NetworkController.
+
+*/
+
+const clone = require('clone')
+
+module.exports = {
+ version,
+
+ migrate: function (originalVersionedData) {
+ const versionedData = clone(originalVersionedData)
+ versionedData.meta.version = version
+ try {
+ const state = versionedData.data
+ const newState = transformState(state)
+ versionedData.data = newState
+ } catch (err) {
+ console.warn(`MetaMask Migration #${version}` + err.stack)
+ }
+ return Promise.resolve(versionedData)
+ },
+}
+
+function transformState (state) {
+ const newState = state
+ newState.NetworkController = {}
+ newState.NetworkController.provider = newState.config.provider
+ delete newState.config.provider
+ return newState
+}
diff --git a/app/scripts/migrations/015.js b/app/scripts/migrations/015.js
new file mode 100644
index 000000000..4b839580b
--- /dev/null
+++ b/app/scripts/migrations/015.js
@@ -0,0 +1,38 @@
+const version = 15
+
+/*
+
+This migration sets transactions with the 'Gave up submitting tx.' err message
+to a 'failed' stated
+
+*/
+
+const clone = require('clone')
+
+module.exports = {
+ version,
+
+ migrate: function (originalVersionedData) {
+ const versionedData = clone(originalVersionedData)
+ versionedData.meta.version = version
+ try {
+ const state = versionedData.data
+ const newState = transformState(state)
+ versionedData.data = newState
+ } catch (err) {
+ console.warn(`MetaMask Migration #${version}` + err.stack)
+ }
+ return Promise.resolve(versionedData)
+ },
+}
+
+function transformState (state) {
+ const newState = state
+ const transactions = newState.TransactionController.transactions
+ newState.TransactionController.transactions = transactions.map((txMeta) => {
+ if (!txMeta.err) return txMeta
+ else if (txMeta.err.message === 'Gave up submitting tx.') txMeta.status = 'failed'
+ return txMeta
+ })
+ return newState
+}
diff --git a/app/scripts/migrations/016.js b/app/scripts/migrations/016.js
new file mode 100644
index 000000000..4fc534f1c
--- /dev/null
+++ b/app/scripts/migrations/016.js
@@ -0,0 +1,41 @@
+const version = 16
+
+/*
+
+This migration sets transactions with the 'Gave up submitting tx.' err message
+to a 'failed' stated
+
+*/
+
+const clone = require('clone')
+
+module.exports = {
+ version,
+
+ migrate: function (originalVersionedData) {
+ const versionedData = clone(originalVersionedData)
+ versionedData.meta.version = version
+ try {
+ const state = versionedData.data
+ const newState = transformState(state)
+ versionedData.data = newState
+ } catch (err) {
+ console.warn(`MetaMask Migration #${version}` + err.stack)
+ }
+ return Promise.resolve(versionedData)
+ },
+}
+
+function transformState (state) {
+ const newState = state
+ const transactions = newState.TransactionController.transactions
+ newState.TransactionController.transactions = transactions.map((txMeta) => {
+ if (!txMeta.err) return txMeta
+ if (txMeta.err === 'transaction with the same hash was already imported.') {
+ txMeta.status = 'submitted'
+ delete txMeta.err
+ }
+ return txMeta
+ })
+ return newState
+}
diff --git a/app/scripts/migrations/017.js b/app/scripts/migrations/017.js
new file mode 100644
index 000000000..24959cd3a
--- /dev/null
+++ b/app/scripts/migrations/017.js
@@ -0,0 +1,40 @@
+const version = 17
+
+/*
+
+This migration sets transactions who were retried and marked as failed to submitted
+
+*/
+
+const clone = require('clone')
+
+module.exports = {
+ version,
+
+ migrate: function (originalVersionedData) {
+ const versionedData = clone(originalVersionedData)
+ versionedData.meta.version = version
+ try {
+ const state = versionedData.data
+ const newState = transformState(state)
+ versionedData.data = newState
+ } catch (err) {
+ console.warn(`MetaMask Migration #${version}` + err.stack)
+ }
+ return Promise.resolve(versionedData)
+ },
+}
+
+function transformState (state) {
+ const newState = state
+ const transactions = newState.TransactionController.transactions
+ newState.TransactionController.transactions = transactions.map((txMeta) => {
+ if (!txMeta.status === 'failed') return txMeta
+ if (txMeta.retryCount > 0 && txMeta.retryCount < 2) {
+ txMeta.status = 'submitted'
+ delete txMeta.err
+ }
+ return txMeta
+ })
+ return newState
+}
diff --git a/app/scripts/migrations/018.js b/app/scripts/migrations/018.js
new file mode 100644
index 000000000..d27fe3f46
--- /dev/null
+++ b/app/scripts/migrations/018.js
@@ -0,0 +1,52 @@
+const version = 18
+
+/*
+
+This migration updates "transaction state history" to diffs style
+
+*/
+
+const clone = require('clone')
+const txStateHistoryHelper = require('../lib/tx-state-history-helper')
+
+
+module.exports = {
+ version,
+
+ migrate: function (originalVersionedData) {
+ const versionedData = clone(originalVersionedData)
+ versionedData.meta.version = version
+ try {
+ const state = versionedData.data
+ const newState = transformState(state)
+ versionedData.data = newState
+ } catch (err) {
+ console.warn(`MetaMask Migration #${version}` + err.stack)
+ }
+ return Promise.resolve(versionedData)
+ },
+}
+
+function transformState (state) {
+ const newState = state
+ const transactions = newState.TransactionController.transactions
+ newState.TransactionController.transactions = transactions.map((txMeta) => {
+ // no history: initialize
+ if (!txMeta.history || txMeta.history.length === 0) {
+ const snapshot = txStateHistoryHelper.snapshotFromTxMeta(txMeta)
+ txMeta.history = [snapshot]
+ return txMeta
+ }
+ // has history: migrate
+ const newHistory = (
+ txStateHistoryHelper.migrateFromSnapshotsToDiffs(txMeta.history)
+ // remove empty diffs
+ .filter((entry) => {
+ return !Array.isArray(entry) || entry.length > 0
+ })
+ )
+ txMeta.history = newHistory
+ return txMeta
+ })
+ return newState
+}
diff --git a/app/scripts/migrations/019.js b/app/scripts/migrations/019.js
new file mode 100644
index 000000000..072c96370
--- /dev/null
+++ b/app/scripts/migrations/019.js
@@ -0,0 +1,83 @@
+
+const version = 19
+
+/*
+
+This migration sets transactions as failed
+whos nonce is too high
+
+*/
+
+const clone = require('clone')
+
+module.exports = {
+ version,
+
+ migrate: function (originalVersionedData) {
+ const versionedData = clone(originalVersionedData)
+ versionedData.meta.version = version
+ try {
+ const state = versionedData.data
+ const newState = transformState(state)
+ versionedData.data = newState
+ } catch (err) {
+ console.warn(`MetaMask Migration #${version}` + err.stack)
+ }
+ return Promise.resolve(versionedData)
+ },
+}
+
+function transformState (state) {
+ const newState = state
+ const transactions = newState.TransactionController.transactions
+
+ newState.TransactionController.transactions = transactions.map((txMeta, _, txList) => {
+ if (txMeta.status !== 'submitted') return txMeta
+
+ const confirmedTxs = txList.filter((tx) => tx.status === 'confirmed')
+ .filter((tx) => tx.txParams.from === txMeta.txParams.from)
+ .filter((tx) => tx.metamaskNetworkId.from === txMeta.metamaskNetworkId.from)
+ const highestConfirmedNonce = getHighestNonce(confirmedTxs)
+
+ const pendingTxs = txList.filter((tx) => tx.status === 'submitted')
+ .filter((tx) => tx.txParams.from === txMeta.txParams.from)
+ .filter((tx) => tx.metamaskNetworkId.from === txMeta.metamaskNetworkId.from)
+ const highestContinuousNonce = getHighestContinuousFrom(pendingTxs, highestConfirmedNonce)
+
+ const maxNonce = Math.max(highestContinuousNonce, highestConfirmedNonce)
+
+ if (parseInt(txMeta.txParams.nonce, 16) > maxNonce + 1) {
+ txMeta.status = 'failed'
+ txMeta.err = {
+ message: 'nonce too high',
+ note: 'migration 019 custom error',
+ }
+ }
+ return txMeta
+ })
+ return newState
+}
+
+function getHighestContinuousFrom (txList, startPoint) {
+ const nonces = txList.map((txMeta) => {
+ const nonce = txMeta.txParams.nonce
+ return parseInt(nonce, 16)
+ })
+
+ let highest = startPoint
+ while (nonces.includes(highest)) {
+ highest++
+ }
+
+ return highest
+}
+
+function getHighestNonce (txList) {
+ const nonces = txList.map((txMeta) => {
+ const nonce = txMeta.txParams.nonce
+ return parseInt(nonce || '0x0', 16)
+ })
+ const highestNonce = Math.max.apply(null, nonces)
+ return highestNonce
+}
+
diff --git a/app/scripts/migrations/020.js b/app/scripts/migrations/020.js
new file mode 100644
index 000000000..8159b3e70
--- /dev/null
+++ b/app/scripts/migrations/020.js
@@ -0,0 +1,41 @@
+const version = 20
+
+/*
+
+This migration ensures previous installations
+get a `firstTimeInfo` key on the metamask state,
+so that we can version notices in the future.
+
+*/
+
+const clone = require('clone')
+
+module.exports = {
+ version,
+
+ migrate: function (originalVersionedData) {
+ const versionedData = clone(originalVersionedData)
+ versionedData.meta.version = version
+ try {
+ const state = versionedData.data
+ const newState = transformState(state)
+ versionedData.data = newState
+ } catch (err) {
+ console.warn(`MetaMask Migration #${version}` + err.stack)
+ }
+ return Promise.resolve(versionedData)
+ },
+}
+
+function transformState (state) {
+ const newState = state
+ if ('metamask' in newState &&
+ !('firstTimeInfo' in newState.metamask)) {
+ newState.metamask.firstTimeInfo = {
+ version: '3.12.0',
+ date: Date.now(),
+ }
+ }
+ return newState
+}
+
diff --git a/app/scripts/migrations/021.js b/app/scripts/migrations/021.js
new file mode 100644
index 000000000..d84e77b50
--- /dev/null
+++ b/app/scripts/migrations/021.js
@@ -0,0 +1,34 @@
+const version = 21
+
+/*
+
+This migration removes the BlackListController from disk state
+
+*/
+
+const clone = require('clone')
+
+module.exports = {
+ version,
+
+ migrate: function (originalVersionedData) {
+ const versionedData = clone(originalVersionedData)
+ versionedData.meta.version = version
+ try {
+ const state = versionedData.data
+ const newState = transformState(state)
+ versionedData.data = newState
+ } catch (err) {
+ console.warn(`MetaMask Migration #${version}` + err.stack)
+ }
+ return Promise.resolve(versionedData)
+ },
+}
+
+function transformState (state) {
+ const newState = state
+ delete newState.BlacklistController
+ delete newState.RecentBlocks
+ return newState
+}
+
diff --git a/app/scripts/migrations/_multi-keyring.js b/app/scripts/migrations/_multi-keyring.js
index 04c966d4d..7a4578ea7 100644
--- a/app/scripts/migrations/_multi-keyring.js
+++ b/app/scripts/migrations/_multi-keyring.js
@@ -10,20 +10,20 @@ which we dont have access to at the time of this writing.
const ObservableStore = require('obs-store')
const ConfigManager = require('../../app/scripts/lib/config-manager')
const IdentityStoreMigrator = require('../../app/scripts/lib/idStore-migrator')
-const KeyringController = require('../../app/scripts/lib/keyring-controller')
+const KeyringController = require('eth-keyring-controller')
const password = 'obviously not correct'
module.exports = {
- version,
+ version,
migrate: function (versionedData) {
versionedData.meta.version = version
- let store = new ObservableStore(versionedData.data)
- let configManager = new ConfigManager({ store })
- let idStoreMigrator = new IdentityStoreMigrator({ configManager })
- let keyringController = new KeyringController({
+ const store = new ObservableStore(versionedData.data)
+ const configManager = new ConfigManager({ store })
+ const idStoreMigrator = new IdentityStoreMigrator({ configManager })
+ const keyringController = new KeyringController({
configManager: configManager,
})
@@ -46,6 +46,5 @@ module.exports = {
return Promise.resolve(versionedData)
})
})
-
},
}
diff --git a/app/scripts/migrations/index.js b/app/scripts/migrations/index.js
index 019b4d13d..a0cf5f4d4 100644
--- a/app/scripts/migrations/index.js
+++ b/app/scripts/migrations/index.js
@@ -23,4 +23,13 @@ module.exports = [
require('./010'),
require('./011'),
require('./012'),
+ require('./013'),
+ require('./014'),
+ require('./015'),
+ require('./016'),
+ require('./017'),
+ require('./018'),
+ require('./019'),
+ require('./020'),
+ require('./021'),
]
diff --git a/app/scripts/notice-controller.js b/app/scripts/notice-controller.js
index 57aad40c5..14a63eae7 100644
--- a/app/scripts/notice-controller.js
+++ b/app/scripts/notice-controller.js
@@ -1,13 +1,17 @@
const EventEmitter = require('events').EventEmitter
+const semver = require('semver')
const extend = require('xtend')
const ObservableStore = require('obs-store')
const hardCodedNotices = require('../../notices/notices.json')
+const uniqBy = require('lodash.uniqby')
module.exports = class NoticeController extends EventEmitter {
constructor (opts) {
super()
this.noticePoller = null
+ this.firstVersion = opts.firstVersion
+ this.version = opts.version
const initState = extend({
noticesList: [],
}, opts.initState)
@@ -30,9 +34,9 @@ module.exports = class NoticeController extends EventEmitter {
return unreadNotices[unreadNotices.length - 1]
}
- setNoticesList (noticesList) {
+ async setNoticesList (noticesList) {
this.store.updateState({ noticesList })
- return Promise.resolve(true)
+ return true
}
markNoticeRead (noticeToMark, cb) {
@@ -50,12 +54,14 @@ module.exports = class NoticeController extends EventEmitter {
}
}
- updateNoticesList () {
- return this._retrieveNoticeData().then((newNotices) => {
- var oldNotices = this.getNoticesList()
- var combinedNotices = this._mergeNotices(oldNotices, newNotices)
- return Promise.resolve(this.setNoticesList(combinedNotices))
- })
+ async updateNoticesList () {
+ const newNotices = await this._retrieveNoticeData()
+ const oldNotices = this.getNoticesList()
+ const combinedNotices = this._mergeNotices(oldNotices, newNotices)
+ const filteredNotices = this._filterNotices(combinedNotices)
+ const result = this.setNoticesList(filteredNotices)
+ this._updateMemstore()
+ return result
}
startPolling () {
@@ -68,22 +74,30 @@ module.exports = class NoticeController extends EventEmitter {
}
_mergeNotices (oldNotices, newNotices) {
- var noticeMap = this._mapNoticeIds(oldNotices)
- newNotices.forEach((notice) => {
- if (noticeMap.indexOf(notice.id) === -1) {
- oldNotices.push(notice)
+ return uniqBy(oldNotices.concat(newNotices), 'id')
+ }
+
+ _filterNotices (notices) {
+ return notices.filter((newNotice) => {
+ if ('version' in newNotice) {
+ const satisfied = semver.satisfies(this.version, newNotice.version)
+ return satisfied
+ }
+ if ('firstVersion' in newNotice) {
+ const satisfied = semver.satisfies(this.firstVersion, newNotice.firstVersion)
+ return satisfied
}
+ return true
})
- return oldNotices
}
_mapNoticeIds (notices) {
return notices.map((notice) => notice.id)
}
- _retrieveNoticeData () {
+ async _retrieveNoticeData () {
// Placeholder for the API.
- return Promise.resolve(hardCodedNotices)
+ return hardCodedNotices
}
_updateMemstore () {
diff --git a/app/scripts/platforms/extension.js b/app/scripts/platforms/extension.js
index 00c2aa275..f5cc255d1 100644
--- a/app/scripts/platforms/extension.js
+++ b/app/scripts/platforms/extension.js
@@ -5,7 +5,6 @@ class ExtensionPlatform {
//
// Public
//
-
reload () {
extension.runtime.reload()
}
@@ -18,6 +17,20 @@ class ExtensionPlatform {
return extension.runtime.getManifest().version
}
+ openExtensionInBrowser () {
+ const extensionURL = extension.runtime.getURL('home.html')
+ this.openWindow({ url: extensionURL })
+ }
+
+ getPlatformInfo (cb) {
+ try {
+ extension.runtime.getPlatformInfo((platform) => {
+ cb(null, platform)
+ })
+ } catch (e) {
+ cb(e)
+ }
+ }
}
module.exports = ExtensionPlatform
diff --git a/app/scripts/popup-core.js b/app/scripts/popup-core.js
index 1e5d70e8b..2e4334bb1 100644
--- a/app/scripts/popup-core.js
+++ b/app/scripts/popup-core.js
@@ -1,7 +1,8 @@
const EventEmitter = require('events').EventEmitter
const async = require('async')
const Dnode = require('dnode')
-const Web3 = require('web3')
+const Eth = require('ethjs')
+const EthQuery = require('eth-query')
const launchMetamaskUi = require('../../ui')
const StreamProvider = require('web3-stream-provider')
const setupMultiplex = require('./lib/stream-utils.js').setupMultiplex
@@ -16,7 +17,6 @@ function initializePopup ({ container, connectionStream }, cb) {
(cb) => connectToAccountManager(connectionStream, cb),
(accountManager, cb) => launchMetamaskUi({ container, accountManager }, cb),
], cb)
-
}
function connectToAccountManager (connectionStream, cb) {
@@ -33,7 +33,9 @@ function setupWeb3Connection (connectionStream) {
providerStream.pipe(connectionStream).pipe(providerStream)
connectionStream.on('error', console.error.bind(console))
providerStream.on('error', console.error.bind(console))
- global.web3 = new Web3(providerStream)
+ global.ethereumProvider = providerStream
+ global.ethQuery = new EthQuery(providerStream)
+ global.eth = new Eth(providerStream)
}
function setupControllerConnection (connectionStream, cb) {
diff --git a/app/scripts/popup.js b/app/scripts/popup.js
index 0fbde54b3..53ab00e00 100644
--- a/app/scripts/popup.js
+++ b/app/scripts/popup.js
@@ -1,5 +1,6 @@
const injectCss = require('inject-css')
-const MetaMaskUiCss = require('../../ui/css')
+const OldMetaMaskUiCss = require('../../old-ui/css')
+const NewMetaMaskUiCss = require('../../ui/css')
const startPopup = require('./popup-core')
const PortStream = require('./lib/port-stream.js')
const isPopupOrNotification = require('./lib/is-popup-or-notification')
@@ -7,13 +8,18 @@ const extension = require('extensionizer')
const ExtensionPlatform = require('./platforms/extension')
const NotificationManager = require('./lib/notification-manager')
const notificationManager = new NotificationManager()
+const setupRaven = require('./setupRaven')
// create platform global
global.platform = new ExtensionPlatform()
+// setup sentry error reporting
+const release = global.platform.getVersion()
+setupRaven({ release })
+
// inject css
-const css = MetaMaskUiCss()
-injectCss(css)
+// const css = MetaMaskUiCss()
+// injectCss(css)
// identify window type (popup, notification)
const windowType = isPopupOrNotification()
@@ -28,8 +34,30 @@ const connectionStream = new PortStream(extensionPort)
const container = document.getElementById('app-content')
startPopup({ container, connectionStream }, (err, store) => {
if (err) return displayCriticalError(err)
+
+ // Code commented out until we begin auto adding users to NewUI
+ // const { isMascara, identities = {}, featureFlags = {} } = store.getState().metamask
+ // const firstTime = Object.keys(identities).length === 0
+ const { isMascara, featureFlags = {} } = store.getState().metamask
+ let betaUIState = featureFlags.betaUI
+
+ // Code commented out until we begin auto adding users to NewUI
+ // const useBetaCss = isMascara || firstTime || betaUIState
+ const useBetaCss = isMascara || betaUIState
+
+ let css = useBetaCss ? NewMetaMaskUiCss() : OldMetaMaskUiCss()
+ let deleteInjectedCss = injectCss(css)
+ let newBetaUIState
+
store.subscribe(() => {
const state = store.getState()
+ newBetaUIState = state.metamask.featureFlags.betaUI
+ if (newBetaUIState !== betaUIState) {
+ deleteInjectedCss()
+ betaUIState = newBetaUIState
+ css = betaUIState ? NewMetaMaskUiCss() : OldMetaMaskUiCss()
+ deleteInjectedCss = injectCss(css)
+ }
if (state.appState.shouldClose) notificationManager.closePopup()
})
})
@@ -41,7 +69,7 @@ function closePopupIfOpen (windowType) {
}
}
-function displayCriticalError(err) {
+function displayCriticalError (err) {
container.innerHTML = '<div class="critical-error">The MetaMask app failed to load: please open and close MetaMask again to restart.</div>'
container.style.height = '80px'
log.error(err.stack)
diff --git a/app/scripts/setupRaven.js b/app/scripts/setupRaven.js
new file mode 100644
index 000000000..7beffeff9
--- /dev/null
+++ b/app/scripts/setupRaven.js
@@ -0,0 +1,26 @@
+const Raven = require('./vendor/raven.min.js')
+const METAMASK_DEBUG = 'GULP_METAMASK_DEBUG'
+const PROD = 'https://3567c198f8a8412082d32655da2961d0@sentry.io/273505'
+const DEV = 'https://f59f3dd640d2429d9d0e2445a87ea8e1@sentry.io/273496'
+
+module.exports = setupRaven
+
+// Setup raven / sentry remote error reporting
+function setupRaven(opts) {
+ const { release } = opts
+ let ravenTarget
+
+ if (METAMASK_DEBUG) {
+ console.log('Setting up Sentry Remote Error Reporting: DEV')
+ ravenTarget = DEV
+ } else {
+ console.log('Setting up Sentry Remote Error Reporting: PROD')
+ ravenTarget = PROD
+ }
+
+ Raven.config(ravenTarget, {
+ release,
+ }).install()
+
+ return Raven
+}
diff --git a/app/scripts/transaction-manager.js b/app/scripts/transaction-manager.js
deleted file mode 100644
index d7051b2cb..000000000
--- a/app/scripts/transaction-manager.js
+++ /dev/null
@@ -1,404 +0,0 @@
-const EventEmitter = require('events')
-const async = require('async')
-const extend = require('xtend')
-const Semaphore = require('semaphore')
-const ObservableStore = require('obs-store')
-const ethUtil = require('ethereumjs-util')
-const EthQuery = require('eth-query')
-const TxProviderUtil = require('./lib/tx-utils')
-const createId = require('./lib/random-id')
-
-module.exports = class TransactionManager extends EventEmitter {
- constructor (opts) {
- super()
- this.store = new ObservableStore(extend({
- transactions: [],
- }, opts.initState))
- this.memStore = new ObservableStore({})
- this.networkStore = opts.networkStore || new ObservableStore({})
- this.preferencesStore = opts.preferencesStore || new ObservableStore({})
- this.txHistoryLimit = opts.txHistoryLimit
- this.provider = opts.provider
- this.blockTracker = opts.blockTracker
- this.query = new EthQuery(this.provider)
- this.txProviderUtils = new TxProviderUtil(this.provider)
- this.blockTracker.on('block', this.checkForTxInBlock.bind(this))
- this.signEthTx = opts.signTransaction
- this.nonceLock = Semaphore(1)
-
- // memstore is computed from a few different stores
- this._updateMemstore()
- this.store.subscribe(() => this._updateMemstore() )
- this.networkStore.subscribe(() => this._updateMemstore() )
- this.preferencesStore.subscribe(() => this._updateMemstore() )
- }
-
- getState () {
- return this.memStore.getState()
- }
-
- getNetwork () {
- return this.networkStore.getState().network
- }
-
- getSelectedAddress () {
- return this.preferencesStore.getState().selectedAddress
- }
-
- // Returns the tx list
- getTxList () {
- let network = this.getNetwork()
- let fullTxList = this.getFullTxList()
- return fullTxList.filter(txMeta => txMeta.metamaskNetworkId === network)
- }
-
- // Returns the number of txs for the current network.
- getTxCount () {
- return this.getTxList().length
- }
-
- // Returns the full tx list across all networks
- getFullTxList () {
- return this.store.getState().transactions
- }
-
- // Adds a tx to the txlist
- addTx (txMeta) {
- let txCount = this.getTxCount()
- let network = this.getNetwork()
- let fullTxList = this.getFullTxList()
- let txHistoryLimit = this.txHistoryLimit
-
- // checks if the length of the tx history is
- // longer then desired persistence limit
- // and then if it is removes only confirmed
- // or rejected tx's.
- // not tx's that are pending or unapproved
- if (txCount > txHistoryLimit - 1) {
- var index = fullTxList.findIndex((metaTx) => ((metaTx.status === 'confirmed' || metaTx.status === 'rejected') && network === txMeta.metamaskNetworkId))
- fullTxList.splice(index, 1)
- }
- fullTxList.push(txMeta)
- this._saveTxList(fullTxList)
- this.emit('update')
-
- this.once(`${txMeta.id}:signed`, function (txId) {
- this.removeAllListeners(`${txMeta.id}:rejected`)
- })
- this.once(`${txMeta.id}:rejected`, function (txId) {
- this.removeAllListeners(`${txMeta.id}:signed`)
- })
-
- this.emit('updateBadge')
- this.emit(`${txMeta.id}:unapproved`, txMeta)
- }
-
- // gets tx by Id and returns it
- getTx (txId, cb) {
- var txList = this.getTxList()
- var txMeta = txList.find(txData => txData.id === txId)
- return cb ? cb(txMeta) : txMeta
- }
-
- //
- updateTx (txMeta) {
- var txId = txMeta.id
- var txList = this.getFullTxList()
- var index = txList.findIndex(txData => txData.id === txId)
- txList[index] = txMeta
- this._saveTxList(txList)
- this.emit('update')
- }
-
- get unapprovedTxCount () {
- return Object.keys(this.getUnapprovedTxList()).length
- }
-
- get pendingTxCount () {
- return this.getTxsByMetaData('status', 'signed').length
- }
-
- addUnapprovedTransaction (txParams, done) {
- let txMeta
- async.waterfall([
- // validate
- (cb) => this.txProviderUtils.validateTxParams(txParams, cb),
- // construct txMeta
- (cb) => {
- txMeta = {
- id: createId(),
- time: (new Date()).getTime(),
- status: 'unapproved',
- metamaskNetworkId: this.getNetwork(),
- txParams: txParams,
- }
- cb()
- },
- // add default tx params
- (cb) => this.addTxDefaults(txMeta, cb),
- // save txMeta
- (cb) => {
- this.addTx(txMeta)
- cb(null, txMeta)
- },
- ], done)
- }
-
- addTxDefaults (txMeta, cb) {
- const txParams = txMeta.txParams
- // ensure value
- txParams.value = txParams.value || '0x0'
- this.query.gasPrice((err, gasPrice) => {
- if (err) return cb(err)
- // set gasPrice
- txParams.gasPrice = gasPrice
- // set gasLimit
- this.txProviderUtils.analyzeGasUsage(txMeta, cb)
- })
- }
-
- getUnapprovedTxList () {
- var txList = this.getTxList()
- return txList.filter((txMeta) => txMeta.status === 'unapproved')
- .reduce((result, tx) => {
- result[tx.id] = tx
- return result
- }, {})
- }
-
- approveTransaction (txId, cb = warn) {
- const self = this
- // approve
- self.setTxStatusApproved(txId)
- // only allow one tx at a time for atomic nonce usage
- self.nonceLock.take(() => {
- // begin signature process
- async.waterfall([
- (cb) => self.fillInTxParams(txId, cb),
- (cb) => self.signTransaction(txId, cb),
- (rawTx, cb) => self.publishTransaction(txId, rawTx, cb),
- ], (err) => {
- self.nonceLock.leave()
- if (err) {
- this.setTxStatusFailed(txId, {
- errCode: err.errCode || err,
- message: err.message || 'Transaction failed during approval',
- })
- return cb(err)
- }
- cb()
- })
- })
- }
-
- cancelTransaction (txId, cb = warn) {
- this.setTxStatusRejected(txId)
- cb()
- }
-
- fillInTxParams (txId, cb) {
- let txMeta = this.getTx(txId)
- this.txProviderUtils.fillInTxParams(txMeta.txParams, (err) => {
- if (err) return cb(err)
- this.updateTx(txMeta)
- cb()
- })
- }
-
- getChainId() {
- const networkState = this.networkStore.getState()
- const getChainId = parseInt(networkState.network)
- if (Number.isNaN(getChainId)) {
- return 0
- } else {
- return getChainId
- }
- }
-
- signTransaction (txId, cb) {
- const txMeta = this.getTx(txId)
- const txParams = txMeta.txParams
- const fromAddress = txParams.from
- // add network/chain id
- txParams.chainId = this.getChainId()
- const ethTx = this.txProviderUtils.buildEthTxFromParams(txParams)
- this.signEthTx(ethTx, fromAddress).then(() => {
- this.setTxStatusSigned(txMeta.id)
- cb(null, ethUtil.bufferToHex(ethTx.serialize()))
- }).catch((err) => {
- cb(err)
- })
- }
-
- publishTransaction (txId, rawTx, cb) {
- this.txProviderUtils.publishTransaction(rawTx, (err, txHash) => {
- if (err) return cb(err)
- this.setTxHash(txId, txHash)
- this.setTxStatusSubmitted(txId)
- cb()
- })
- }
-
- // receives a txHash records the tx as signed
- setTxHash (txId, txHash) {
- // Add the tx hash to the persisted meta-tx object
- let txMeta = this.getTx(txId)
- txMeta.hash = txHash
- this.updateTx(txMeta)
- }
-
- /*
- Takes an object of fields to search for eg:
- var thingsToLookFor = {
- to: '0x0..',
- from: '0x0..',
- status: 'signed',
- }
- and returns a list of tx with all
- options matching
-
- this is for things like filtering a the tx list
- for only tx's from 1 account
- or for filltering for all txs from one account
- and that have been 'confirmed'
- */
- getFilteredTxList (opts) {
- var filteredTxList
- Object.keys(opts).forEach((key) => {
- filteredTxList = this.getTxsByMetaData(key, opts[key], filteredTxList)
- })
- return filteredTxList
- }
-
- getTxsByMetaData (key, value, txList = this.getTxList()) {
- return txList.filter((txMeta) => {
- if (txMeta.txParams[key]) {
- return txMeta.txParams[key] === value
- } else {
- return txMeta[key] === value
- }
- })
- }
-
- // STATUS METHODS
- // get::set status
-
- // should return the status of the tx.
- getTxStatus (txId) {
- const txMeta = this.getTx(txId)
- return txMeta.status
- }
-
- // should update the status of the tx to 'rejected'.
- setTxStatusRejected (txId) {
- this._setTxStatus(txId, 'rejected')
- }
-
- // should update the status of the tx to 'approved'.
- setTxStatusApproved (txId) {
- this._setTxStatus(txId, 'approved')
- }
-
- // should update the status of the tx to 'signed'.
- setTxStatusSigned (txId) {
- this._setTxStatus(txId, 'signed')
- }
-
- // should update the status of the tx to 'submitted'.
- setTxStatusSubmitted (txId) {
- this._setTxStatus(txId, 'submitted')
- }
-
- // should update the status of the tx to 'confirmed'.
- setTxStatusConfirmed (txId) {
- this._setTxStatus(txId, 'confirmed')
- }
-
- setTxStatusFailed (txId, reason) {
- let txMeta = this.getTx(txId)
- txMeta.err = reason
- this.updateTx(txMeta)
- this._setTxStatus(txId, 'failed')
- }
-
- // merges txParams obj onto txData.txParams
- // use extend to ensure that all fields are filled
- updateTxParams (txId, txParams) {
- var txMeta = this.getTx(txId)
- txMeta.txParams = extend(txMeta.txParams, txParams)
- this.updateTx(txMeta)
- }
-
- // checks if a signed tx is in a block and
- // if included sets the tx status as 'confirmed'
- checkForTxInBlock () {
- var signedTxList = this.getFilteredTxList({status: 'submitted'})
- if (!signedTxList.length) return
- signedTxList.forEach((txMeta) => {
- var txHash = txMeta.hash
- var txId = txMeta.id
- if (!txHash) {
- let errReason = {
- errCode: 'No hash was provided',
- message: 'We had an error while submitting this transaction, please try again.',
- }
- return this.setTxStatusFailed(txId, errReason)
- }
- this.query.getTransactionByHash(txHash, (err, txParams) => {
- if (err || !txParams) {
- if (!txParams) return
- txMeta.err = {
- isWarning: true,
- errorCode: err,
- message: 'There was a problem loading this transaction.',
- }
- this.updateTx(txMeta)
- return console.error(err)
- }
- if (txParams.blockNumber) {
- this.setTxStatusConfirmed(txId)
- }
- })
- })
- }
-
- // PRIVATE METHODS
-
- // Should find the tx in the tx list and
- // update it.
- // should set the status in txData
- // - `'unapproved'` the user has not responded
- // - `'rejected'` the user has responded no!
- // - `'approved'` the user has approved the tx
- // - `'signed'` the tx is signed
- // - `'submitted'` the tx is sent to a server
- // - `'confirmed'` the tx has been included in a block.
- _setTxStatus (txId, status) {
- var txMeta = this.getTx(txId)
- txMeta.status = status
- this.emit(`${txMeta.id}:${status}`, txId)
- if (status === 'submitted' || status === 'rejected') {
- this.emit(`${txMeta.id}:finished`, txMeta)
- }
- this.updateTx(txMeta)
- this.emit('updateBadge')
- }
-
- // Saves the new/updated txList.
- // Function is intended only for internal use
- _saveTxList (transactions) {
- this.store.updateState({ transactions })
- }
-
- _updateMemstore () {
- const unapprovedTxs = this.getUnapprovedTxList()
- const selectedAddressTxList = this.getFilteredTxList({
- from: this.getSelectedAddress(),
- metamaskNetworkId: this.getNetwork(),
- })
- this.memStore.updateState({ unapprovedTxs, selectedAddressTxList })
- }
-}
-
-
-const warn = () => console.warn('warn was used no cb provided')
diff --git a/app/scripts/vendor/raven.min.js b/app/scripts/vendor/raven.min.js
new file mode 100644
index 000000000..b439aeae6
--- /dev/null
+++ b/app/scripts/vendor/raven.min.js
@@ -0,0 +1,3 @@
+/*! Raven.js 3.22.1 (7584197) | github.com/getsentry/raven-js */
+!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.Raven=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){function d(a){this.name="RavenConfigError",this.message=a}d.prototype=new Error,d.prototype.constructor=d,b.exports=d},{}],2:[function(a,b,c){var d=function(a,b,c){var d=a[b],e=a;if(b in a){var f="warn"===b?"warning":b;a[b]=function(){var a=[].slice.call(arguments),g=""+a.join(" "),h={level:f,logger:"console",extra:{arguments:a}};"assert"===b?a[0]===!1&&(g="Assertion failed: "+(a.slice(1).join(" ")||"console.assert"),h.extra.arguments=a.slice(1),c&&c(g,h)):c&&c(g,h),d&&Function.prototype.apply.call(d,e,a)}}};b.exports={wrapMethod:d}},{}],3:[function(a,b,c){(function(c){function d(){return+new Date}function e(a,b){return o(b)?function(c){return b(c,a)}:b}function f(){this.a=!("object"!=typeof JSON||!JSON.stringify),this.b=!n(K),this.c=!n(L),this.d=null,this.e=null,this.f=null,this.g=null,this.h=null,this.i=null,this.j={},this.k={release:J.SENTRY_RELEASE&&J.SENTRY_RELEASE.id,logger:"javascript",ignoreErrors:[],ignoreUrls:[],whitelistUrls:[],includePaths:[],headers:null,collectWindowErrors:!0,maxMessageLength:0,maxUrlLength:250,stackTraceLimit:50,autoBreadcrumbs:!0,instrument:!0,sampleRate:1},this.l={method:"POST",keepalive:!0,referrerPolicy:"origin"},this.m=0,this.n=!1,this.o=Error.stackTraceLimit,this.p=J.console||{},this.q={},this.r=[],this.s=d(),this.t=[],this.u=[],this.v=null,this.w=J.location,this.x=this.w&&this.w.href,this.y();for(var a in this.p)this.q[a]=this.p[a]}var g=a(6),h=a(7),i=a(1),j=a(5),k=j.isError,l=j.isObject,m=j.isErrorEvent,n=j.isUndefined,o=j.isFunction,p=j.isString,q=j.isArray,r=j.isEmptyObject,s=j.each,t=j.objectMerge,u=j.truncate,v=j.objectFrozen,w=j.hasKey,x=j.joinRegExp,y=j.urlencode,z=j.uuid4,A=j.htmlTreeAsString,B=j.isSameException,C=j.isSameStacktrace,D=j.parseUrl,E=j.fill,F=j.supportsFetch,G=a(2).wrapMethod,H="source protocol user pass host port path".split(" "),I=/^(?:(\w+):)?\/\/(?:(\w+)(:\w+)?@)?([\w\.-]+)(?::(\d+))?(\/.*)/,J="undefined"!=typeof window?window:"undefined"!=typeof c?c:"undefined"!=typeof self?self:{},K=J.document,L=J.navigator;f.prototype={VERSION:"3.22.1",debug:!1,TraceKit:g,config:function(a,b){var c=this;if(c.g)return this.z("error","Error: Raven has already been configured"),c;if(!a)return c;var d=c.k;b&&s(b,function(a,b){"tags"===a||"extra"===a||"user"===a?c.j[a]=b:d[a]=b}),c.setDSN(a),d.ignoreErrors.push(/^Script error\.?$/),d.ignoreErrors.push(/^Javascript error: Script error\.? on line 0$/),d.ignoreErrors=x(d.ignoreErrors),d.ignoreUrls=!!d.ignoreUrls.length&&x(d.ignoreUrls),d.whitelistUrls=!!d.whitelistUrls.length&&x(d.whitelistUrls),d.includePaths=x(d.includePaths),d.maxBreadcrumbs=Math.max(0,Math.min(d.maxBreadcrumbs||100,100));var e={xhr:!0,console:!0,dom:!0,location:!0,sentry:!0},f=d.autoBreadcrumbs;"[object Object]"==={}.toString.call(f)?f=t(e,f):f!==!1&&(f=e),d.autoBreadcrumbs=f;var h={tryCatch:!0},i=d.instrument;return"[object Object]"==={}.toString.call(i)?i=t(h,i):i!==!1&&(i=h),d.instrument=i,g.collectWindowErrors=!!d.collectWindowErrors,c},install:function(){var a=this;return a.isSetup()&&!a.n&&(g.report.subscribe(function(){a.A.apply(a,arguments)}),a.B(),a.k.instrument&&a.k.instrument.tryCatch&&a.C(),a.k.autoBreadcrumbs&&a.D(),a.E(),a.n=!0),Error.stackTraceLimit=a.k.stackTraceLimit,this},setDSN:function(a){var b=this,c=b.F(a),d=c.path.lastIndexOf("/"),e=c.path.substr(1,d);b.G=a,b.h=c.user,b.H=c.pass&&c.pass.substr(1),b.i=c.path.substr(d+1),b.g=b.I(c),b.J=b.g+"/"+e+"api/"+b.i+"/store/",this.y()},context:function(a,b,c){return o(a)&&(c=b||[],b=a,a=void 0),this.wrap(a,b).apply(this,c)},wrap:function(a,b,c){function d(){var d=[],f=arguments.length,g=!a||a&&a.deep!==!1;for(c&&o(c)&&c.apply(this,arguments);f--;)d[f]=g?e.wrap(a,arguments[f]):arguments[f];try{return b.apply(this,d)}catch(h){throw e.K(),e.captureException(h,a),h}}var e=this;if(n(b)&&!o(a))return a;if(o(a)&&(b=a,a=void 0),!o(b))return b;try{if(b.L)return b;if(b.M)return b.M}catch(f){return b}for(var g in b)w(b,g)&&(d[g]=b[g]);return d.prototype=b.prototype,b.M=d,d.L=!0,d.N=b,d},uninstall:function(){return g.report.uninstall(),this.O(),this.P(),Error.stackTraceLimit=this.o,this.n=!1,this},captureException:function(a,b){var c=!k(a),d=!m(a),e=m(a)&&!a.error;if(c&&d||e)return this.captureMessage(a,t({trimHeadFrames:1,stacktrace:!0},b));m(a)&&(a=a.error),this.d=a;try{var f=g.computeStackTrace(a);this.Q(f,b)}catch(h){if(a!==h)throw h}return this},captureMessage:function(a,b){if(!this.k.ignoreErrors.test||!this.k.ignoreErrors.test(a)){b=b||{};var c,d=t({message:a+""},b);try{throw new Error(a)}catch(e){c=e}c.name=null;var f=g.computeStackTrace(c),h=q(f.stack)&&f.stack[1],i=h&&h.url||"";if((!this.k.ignoreUrls.test||!this.k.ignoreUrls.test(i))&&(!this.k.whitelistUrls.test||this.k.whitelistUrls.test(i))){if(this.k.stacktrace||b&&b.stacktrace){b=t({fingerprint:a,trimHeadFrames:(b.trimHeadFrames||0)+1},b);var j=this.R(f,b);d.stacktrace={frames:j.reverse()}}return this.S(d),this}}},captureBreadcrumb:function(a){var b=t({timestamp:d()/1e3},a);if(o(this.k.breadcrumbCallback)){var c=this.k.breadcrumbCallback(b);if(l(c)&&!r(c))b=c;else if(c===!1)return this}return this.u.push(b),this.u.length>this.k.maxBreadcrumbs&&this.u.shift(),this},addPlugin:function(a){var b=[].slice.call(arguments,1);return this.r.push([a,b]),this.n&&this.E(),this},setUserContext:function(a){return this.j.user=a,this},setExtraContext:function(a){return this.T("extra",a),this},setTagsContext:function(a){return this.T("tags",a),this},clearContext:function(){return this.j={},this},getContext:function(){return JSON.parse(h(this.j))},setEnvironment:function(a){return this.k.environment=a,this},setRelease:function(a){return this.k.release=a,this},setDataCallback:function(a){var b=this.k.dataCallback;return this.k.dataCallback=e(b,a),this},setBreadcrumbCallback:function(a){var b=this.k.breadcrumbCallback;return this.k.breadcrumbCallback=e(b,a),this},setShouldSendCallback:function(a){var b=this.k.shouldSendCallback;return this.k.shouldSendCallback=e(b,a),this},setTransport:function(a){return this.k.transport=a,this},lastException:function(){return this.d},lastEventId:function(){return this.f},isSetup:function(){return!!this.a&&(!!this.g||(this.ravenNotConfiguredError||(this.ravenNotConfiguredError=!0,this.z("error","Error: Raven has not been configured.")),!1))},afterLoad:function(){var a=J.RavenConfig;a&&this.config(a.dsn,a.config).install()},showReportDialog:function(a){if(K){a=a||{};var b=a.eventId||this.lastEventId();if(!b)throw new i("Missing eventId");var c=a.dsn||this.G;if(!c)throw new i("Missing DSN");var d=encodeURIComponent,e="";e+="?eventId="+d(b),e+="&dsn="+d(c);var f=a.user||this.j.user;f&&(f.name&&(e+="&name="+d(f.name)),f.email&&(e+="&email="+d(f.email)));var g=this.I(this.F(c)),h=K.createElement("script");h.async=!0,h.src=g+"/api/embed/error-page/"+e,(K.head||K.body).appendChild(h)}},K:function(){var a=this;this.m+=1,setTimeout(function(){a.m-=1})},U:function(a,b){var c,d;if(this.b){b=b||{},a="raven"+a.substr(0,1).toUpperCase()+a.substr(1),K.createEvent?(c=K.createEvent("HTMLEvents"),c.initEvent(a,!0,!0)):(c=K.createEventObject(),c.eventType=a);for(d in b)w(b,d)&&(c[d]=b[d]);if(K.createEvent)K.dispatchEvent(c);else try{K.fireEvent("on"+c.eventType.toLowerCase(),c)}catch(e){}}},V:function(a){var b=this;return function(c){if(b.W=null,b.v!==c){b.v=c;var d;try{d=A(c.target)}catch(e){d="<unknown>"}b.captureBreadcrumb({category:"ui."+a,message:d})}}},X:function(){var a=this,b=1e3;return function(c){var d;try{d=c.target}catch(e){return}var f=d&&d.tagName;if(f&&("INPUT"===f||"TEXTAREA"===f||d.isContentEditable)){var g=a.W;g||a.V("input")(c),clearTimeout(g),a.W=setTimeout(function(){a.W=null},b)}}},Y:function(a,b){var c=D(this.w.href),d=D(b),e=D(a);this.x=b,c.protocol===d.protocol&&c.host===d.host&&(b=d.relative),c.protocol===e.protocol&&c.host===e.host&&(a=e.relative),this.captureBreadcrumb({category:"navigation",data:{to:b,from:a}})},B:function(){var a=this;a.Z=Function.prototype.toString,Function.prototype.toString=function(){return"function"==typeof this&&this.L?a.Z.apply(this.N,arguments):a.Z.apply(this,arguments)}},O:function(){this.Z&&(Function.prototype.toString=this.Z)},C:function(){function a(a){return function(b,d){for(var e=new Array(arguments.length),f=0;f<e.length;++f)e[f]=arguments[f];var g=e[0];return o(g)&&(e[0]=c.wrap(g)),a.apply?a.apply(this,e):a(e[0],e[1])}}function b(a){var b=J[a]&&J[a].prototype;b&&b.hasOwnProperty&&b.hasOwnProperty("addEventListener")&&(E(b,"addEventListener",function(b){return function(d,f,g,h){try{f&&f.handleEvent&&(f.handleEvent=c.wrap(f.handleEvent))}catch(i){}var j,k,l;return e&&e.dom&&("EventTarget"===a||"Node"===a)&&(k=c.V("click"),l=c.X(),j=function(a){if(a){var b;try{b=a.type}catch(c){return}return"click"===b?k(a):"keypress"===b?l(a):void 0}}),b.call(this,d,c.wrap(f,void 0,j),g,h)}},d),E(b,"removeEventListener",function(a){return function(b,c,d,e){try{c=c&&(c.M?c.M:c)}catch(f){}return a.call(this,b,c,d,e)}},d))}var c=this,d=c.t,e=this.k.autoBreadcrumbs;E(J,"setTimeout",a,d),E(J,"setInterval",a,d),J.requestAnimationFrame&&E(J,"requestAnimationFrame",function(a){return function(b){return a(c.wrap(b))}},d);for(var f=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],g=0;g<f.length;g++)b(f[g])},D:function(){function a(a,c){a in c&&o(c[a])&&E(c,a,function(a){return b.wrap(a)})}var b=this,c=this.k.autoBreadcrumbs,d=b.t;if(c.xhr&&"XMLHttpRequest"in J){var e=XMLHttpRequest.prototype;E(e,"open",function(a){return function(c,d){return p(d)&&d.indexOf(b.h)===-1&&(this.$={method:c,url:d,status_code:null}),a.apply(this,arguments)}},d),E(e,"send",function(c){return function(){function d(){if(e.$&&4===e.readyState){try{e.$.status_code=e.status}catch(a){}b.captureBreadcrumb({type:"http",category:"xhr",data:e.$})}}for(var e=this,f=["onload","onerror","onprogress"],g=0;g<f.length;g++)a(f[g],e);return"onreadystatechange"in e&&o(e.onreadystatechange)?E(e,"onreadystatechange",function(a){return b.wrap(a,void 0,d)}):e.onreadystatechange=d,c.apply(this,arguments)}},d)}c.xhr&&F()&&E(J,"fetch",function(a){return function(){for(var c=new Array(arguments.length),d=0;d<c.length;++d)c[d]=arguments[d];var e,f=c[0],g="GET";if("string"==typeof f?e=f:"Request"in J&&f instanceof J.Request?(e=f.url,f.method&&(g=f.method)):e=""+f,e.indexOf(b.h)!==-1)return a.apply(this,c);c[1]&&c[1].method&&(g=c[1].method);var h={method:g,url:e,status_code:null};return a.apply(this,c).then(function(a){return h.status_code=a.status,b.captureBreadcrumb({type:"http",category:"fetch",data:h}),a})}},d),c.dom&&this.b&&(K.addEventListener?(K.addEventListener("click",b.V("click"),!1),K.addEventListener("keypress",b.X(),!1)):(K.attachEvent("onclick",b.V("click")),K.attachEvent("onkeypress",b.X())));var f=J.chrome,g=f&&f.app&&f.app.runtime,h=!g&&J.history&&history.pushState&&history.replaceState;if(c.location&&h){var i=J.onpopstate;J.onpopstate=function(){var a=b.w.href;if(b.Y(b.x,a),i)return i.apply(this,arguments)};var j=function(a){return function(){var c=arguments.length>2?arguments[2]:void 0;return c&&b.Y(b.x,c+""),a.apply(this,arguments)}};E(history,"pushState",j,d),E(history,"replaceState",j,d)}if(c.console&&"console"in J&&console.log){var k=function(a,c){b.captureBreadcrumb({message:a,level:c.level,category:"console"})};s(["debug","info","warn","error","log"],function(a,b){G(console,b,k)})}},P:function(){for(var a;this.t.length;){a=this.t.shift();var b=a[0],c=a[1],d=a[2];b[c]=d}},E:function(){var a=this;s(this.r,function(b,c){var d=c[0],e=c[1];d.apply(a,[a].concat(e))})},F:function(a){var b=I.exec(a),c={},d=7;try{for(;d--;)c[H[d]]=b[d]||""}catch(e){throw new i("Invalid DSN: "+a)}if(c.pass&&!this.k.allowSecretKey)throw new i("Do not specify your secret key in the DSN. See: http://bit.ly/raven-secret-key");return c},I:function(a){var b="//"+a.host+(a.port?":"+a.port:"");return a.protocol&&(b=a.protocol+":"+b),b},A:function(){this.m||this.Q.apply(this,arguments)},Q:function(a,b){var c=this.R(a,b);this.U("handle",{stackInfo:a,options:b}),this._(a.name,a.message,a.url,a.lineno,c,b)},R:function(a,b){var c=this,d=[];if(a.stack&&a.stack.length&&(s(a.stack,function(b,e){var f=c.aa(e,a.url);f&&d.push(f)}),b&&b.trimHeadFrames))for(var e=0;e<b.trimHeadFrames&&e<d.length;e++)d[e].in_app=!1;return d=d.slice(0,this.k.stackTraceLimit)},aa:function(a,b){var c={filename:a.url,lineno:a.line,colno:a.column,"function":a.func||"?"};return a.url||(c.filename=b),c.in_app=!(this.k.includePaths.test&&!this.k.includePaths.test(c.filename)||/(Raven|TraceKit)\./.test(c["function"])||/raven\.(min\.)?js$/.test(c.filename)),c},_:function(a,b,c,d,e,f){var g=(a?a+": ":"")+(b||"");if(!this.k.ignoreErrors.test||!this.k.ignoreErrors.test(b)&&!this.k.ignoreErrors.test(g)){var h;if(e&&e.length?(c=e[0].filename||c,e.reverse(),h={frames:e}):c&&(h={frames:[{filename:c,lineno:d,in_app:!0}]}),(!this.k.ignoreUrls.test||!this.k.ignoreUrls.test(c))&&(!this.k.whitelistUrls.test||this.k.whitelistUrls.test(c))){var i=t({exception:{values:[{type:a,value:b,stacktrace:h}]},culprit:c},f);this.S(i)}}},ba:function(a){var b=this.k.maxMessageLength;if(a.message&&(a.message=u(a.message,b)),a.exception){var c=a.exception.values[0];c.value=u(c.value,b)}var d=a.request;return d&&(d.url&&(d.url=u(d.url,this.k.maxUrlLength)),d.Referer&&(d.Referer=u(d.Referer,this.k.maxUrlLength))),a.breadcrumbs&&a.breadcrumbs.values&&this.ca(a.breadcrumbs),a},ca:function(a){for(var b,c,d,e=["to","from","url"],f=0;f<a.values.length;++f)if(c=a.values[f],c.hasOwnProperty("data")&&l(c.data)&&!v(c.data)){d=t({},c.data);for(var g=0;g<e.length;++g)b=e[g],d.hasOwnProperty(b)&&d[b]&&(d[b]=u(d[b],this.k.maxUrlLength));a.values[f].data=d}},da:function(){if(this.c||this.b){var a={};return this.c&&L.userAgent&&(a.headers={"User-Agent":navigator.userAgent}),J.location&&J.location.href&&(a.url=J.location.href),this.b&&K.referrer&&(a.headers||(a.headers={}),a.headers.Referer=K.referrer),a}},y:function(){this.ea=0,this.fa=null},ga:function(){return this.ea&&d()-this.fa<this.ea},ha:function(a){var b=this.e;return!(!b||a.message!==b.message||a.culprit!==b.culprit)&&(a.stacktrace||b.stacktrace?C(a.stacktrace,b.stacktrace):!a.exception&&!b.exception||B(a.exception,b.exception))},ia:function(a){if(!this.ga()){var b=a.status;if(400===b||401===b||429===b){var c;try{c=F()?a.headers.get("Retry-After"):a.getResponseHeader("Retry-After"),c=1e3*parseInt(c,10)}catch(e){}this.ea=c?c:2*this.ea||1e3,this.fa=d()}}},S:function(a){var b=this.k,c={project:this.i,logger:b.logger,platform:"javascript"},e=this.da();if(e&&(c.request=e),a.trimHeadFrames&&delete a.trimHeadFrames,a=t(c,a),a.tags=t(t({},this.j.tags),a.tags),a.extra=t(t({},this.j.extra),a.extra),a.extra["session:duration"]=d()-this.s,this.u&&this.u.length>0&&(a.breadcrumbs={values:[].slice.call(this.u,0)}),this.j.user&&(a.user=this.j.user),b.environment&&(a.environment=b.environment),b.release&&(a.release=b.release),b.serverName&&(a.server_name=b.serverName),Object.keys(a).forEach(function(b){(null==a[b]||""===a[b]||r(a[b]))&&delete a[b]}),o(b.dataCallback)&&(a=b.dataCallback(a)||a),a&&!r(a)&&(!o(b.shouldSendCallback)||b.shouldSendCallback(a)))return this.ga()?void this.z("warn","Raven dropped error due to backoff: ",a):void("number"==typeof b.sampleRate?Math.random()<b.sampleRate&&this.ja(a):this.ja(a))},ka:function(){return z()},ja:function(a,b){var c=this,d=this.k;if(this.isSetup()){if(a=this.ba(a),!this.k.allowDuplicates&&this.ha(a))return void this.z("warn","Raven dropped repeat event: ",a);this.f=a.event_id||(a.event_id=this.ka()),this.e=a,this.z("debug","Raven about to send:",a);var e={sentry_version:"7",sentry_client:"raven-js/"+this.VERSION,sentry_key:this.h};this.H&&(e.sentry_secret=this.H);var f=a.exception&&a.exception.values[0];this.k.autoBreadcrumbs&&this.k.autoBreadcrumbs.sentry&&this.captureBreadcrumb({category:"sentry",message:f?(f.type?f.type+": ":"")+f.value:a.message,event_id:a.event_id,level:a.level||"error"});var g=this.J;(d.transport||this.la).call(this,{url:g,auth:e,data:a,options:d,onSuccess:function(){c.y(),c.U("success",{data:a,src:g}),b&&b()},onError:function(d){c.z("error","Raven transport failed to send: ",d),d.request&&c.ia(d.request),c.U("failure",{data:a,src:g}),d=d||new Error("Raven send failed (no additional details provided)"),b&&b(d)}})}},la:function(a){var b=a.url+"?"+y(a.auth),c=null,d={};if(a.options.headers&&(c=this.ma(a.options.headers)),a.options.fetchParameters&&(d=this.ma(a.options.fetchParameters)),F()){d.body=h(a.data);var e=t({},this.l),f=t(e,d);return c&&(f.headers=c),J.fetch(b,f).then(function(b){if(b.ok)a.onSuccess&&a.onSuccess();else{var c=new Error("Sentry error code: "+b.status);c.request=b,a.onError&&a.onError(c)}})["catch"](function(){a.onError&&a.onError(new Error("Sentry error code: network unavailable"))})}var g=J.XMLHttpRequest&&new J.XMLHttpRequest;if(g){var i="withCredentials"in g||"undefined"!=typeof XDomainRequest;i&&("withCredentials"in g?g.onreadystatechange=function(){if(4===g.readyState)if(200===g.status)a.onSuccess&&a.onSuccess();else if(a.onError){var b=new Error("Sentry error code: "+g.status);b.request=g,a.onError(b)}}:(g=new XDomainRequest,b=b.replace(/^https?:/,""),a.onSuccess&&(g.onload=a.onSuccess),a.onError&&(g.onerror=function(){var b=new Error("Sentry error code: XDomainRequest");b.request=g,a.onError(b)})),g.open("POST",b),c&&s(c,function(a,b){g.setRequestHeader(a,b)}),g.send(h(a.data)))}},ma:function(a){var b={};for(var c in a)if(a.hasOwnProperty(c)){var d=a[c];b[c]="function"==typeof d?d():d}return b},z:function(a){this.q[a]&&this.debug&&Function.prototype.apply.call(this.q[a],this.p,[].slice.call(arguments,1))},T:function(a,b){n(b)?delete this.j[a]:this.j[a]=t(this.j[a]||{},b)}},f.prototype.setUser=f.prototype.setUserContext,f.prototype.setReleaseContext=f.prototype.setRelease,b.exports=f}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{1:1,2:2,5:5,6:6,7:7}],4:[function(a,b,c){(function(c){var d=a(3),e="undefined"!=typeof window?window:"undefined"!=typeof c?c:"undefined"!=typeof self?self:{},f=e.Raven,g=new d;g.noConflict=function(){return e.Raven=f,g},g.afterLoad(),b.exports=g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{3:3}],5:[function(a,b,c){(function(a){function c(a){return"object"==typeof a&&null!==a}function d(a){switch({}.toString.call(a)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return a instanceof Error}}function e(a){return l()&&"[object ErrorEvent]"==={}.toString.call(a)}function f(a){return void 0===a}function g(a){return"function"==typeof a}function h(a){return"[object Object]"===Object.prototype.toString.call(a)}function i(a){return"[object String]"===Object.prototype.toString.call(a)}function j(a){return"[object Array]"===Object.prototype.toString.call(a)}function k(a){if(!h(a))return!1;for(var b in a)if(a.hasOwnProperty(b))return!1;return!0}function l(){try{return new ErrorEvent(""),!0}catch(a){return!1}}function m(){if(!("fetch"in E))return!1;try{return new Headers,new Request(""),new Response,!0}catch(a){return!1}}function n(a){function b(b,c){var d=a(b)||b;return c?c(d)||d:d}return b}function o(a,b){var c,d;if(f(a.length))for(c in a)s(a,c)&&b.call(null,c,a[c]);else if(d=a.length)for(c=0;c<d;c++)b.call(null,c,a[c])}function p(a,b){return b?(o(b,function(b,c){a[b]=c}),a):a}function q(a){return!!Object.isFrozen&&Object.isFrozen(a)}function r(a,b){return!b||a.length<=b?a:a.substr(0,b)+"…"}function s(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function t(a){for(var b,c=[],d=0,e=a.length;d<e;d++)b=a[d],i(b)?c.push(b.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):b&&b.source&&c.push(b.source);return new RegExp(c.join("|"),"i")}function u(a){var b=[];return o(a,function(a,c){b.push(encodeURIComponent(a)+"="+encodeURIComponent(c))}),b.join("&")}function v(a){if("string"!=typeof a)return{};var b=a.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/),c=b[6]||"",d=b[8]||"";return{protocol:b[2],host:b[4],path:b[5],relative:b[5]+c+d}}function w(){var a=E.crypto||E.msCrypto;if(!f(a)&&a.getRandomValues){var b=new Uint16Array(8);a.getRandomValues(b),b[3]=4095&b[3]|16384,b[4]=16383&b[4]|32768;var c=function(a){for(var b=a.toString(16);b.length<4;)b="0"+b;return b};return c(b[0])+c(b[1])+c(b[2])+c(b[3])+c(b[4])+c(b[5])+c(b[6])+c(b[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(a){var b=16*Math.random()|0,c="x"===a?b:3&b|8;return c.toString(16)})}function x(a){for(var b,c=5,d=80,e=[],f=0,g=0,h=" > ",i=h.length;a&&f++<c&&(b=y(a),!("html"===b||f>1&&g+e.length*i+b.length>=d));)e.push(b),g+=b.length,a=a.parentNode;return e.reverse().join(h)}function y(a){var b,c,d,e,f,g=[];if(!a||!a.tagName)return"";if(g.push(a.tagName.toLowerCase()),a.id&&g.push("#"+a.id),b=a.className,b&&i(b))for(c=b.split(/\s+/),f=0;f<c.length;f++)g.push("."+c[f]);var h=["type","name","title","alt"];for(f=0;f<h.length;f++)d=h[f],e=a.getAttribute(d),e&&g.push("["+d+'="'+e+'"]');return g.join("")}function z(a,b){return!!(!!a^!!b)}function A(a,b){return f(a)&&f(b)}function B(a,b){return!z(a,b)&&(a=a.values[0],b=b.values[0],a.type===b.type&&a.value===b.value&&(!A(a.stacktrace,b.stacktrace)&&C(a.stacktrace,b.stacktrace)))}function C(a,b){if(z(a,b))return!1;var c=a.frames,d=b.frames;if(c.length!==d.length)return!1;for(var e,f,g=0;g<c.length;g++)if(e=c[g],f=d[g],e.filename!==f.filename||e.lineno!==f.lineno||e.colno!==f.colno||e["function"]!==f["function"])return!1;return!0}function D(a,b,c,d){var e=a[b];a[b]=c(e),a[b].L=!0,a[b].N=e,d&&d.push([a,b,e])}var E="undefined"!=typeof window?window:"undefined"!=typeof a?a:"undefined"!=typeof self?self:{};b.exports={isObject:c,isError:d,isErrorEvent:e,isUndefined:f,isFunction:g,isPlainObject:h,isString:i,isArray:j,isEmptyObject:k,supportsErrorEvent:l,supportsFetch:m,wrappedCallback:n,each:o,objectMerge:p,truncate:r,objectFrozen:q,hasKey:s,joinRegExp:t,urlencode:u,uuid4:w,htmlTreeAsString:x,htmlElementAsString:y,isSameException:B,isSameStacktrace:C,parseUrl:v,fill:D}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],6:[function(a,b,c){(function(c){function d(){return"undefined"==typeof document||null==document.location?"":document.location.href}var e=a(5),f={collectWindowErrors:!0,debug:!1},g="undefined"!=typeof window?window:"undefined"!=typeof c?c:"undefined"!=typeof self?self:{},h=[].slice,i="?",j=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;f.report=function(){function a(a){m(),s.push(a)}function b(a){for(var b=s.length-1;b>=0;--b)s[b]===a&&s.splice(b,1)}function c(){n(),s=[]}function k(a,b){var c=null;if(!b||f.collectWindowErrors){for(var d in s)if(s.hasOwnProperty(d))try{s[d].apply(null,[a].concat(h.call(arguments,2)))}catch(e){c=e}if(c)throw c}}function l(a,b,c,g,h){var l=null,m=e.isErrorEvent(h)?h.error:h,n=e.isErrorEvent(a)?a.message:a;if(v)f.computeStackTrace.augmentStackTraceWithInitialElement(v,b,c,n),o();else if(m&&e.isError(m))l=f.computeStackTrace(m),k(l,!0);else{var p,r={url:b,line:c,column:g},s=void 0;if("[object String]"==={}.toString.call(n)){var p=n.match(j);p&&(s=p[1],n=p[2])}r.func=i,l={name:s,message:n,url:d(),stack:[r]},k(l,!0)}return!!q&&q.apply(this,arguments)}function m(){r||(q=g.onerror,g.onerror=l,r=!0)}function n(){r&&(g.onerror=q,r=!1,q=void 0)}function o(){var a=v,b=t;t=null,v=null,u=null,k.apply(null,[a,!1].concat(b))}function p(a,b){var c=h.call(arguments,1);if(v){if(u===a)return;o()}var d=f.computeStackTrace(a);if(v=d,u=a,t=c,setTimeout(function(){u===a&&o()},d.incomplete?2e3:0),b!==!1)throw a}var q,r,s=[],t=null,u=null,v=null;return p.subscribe=a,p.unsubscribe=b,p.uninstall=c,p}(),f.computeStackTrace=function(){function a(a){if("undefined"!=typeof a.stack&&a.stack){for(var b,c,e,f=/^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|[a-z]:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,g=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,h=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx(?:-web)|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,j=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,k=/\((\S*)(?::(\d+))(?::(\d+))\)/,l=a.stack.split("\n"),m=[],n=(/^(.*) is undefined$/.exec(a.message),0),o=l.length;n<o;++n){if(c=f.exec(l[n])){var p=c[2]&&0===c[2].indexOf("native"),q=c[2]&&0===c[2].indexOf("eval");q&&(b=k.exec(c[2]))&&(c[2]=b[1],c[3]=b[2],c[4]=b[3]),e={url:p?null:c[2],func:c[1]||i,args:p?[c[2]]:[],line:c[3]?+c[3]:null,column:c[4]?+c[4]:null}}else if(c=h.exec(l[n]))e={url:c[2],func:c[1]||i,args:[],line:+c[3],column:c[4]?+c[4]:null};else{if(!(c=g.exec(l[n])))continue;var q=c[3]&&c[3].indexOf(" > eval")>-1;q&&(b=j.exec(c[3]))?(c[3]=b[1],c[4]=b[2],c[5]=null):0!==n||c[5]||"undefined"==typeof a.columnNumber||(m[0].column=a.columnNumber+1),e={url:c[3],func:c[1]||i,args:c[2]?c[2].split(","):[],line:c[4]?+c[4]:null,column:c[5]?+c[5]:null}}!e.func&&e.line&&(e.func=i),m.push(e)}return m.length?{name:a.name,message:a.message,url:d(),stack:m}:null}}function b(a,b,c,d){var e={url:b,line:c};if(e.url&&e.line){if(a.incomplete=!1,e.func||(e.func=i),a.stack.length>0&&a.stack[0].url===e.url){if(a.stack[0].line===e.line)return!1;if(!a.stack[0].line&&a.stack[0].func===e.func)return a.stack[0].line=e.line,!1}return a.stack.unshift(e),a.partial=!0,!0}return a.incomplete=!0,!1}function c(a,g){for(var h,j,k=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,l=[],m={},n=!1,o=c.caller;o&&!n;o=o.caller)if(o!==e&&o!==f.report){if(j={url:null,func:i,line:null,column:null},o.name?j.func=o.name:(h=k.exec(o.toString()))&&(j.func=h[1]),"undefined"==typeof j.func)try{j.func=h.input.substring(0,h.input.indexOf("{"))}catch(p){}m[""+o]?n=!0:m[""+o]=!0,l.push(j)}g&&l.splice(0,g);var q={name:a.name,message:a.message,url:d(),stack:l};return b(q,a.sourceURL||a.fileName,a.line||a.lineNumber,a.message||a.description),q}function e(b,e){var g=null;e=null==e?0:+e;try{if(g=a(b))return g}catch(h){if(f.debug)throw h}try{if(g=c(b,e+1))return g}catch(h){if(f.debug)throw h}return{name:b.name,message:b.message,url:d()}}return e.augmentStackTraceWithInitialElement=b,e.computeStackTraceFromStackProp=a,e}(),b.exports=f}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{5:5}],7:[function(a,b,c){function d(a,b){for(var c=0;c<a.length;++c)if(a[c]===b)return c;return-1}function e(a,b,c,d){return JSON.stringify(a,g(b,d),c)}function f(a){var b={stack:a.stack,message:a.message,name:a.name};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b}function g(a,b){var c=[],e=[];return null==b&&(b=function(a,b){return c[0]===b?"[Circular ~]":"[Circular ~."+e.slice(0,d(c,b)).join(".")+"]"}),function(g,h){if(c.length>0){var i=d(c,this);~i?c.splice(i+1):c.push(this),~i?e.splice(i,1/0,g):e.push(g),~d(c,h)&&(h=b.call(this,g,h))}else c.push(h);return null==a?h instanceof Error?f(h):h:a.call(this,g,h)}}c=b.exports=e,c.getSerialize=g},{}]},{},[4])(4)});
+//# sourceMappingURL=raven.min.js.map \ No newline at end of file