1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00
metamask-extension/app/scripts/inpage.js

77 lines
2.2 KiB
JavaScript
Raw Normal View History

2015-12-19 07:05:16 +01:00
const Web3 = require('web3')
const createPayload = require('web3-provider-engine/util/create-payload')
2015-12-19 07:05:16 +01:00
const StreamProvider = require('./lib/stream-provider.js')
const LocalMessageDuplexStream = require('./lib/local-message-stream.js')
2015-10-10 08:14:18 +02:00
2015-12-19 07:05:16 +01:00
// setup plugin communication
var pluginStream = new LocalMessageDuplexStream({
name: 'inpage',
target: 'contentscript',
})
var remoteProvider = new StreamProvider()
remoteProvider.pipe(pluginStream).pipe(remoteProvider)
2015-10-10 08:14:18 +02:00
2016-02-10 20:46:13 +01:00
pluginStream.on('error', console.error.bind(console))
remoteProvider.on('error', console.error.bind(console))
2016-01-31 08:15:38 +01:00
// handle synchronous methods remotely
// handle accounts cache
var accountsCache = []
2016-02-09 02:13:30 +01:00
setInterval(populateAccountsCache, 4000)
function populateAccountsCache(){
remoteProvider.sendAsync(createPayload({
method: 'eth_accounts',
params: [],
note: 'from metamask inpage provider',
}), function(err, response){
if (err) return console.error('MetaMask - Error polling accounts')
// update localStorage
var accounts = response.result
if (accounts.toString() !== accountsCache.toString()) {
accountsCache = accounts
localStorage['MetaMask-Accounts'] = JSON.stringify(accounts)
}
})
}
var syncProvider = new Web3.providers.HttpProvider('https://rawtestrpc.metamask.io/')
// var unsupportedMethods = ['eth_accounts']
remoteProvider.send = function(payload){
var result = null
switch (payload.method) {
case 'eth_accounts':
// read from localStorage
accountsCache = JSON.parse(localStorage['MetaMask-Accounts'] || '[]')
result = accountsCache
break
case 'eth_coinbase':
// read from localStorage
accountsCache = JSON.parse(localStorage['MetaMask-Accounts'] || '[]')
result = accountsCache[0] || '0x0000000000000000000000000000000000000000'
break
// fallback to normal rpc
default:
return syncProvider.send(payload)
}
// return the result
return {
id: payload.id,
jsonrpc: payload.jsonrpc,
result: result,
}
}
2016-01-31 08:15:38 +01:00
2015-12-19 07:05:16 +01:00
// create web3
var web3 = new Web3(remoteProvider)
2015-08-02 01:33:31 +02:00
window.web3 = web3
2016-01-31 08:15:38 +01:00
web3.setProvider = function(){
console.log('MetaMask Extension - overrode web3.setProvider')
}
console.log('MetaMask Extension - injected web3')