Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent accidental use of globals #8340

Merged
merged 1 commit into from
Apr 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ module.exports = {
'plugin:react/recommended',
],

env: {
'browser': true,
},

plugins: [
'babel',
'react',
Expand All @@ -37,9 +33,10 @@ module.exports = {
],

globals: {
'web3': true,
'$': false,
'QUnit': false,
'$': 'readonly',
document: 'readonly',
QUnit: 'readonly',
window: 'readonly',
},

rules: {
Expand Down
2 changes: 1 addition & 1 deletion app/scripts/controllers/infura.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class InfuraController {
// Responsible for retrieving the status of Infura's nodes. Can return either
// ok, degraded, or down.
async checkInfuraNetworkStatus () {
const response = await fetch('https://api.infura.io/v1/status/metamask')
const response = await window.fetch('https://api.infura.io/v1/status/metamask')
const parsedResponse = await response.json()
this.store.updateState({
infuraNetworkStatus: parsedResponse,
Expand Down
2 changes: 1 addition & 1 deletion app/scripts/controllers/token-rates.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class TokenRatesController {
const query = `contract_addresses=${pairs}&vs_currencies=${nativeCurrency}`
if (this._tokens.length > 0) {
try {
const response = await fetch(`https://api.coingecko.com/api/v3/simple/token_price/ethereum?${query}`)
const response = await window.fetch(`https://api.coingecko.com/api/v3/simple/token_price/ethereum?${query}`)
const prices = await response.json()
this._tokens.forEach((token) => {
const price = prices[token.address.toLowerCase()] || prices[ethUtil.toChecksumAddress(token.address)]
Expand Down
2 changes: 1 addition & 1 deletion app/scripts/lib/ens-ipfs/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function setupEnsIpfsResolver ({ provider, getCurrentNetwork, getIpfsGateway })
const resolvedUrl = `https://${hash}.${ipfsGateway}${path}${search || ''}${fragment || ''}`
try {
// check if ipfs gateway has result
const response = await fetch(resolvedUrl, { method: 'HEAD' })
const response = await window.fetch(resolvedUrl, { method: 'HEAD' })
if (response.status === 200) {
url = resolvedUrl
}
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/lib/fetch-with-timeout.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const fetchWithTimeout = ({ timeout = 120000 } = {}) => {
return async function _fetch (url, opts) {
const abortController = new AbortController()
const abortController = new window.AbortController()
const abortSignal = abortController.signal
const f = fetch(url, {
const f = window.fetch(url, {
...opts,
signal: abortSignal,
})
Expand Down
2 changes: 1 addition & 1 deletion app/scripts/lib/network-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class ReadOnlyNetworkStore {
*/
async _init () {
try {
const response = await fetch(FIXTURE_SERVER_URL)
const response = await window.fetch(FIXTURE_SERVER_URL)
if (response.ok) {
this._state = await response.json()
}
Expand Down
6 changes: 3 additions & 3 deletions app/scripts/lib/setupFetchDebugging.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ export default setupFetchDebugging
//

function setupFetchDebugging () {
if (!global.fetch) {
if (!window.fetch) {
return
}
const originalFetch = global.fetch
const originalFetch = window.fetch

global.fetch = wrappedFetch
window.fetch = wrappedFetch

async function wrappedFetch (...args) {
const initialStack = getCurrentStack()
Expand Down
2 changes: 1 addition & 1 deletion app/scripts/lib/setupSentry.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ function rewriteReportUrls (report) {
}

function toMetamaskUrl (origUrl) {
const filePath = origUrl.split(location.origin)[1]
const filePath = origUrl.split(window.location.origin)[1]
if (!filePath) {
return origUrl
}
Expand Down
2 changes: 1 addition & 1 deletion app/scripts/lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const getEnvironmentType = (url = window.location.href) => {
*
*/
const getPlatform = (_) => {
const ua = navigator.userAgent
const ua = window.navigator.userAgent
if (ua.search('Firefox') !== -1) {
return PLATFORM_FIREFOX
} else {
Expand Down
4 changes: 2 additions & 2 deletions development/mock-3box.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ function delay (time) {
}

async function loadFromMock3Box (key) {
const res = await fetch('http://localhost:8889?key=' + key)
const res = await window.fetch('http://localhost:8889?key=' + key)
const text = await res.text()
return text.length ? JSON.parse(text) : null
}

async function saveToMock3Box (key, newDataAtKey) {
const res = await fetch('http://localhost:8889', {
const res = await window.fetch('http://localhost:8889', {
method: 'POST',
body: JSON.stringify({
key,
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,6 @@
"gulp-watch": "^5.0.1",
"gulp-zip": "^4.0.0",
"jsdom": "^11.2.0",
"jsdom-global": "^3.0.2",
"karma": "^4.1.0",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^1.0.1",
Expand Down
2 changes: 1 addition & 1 deletion test/e2e/contract-test/contract.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*global ethereum, MetamaskOnboarding */
/*global ethereum, MetamaskOnboarding, web3 */

/*
The `piggybankContract` is compiled from:
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/webdriver/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,11 +192,11 @@ function collectMetrics () {
navigation: [],
}

performance.getEntriesByType('paint').forEach((paintEntry) => {
window.performance.getEntriesByType('paint').forEach((paintEntry) => {
results.paint[paintEntry.name] = paintEntry.startTime
})

performance.getEntriesByType('navigation').forEach((navigationEntry) => {
window.performance.getEntriesByType('navigation').forEach((navigationEntry) => {
results.navigation.push({
domContentLoaded: navigationEntry.domContentLoadedEventEnd,
load: navigationEntry.loadEventEnd,
Expand Down
32 changes: 24 additions & 8 deletions test/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ Enzyme.configure({ adapter: new Adapter() })

// ganache server
const server = Ganache.server()
server.listen(8545, () => {})
server.listen(8545)

server.on('error', console.error)
server.on('clientError', console.error)

log.setDefaultLevel(5)
global.log = log
Expand All @@ -41,17 +44,30 @@ global.log = log
// polyfills
//

// dom
const { JSDOM } = require('jsdom')

const jsdom = new JSDOM()
global.window = jsdom.window

// required by `trezor-connect/node_modules/whatwg-fetch`
global.self = window
// required by `dom-helpers` and various other libraries
global.document = window.document
// required by `react-tippy`
global.navigator = window.navigator
global.Element = window.Element

// delete AbortController added by jsdom so it can be polyfilled correctly below
delete window.AbortController

// fetch
const fetch = require('node-fetch')

global.fetch = fetch
global.Response = fetch.Response
global.Headers = fetch.Headers
global.Request = fetch.Request
require('abortcontroller-polyfill/dist/polyfill-patch-fetch')
const { Headers, Request, Response } = fetch
Object.assign(window, { fetch, Headers, Request, Response })

// dom
require('jsdom-global')()
require('abortcontroller-polyfill/dist/polyfill-patch-fetch')

// localStorage
window.localStorage = {}
Expand Down
2 changes: 1 addition & 1 deletion test/integration/lib/confirm-sig-requests.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async function runConfirmSigRequestsTest (assert) {
reactTriggerChange(selectState[0])

const realFetch = window.fetch.bind(window)
global.fetch = (...args) => {
window.fetch = (...args) => {
if (args[0] === 'https://ethgasstation.info/json/ethgasAPI.json') {
return Promise.resolve({ json: () => Promise.resolve(JSON.parse(fetchMockResponses.ethGasBasic)) })
} else if (args[0] === 'https://ethgasstation.info/json/predictTable.json') {
Expand Down
2 changes: 1 addition & 1 deletion test/integration/lib/currency-localization.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async function runCurrencyLocalizationTest (assert) {
selectState.val('currency localization')

const realFetch = window.fetch.bind(window)
global.fetch = (...args) => {
window.fetch = (...args) => {
if (args[0] === 'https://ethgasstation.info/json/ethgasAPI.json') {
return Promise.resolve({ json: () => Promise.resolve(JSON.parse(fetchMockResponses.ethGasBasic)) })
} else if (args[0] === 'https://ethgasstation.info/json/predictTable.json') {
Expand Down
2 changes: 1 addition & 1 deletion test/integration/lib/tx-list-items.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ async function runTxListItemsTest (assert) {
reactTriggerChange(selectState[0])

const realFetch = window.fetch.bind(window)
global.fetch = (...args) => {
window.fetch = (...args) => {
if (args[0] === 'https://ethgasstation.info/json/ethgasAPI.json') {
return Promise.resolve({ json: () => Promise.resolve(JSON.parse(fetchMockResponses.ethGasBasic)) })
} else if (args[0] === 'https://ethgasstation.info/json/predictTable.json') {
Expand Down
6 changes: 0 additions & 6 deletions test/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,4 @@ require('@babel/register')({
require('./helper')

window.SVGPathElement = window.SVGPathElement || { prototype: {} }
window.fetch = window.fetch || function fetch () {
return Promise.resolve()
}
global.indexedDB = {}
global.fetch = global.fetch || function fetch () {
return Promise.resolve()
}
6 changes: 3 additions & 3 deletions test/unit/app/controllers/incoming-transactions-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,12 +314,12 @@ describe('IncomingTransactionsController', function () {
}))
let tempFetch
beforeEach(function () {
tempFetch = global.fetch
global.fetch = mockFetch
tempFetch = window.fetch
window.fetch = mockFetch
})

afterEach(function () {
global.fetch = tempFetch
window.fetch = tempFetch
mockFetch.resetHistory()
})

Expand Down
4 changes: 2 additions & 2 deletions test/unit/ui/app/actions.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1432,15 +1432,15 @@ describe('Actions', function () {
let setCurrentLocaleSpy

beforeEach(function () {
sinon.stub(global, 'fetch')
sinon.stub(window, 'fetch')
.resolves({
json: async () => enLocale,
})
})

afterEach(function () {
setCurrentLocaleSpy.restore()
global.fetch.restore()
window.fetch.restore()
})

it('calls expected actions', async function () {
Expand Down
22 changes: 11 additions & 11 deletions ui/app/ducks/gas/gas-duck.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,19 +76,19 @@ describe('Gas Duck', function () {
})

beforeEach(function () {
tempFetch = global.fetch
tempFetch = window.fetch
tempDateNow = global.Date.now

fakeLocalStorage.loadLocalStorageData = sinon.stub()
fakeLocalStorage.saveLocalStorageData = sinon.spy()
global.fetch = sinon.stub().callsFake(fakeFetch)
window.fetch = sinon.stub().callsFake(fakeFetch)
global.Date.now = () => 2000000
})

afterEach(function () {
sinon.restore()

global.fetch = tempFetch
window.fetch = tempFetch
global.Date.now = tempDateNow
})

Expand Down Expand Up @@ -291,7 +291,7 @@ describe('Gas Duck', function () {
[{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ]
)
assert.deepEqual(
global.fetch.getCall(0).args,
window.fetch.getCall(0).args,
[
'https://ethgasstation.info/json/ethgasAPI.json',
{
Expand Down Expand Up @@ -353,7 +353,7 @@ describe('Gas Duck', function () {
mockDistpatch.getCall(0).args,
[{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ]
)
assert.ok(global.fetch.notCalled)
assert.ok(window.fetch.notCalled)
assert.deepEqual(
mockDistpatch.getCall(1).args,
[{
Expand Down Expand Up @@ -390,7 +390,7 @@ describe('Gas Duck', function () {
[{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ]
)
assert.deepEqual(
global.fetch.getCall(0).args,
window.fetch.getCall(0).args,
[
'https://ethgasstation.info/json/ethgasAPI.json',
{
Expand Down Expand Up @@ -444,7 +444,7 @@ describe('Gas Duck', function () {
[{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ]
)
assert.deepEqual(
global.fetch.getCall(0).args,
window.fetch.getCall(0).args,
[
'https://ethgasstation.info/json/ethgasAPI.json',
{
Expand Down Expand Up @@ -520,7 +520,7 @@ describe('Gas Duck', function () {
mockDistpatch.getCall(0).args,
[{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ]
)
assert.ok(global.fetch.notCalled)
assert.ok(window.fetch.notCalled)

assert.deepEqual(
mockDistpatch.getCall(1).args,
Expand Down Expand Up @@ -565,7 +565,7 @@ describe('Gas Duck', function () {
[{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ]
)
assert.deepEqual(
global.fetch.getCall(0).args,
window.fetch.getCall(0).args,
[
'https://ethgasstation.info/json/ethgasAPI.json',
{
Expand Down Expand Up @@ -626,7 +626,7 @@ describe('Gas Duck', function () {
[{ type: GAS_ESTIMATE_LOADING_STARTED } ]
)
assert.deepEqual(
global.fetch.getCall(0).args,
window.fetch.getCall(0).args,
[
'https://ethgasstation.info/json/predictTable.json',
{
Expand Down Expand Up @@ -679,7 +679,7 @@ describe('Gas Duck', function () {
mockDistpatch.getCall(0).args,
[{ type: GAS_ESTIMATE_LOADING_STARTED } ]
)
assert.equal(global.fetch.callCount, 0)
assert.equal(window.fetch.callCount, 0)

assert.deepEqual(
mockDistpatch.getCall(1).args,
Expand Down
6 changes: 3 additions & 3 deletions ui/app/ducks/gas/gas.duck.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ export function fetchBasicGasEstimates () {
}

async function fetchExternalBasicGasEstimates (dispatch) {
const response = await fetch('https://ethgasstation.info/json/ethgasAPI.json', {
const response = await window.fetch('https://ethgasstation.info/json/ethgasAPI.json', {
'headers': {},
'referrer': 'http://ethgasstation.info/json/',
'referrerPolicy': 'no-referrer-when-downgrade',
Expand Down Expand Up @@ -259,7 +259,7 @@ export function fetchBasicGasAndTimeEstimates () {
}

async function fetchExternalBasicGasAndTimeEstimates (dispatch) {
const response = await fetch('https://ethgasstation.info/json/ethgasAPI.json', {
const response = await window.fetch('https://ethgasstation.info/json/ethgasAPI.json', {
'headers': {},
'referrer': 'http://ethgasstation.info/json/',
'referrerPolicy': 'no-referrer-when-downgrade',
Expand Down Expand Up @@ -377,7 +377,7 @@ export function fetchGasEstimates (blockTime) {
dispatch(gasEstimatesLoadingStarted())

const promiseToFetch = Date.now() - timeLastRetrieved > 75000
? fetch('https://ethgasstation.info/json/predictTable.json', {
? window.fetch('https://ethgasstation.info/json/predictTable.json', {
'headers': {},
'referrer': 'http://ethgasstation.info/json/',
'referrerPolicy': 'no-referrer-when-downgrade',
Expand Down
Loading