Skip to content

Commit

Permalink
Merge pull request #57 from DarkFlorist/fix-mew
Browse files Browse the repository at this point in the history
Fixes mew
  • Loading branch information
KillariDev committed Dec 16, 2022
2 parents 5110eac + 28ab999 commit c8a5cff
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 50 deletions.
59 changes: 42 additions & 17 deletions extension/app/inpage/output/injected_document_start.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,11 @@ window.interceptor = {
connected: false,
requestId: 0,
outstandingRequests: new Map(),
onMessageCallBack: (_message) => { },
onConnectCallBack: (_connectInfo) => { },
onAccountsChangedCallBack: (_accounts) => { },
onDisconnectCallBack: (_error) => { },
onChainChangedCallBack: (_chainId) => { },
onMessageCallBacks: new Set(),
onConnectCallBacks: new Set(),
onAccountsChangedCallBacks: new Set(),
onDisconnectCallBacks: new Set(),
onChainChangedCallBacks: new Set(),
};
function startListeningForMessages() {
async function requestAccounts() {
Expand Down Expand Up @@ -192,22 +192,22 @@ function startListeningForMessages() {
if (forwardRequest.result !== undefined) {
// if interceptor direclty sent us the result, just forward that to the dapp, otherwise ask the signer for the result
if (forwardRequest.subscription !== undefined) {
return window.interceptor.onMessageCallBack({ type: 'eth_subscription', data: forwardRequest.result });
return window.interceptor.onMessageCallBacks.forEach((f) => f({ type: 'eth_subscription', data: forwardRequest.result }));
}
if (forwardRequest.options.method === 'accountsChanged') {
return window.interceptor.onAccountsChangedCallBack(forwardRequest.result);
return window.interceptor.onAccountsChangedCallBacks.forEach((f) => f(forwardRequest.result));
}
if (forwardRequest.options.method === 'connect') {
window.interceptor.connected = true;
return window.interceptor.onConnectCallBack({ chainId: forwardRequest.result });
return window.interceptor.onConnectCallBacks.forEach((f) => f({ chainId: forwardRequest.result }));
}
if (forwardRequest.options.method === 'disconnect') {
window.interceptor.connected = false;
const resultArray = forwardRequest.result;
return window.interceptor.onDisconnectCallBack({ name: 'disconnect', ...resultArray });
return window.interceptor.onDisconnectCallBacks.forEach((f) => f({ name: 'disconnect', ...resultArray }));
}
if (forwardRequest.options.method === 'chainChanged') {
return window.interceptor.onChainChangedCallBack(forwardRequest.result);
return window.interceptor.onChainChangedCallBacks.forEach((f) => f(forwardRequest.result));
}
if (forwardRequest.options.method === 'request_signer_to_eth_requestAccounts') {
// when dapp requsts eth_requestAccounts, interceptor needs to reply to it, but we also need to try to sign to the signer
Expand Down Expand Up @@ -313,25 +313,47 @@ function injectEthereumIntoWindow() {
.catch(error => callback({ jsonrpc: '2.0', id: payload.id, error: { code: error.code, message: error.message, data: { ...error.data, stack: error.stack } } }, null));
};
const on = async (kind, callback) => {
console.log(\`set on: \${kind}\`);
switch (kind) {
case 'accountsChanged':
window.interceptor.onAccountsChangedCallBack = callback;
window.interceptor.onAccountsChangedCallBacks.add(callback);
return;
case 'message':
window.interceptor.onMessageCallBack = callback;
window.interceptor.onMessageCallBacks.add(callback);
return;
case 'connect':
window.interceptor.onConnectCallBack = callback;
window.interceptor.onConnectCallBacks.add(callback);
return;
case 'close': //close is deprecated on eip-1193 by disconnect but its still used by dapps (MyEtherWallet)
window.interceptor.onDisconnectCallBack = callback;
window.interceptor.onDisconnectCallBacks.add(callback);
return;
case 'disconnect':
window.interceptor.onDisconnectCallBack = callback;
window.interceptor.onDisconnectCallBacks.add(callback);
return;
case 'chainChanged':
window.interceptor.onChainChangedCallBack = callback;
window.interceptor.onChainChangedCallBacks.add(callback);
return;
default:
}
};
const removeListener = async (kind, callback) => {
switch (kind) {
case 'accountsChanged':
window.interceptor.onAccountsChangedCallBacks.delete(callback);
return;
case 'message':
window.interceptor.onMessageCallBacks.delete(callback);
return;
case 'connect':
window.interceptor.onConnectCallBacks.delete(callback);
return;
case 'close': //close is deprecated on eip-1193 by disconnect but its still used by dapps (MyEtherWallet)
window.interceptor.onDisconnectCallBacks.delete(callback);
return;
case 'disconnect':
window.interceptor.onDisconnectCallBacks.delete(callback);
return;
case 'chainChanged':
window.interceptor.onChainChangedCallBacks.delete(callback);
return;
default:
}
Expand All @@ -356,6 +378,7 @@ function injectEthereumIntoWindow() {
window.ethereum = {
request: request,
on: on,
removeListener: removeListener,
send: send,
sendAsync: sendAsync,
usingInterceptorWithoutSigner: true,
Expand All @@ -376,6 +399,7 @@ function injectEthereumIntoWindow() {
oldOn: window.ethereum.on,
request: request,
on: on,
removeListener: removeListener,
send: send,
sendAsync: sendAsync,
usingInterceptorWithoutSigner: false,
Expand All @@ -390,6 +414,7 @@ function injectEthereumIntoWindow() {
window.ethereum.oldOn = window.ethereum.on; // store the on object to access the signer later on
window.ethereum.request = request;
window.ethereum.on = on;
window.ethereum.removeListener = removeListener;
window.ethereum.send = send;
window.ethereum.sendAsync = sendAsync;
window.ethereum.usingInterceptorWithoutSigner = false;
Expand Down
89 changes: 61 additions & 28 deletions extension/app/inpage/ts/inpage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,16 +87,23 @@ interface ProviderMessage {
readonly data: unknown
}

type AnyCallBack = ((message: ProviderMessage) => void)
| ( (connectInfo: ProviderConnectInfo) => void )
| ( (accounts: string[]) => void )
| ( (error: ProviderRpcError) => void )
| ( (chainId: string) => void )

interface Window {
dispatchEvent: any,
ethereum?: {
request?: (options: { readonly method: string, readonly params?: unknown[] }) => Promise<unknown>,
send?: unknown,
sendAsync?: unknown,
on?: (kind: OnMessage, callback: any) => Promise<void>,
request: (options: { readonly method: string, readonly params?: unknown[] }) => Promise<unknown>,
send: unknown,
sendAsync: unknown,
on: (kind: OnMessage, callback: AnyCallBack) => Promise<void>,
removeListener: (kind: OnMessage, callback: AnyCallBack) => Promise<void>,
usingInterceptorWithoutSigner?: boolean, // are we using Interceptor as a wallet instead of an external signer
oldRequest?: (options: { readonly method: string, readonly params?: unknown[] }) => Promise<unknown>,
oldOn?: (kind: OnMessage, callback: any) => Promise<void>,
oldOn?: (kind: OnMessage, callback: AnyCallBack) => Promise<void>,
enable: () => void,
isBraveWallet?: boolean,
isMetaMask?: boolean,
Expand All @@ -107,11 +114,11 @@ interface Window {
connected: boolean,
requestId: number,
outstandingRequests: Map<number, InterceptorFuture<unknown> >,
onMessageCallBack: ((message: ProviderMessage) => void),
onConnectCallBack: ((connectInfo: ProviderConnectInfo) => void)
onAccountsChangedCallBack: ((accounts: string[]) => void),
onDisconnectCallBack: ((error: ProviderRpcError) => void),
onChainChangedCallBack: ((chainId: string) => void),
onMessageCallBacks: Set<((message: ProviderMessage) => void)>,
onConnectCallBacks: Set<((connectInfo: ProviderConnectInfo) => void)>
onAccountsChangedCallBacks: Set<((accounts: string[]) => void)>,
onDisconnectCallBacks: Set<((error: ProviderRpcError) => void)>,
onChainChangedCallBacks: Set<((chainId: string) => void)>,
}
}

Expand All @@ -120,11 +127,11 @@ window.interceptor = {
connected: false,
requestId: 0,
outstandingRequests: new Map(),
onMessageCallBack: (_message: ProviderMessage) => {},
onConnectCallBack: (_connectInfo: ProviderConnectInfo) => {},
onAccountsChangedCallBack: (_accounts: string[]) => {},
onDisconnectCallBack: (_error: ProviderRpcError) => {},
onChainChangedCallBack: (_chainId: string) => {},
onMessageCallBacks: new Set(),
onConnectCallBacks: new Set(),
onAccountsChangedCallBacks: new Set(),
onDisconnectCallBacks: new Set(),
onChainChangedCallBacks: new Set(),
}

type OnMessage = "accountsChanged" | "message" | "connect" | "error" | "close" | "disconnect" | "chainChanged"
Expand Down Expand Up @@ -218,22 +225,22 @@ function startListeningForMessages() {
if (forwardRequest.result !== undefined) {
// if interceptor direclty sent us the result, just forward that to the dapp, otherwise ask the signer for the result
if (forwardRequest.subscription !== undefined) {
return window.interceptor.onMessageCallBack( { type: 'eth_subscription', data: forwardRequest.result } )
return window.interceptor.onMessageCallBacks.forEach( (f) => f( { type: 'eth_subscription', data: forwardRequest.result } ))
}
if (forwardRequest.options.method === 'accountsChanged') {
return window.interceptor.onAccountsChangedCallBack( forwardRequest.result as string[] )
return window.interceptor.onAccountsChangedCallBacks.forEach( (f) => f( forwardRequest.result as string[] ) )
}
if (forwardRequest.options.method === 'connect') {
window.interceptor.connected = true
return window.interceptor.onConnectCallBack( { chainId: forwardRequest.result as string } )
return window.interceptor.onConnectCallBacks.forEach( (f) => f( { chainId: forwardRequest.result as string } ) )
}
if (forwardRequest.options.method === 'disconnect') {
window.interceptor.connected = false
const resultArray = forwardRequest.result as { code: number, message: string }
return window.interceptor.onDisconnectCallBack( { name: 'disconnect', ...resultArray } )
return window.interceptor.onDisconnectCallBacks.forEach( (f) => f( { name: 'disconnect', ...resultArray } ) )
}
if (forwardRequest.options.method === 'chainChanged') {
return window.interceptor.onChainChangedCallBack( forwardRequest.result as string )
return window.interceptor.onChainChangedCallBacks.forEach( (f) => f( forwardRequest.result as string ) )
}
if (forwardRequest.options.method === 'request_signer_to_eth_requestAccounts') {
// when dapp requsts eth_requestAccounts, interceptor needs to reply to it, but we also need to try to sign to the signer
Expand Down Expand Up @@ -330,26 +337,49 @@ function injectEthereumIntoWindow() {
.catch(error => callback({ jsonrpc: '2.0', id: payload.id, error: { code: error.code, message: error.message, data: { ...error.data, stack: error.stack } } }, null))
}

const on = async (kind: OnMessage, callback: any) => {
console.log(`set on: ${kind}`)
const on = async (kind: OnMessage, callback: AnyCallBack) => {
switch (kind) {
case 'accountsChanged':
window.interceptor.onAccountsChangedCallBacks.add( callback as (accounts: string[]) => void )
return
case 'message':
window.interceptor.onMessageCallBacks.add(callback as (message: ProviderMessage) => void)
return
case 'connect':
window.interceptor.onConnectCallBacks.add(callback as (connectInfo: ProviderConnectInfo) => void)
return
case 'close': //close is deprecated on eip-1193 by disconnect but its still used by dapps (MyEtherWallet)
window.interceptor.onDisconnectCallBacks.add(callback as (error: ProviderRpcError) => void)
return
case 'disconnect':
window.interceptor.onDisconnectCallBacks.add(callback as (error: ProviderRpcError) => void)
return
case 'chainChanged':
window.interceptor.onChainChangedCallBacks.add(callback as (chainId: string) => void)
return
default:
}
}

const removeListener = async (kind: OnMessage, callback: AnyCallBack) => {
switch (kind) {
case 'accountsChanged':
window.interceptor.onAccountsChangedCallBack = callback as (accounts: string[]) => void
window.interceptor.onAccountsChangedCallBacks.delete(callback as (accounts: string[]) => void)
return
case 'message':
window.interceptor.onMessageCallBack = callback as (message: ProviderMessage) => void
window.interceptor.onMessageCallBacks.delete(callback as (message: ProviderMessage) => void)
return
case 'connect':
window.interceptor.onConnectCallBack = callback as (connectInfo: ProviderConnectInfo) => void
window.interceptor.onConnectCallBacks.delete(callback as (connectInfo: ProviderConnectInfo) => void)
return
case 'close': //close is deprecated on eip-1193 by disconnect but its still used by dapps (MyEtherWallet)
window.interceptor.onDisconnectCallBack = callback as (error: ProviderRpcError) => void
window.interceptor.onDisconnectCallBacks.delete(callback as (error: ProviderRpcError) => void)
return
case 'disconnect':
window.interceptor.onDisconnectCallBack = callback as (error: ProviderRpcError) => void
window.interceptor.onDisconnectCallBacks.delete(callback as (error: ProviderRpcError) => void)
return
case 'chainChanged':
window.interceptor.onChainChangedCallBack = callback as (chainId: string) => void
window.interceptor.onChainChangedCallBacks.delete(callback as (chainId: string) => void)
return
default:
}
Expand All @@ -376,6 +406,7 @@ function injectEthereumIntoWindow() {
window.ethereum = {
request: request,
on: on,
removeListener: removeListener,
send: send,
sendAsync: sendAsync,
usingInterceptorWithoutSigner: true,
Expand All @@ -397,6 +428,7 @@ function injectEthereumIntoWindow() {
oldOn: window.ethereum.on, // store the on object to access Brave Wallet later on
request: request,
on: on,
removeListener: removeListener,
send: send,
sendAsync: sendAsync,
usingInterceptorWithoutSigner: false,
Expand All @@ -410,6 +442,7 @@ function injectEthereumIntoWindow() {
window.ethereum.oldOn = window.ethereum.on // store the on object to access the signer later on
window.ethereum.request = request
window.ethereum.on = on
window.ethereum.removeListener = removeListener
window.ethereum.send = send
window.ethereum.sendAsync = sendAsync
window.ethereum.usingInterceptorWithoutSigner = false
Expand Down
6 changes: 3 additions & 3 deletions extension/app/ts/background/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import 'webextension-polyfill'
import { Simulator } from '../simulation/simulator.js'
import { EIP2612Message, EthereumAddress, EthereumQuantity, EthereumUnsignedTransaction } from '../utils/wire-types.js'
import { getSettings, saveActiveChain, saveActiveSigningAddress, saveActiveSimulationAddress, Settings } from './settings.js'
import { blockNumber, call, chainId, estimateGas, gasPrice, getAccounts, getBalance, getBlockByNumber, getCode, getPermissions, getTransactionByHash, getTransactionReceipt, personalSign, requestPermissions, sendRawTransaction, sendTransaction, signTypedDataV4, subscribe, switchEthereumChain, unsubscribe } from './simulationModeHanders.js'
import { blockNumber, call, chainId, estimateGas, gasPrice, getAccounts, getBalance, getBlockByNumber, getCode, getPermissions, getTransactionByHash, getTransactionCount, getTransactionReceipt, personalSign, requestPermissions, sendRawTransaction, sendTransaction, signTypedDataV4, subscribe, switchEthereumChain, unsubscribe } from './simulationModeHanders.js'
import { changeActiveAddress, changeAddressInfos, changeMakeMeRich, changePage, resetSimulation, confirmDialog, RefreshSimulation, removeTransaction, requestAccountsFromSigner, refreshPopupConfirmTransactionSimulation, confirmPersonalSign, confirmRequestAccess, changeInterceptorAccess, changeChainDialog, popupChangeActiveChain, enableSimulationMode, reviewNotification, rejectNotification } from './popupMessageHandlers.js'
import { AddressMetadata, SimResults, SimulationState, TokenPriceEstimate } from '../utils/visualizer-types.js'
import { WebsiteApproval, SignerState } from '../utils/user-interface-types.js'
Expand Down Expand Up @@ -289,12 +289,12 @@ export const handlers = new Map<string, SimulationHandler >([
['eth_accounts', getAccounts.bind(undefined, getActiveAddressForDomain)],
['eth_requestAccounts', getAccounts.bind(undefined, getActiveAddressForDomain)],
['eth_sendRawTransaction', sendRawTransaction],
['eth_gasPrice', gasPrice]
['eth_gasPrice', gasPrice],
['eth_getTransactionCount', getTransactionCount],

/*
Missing methods:
['eth_getProof', ],
['eth_getTransactionCount', ],
['eth_getBlockTransactionCountByNumber', ],
['eth_getTransactionByBlockHashAndIndex', ],
['eth_getTransactionByBlockNumberAndIndex', ],
Expand Down
22 changes: 20 additions & 2 deletions extension/app/ts/background/simulationModeHanders.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Simulator } from '../simulation/simulator.js'
import { bytes32String } from '../utils/bigint.js'
import { InterceptedRequest } from '../utils/interceptor-messages.js'
import { EstimateGasParams, EthBalanceParams, EthBlockByNumberParams, EthCallParams, EthereumAddress, EthereumData, EthereumQuantity, EthereumSignedTransactionWithBlockData, EthSubscribeParams, EthTransactionReceiptResponse, EthUnSubscribeParams, GetBlockReturn, GetCode, JsonRpcNewHeadsNotification, NewHeadsSubscriptionData, PersonalSignParams, RequestPermissions, SendTransactionParams, SignTypedDataV4Params, SwitchEthereumChainParams, TransactionByHashParams, TransactionReceiptParams } from '../utils/wire-types.js'
import { EstimateGasParams, EthBalanceParams, EthBlockByNumberParams, EthCallParams, EthereumAddress, EthereumData, EthereumQuantity, EthereumSignedTransactionWithBlockData, EthSubscribeParams, EthTransactionReceiptResponse, EthUnSubscribeParams, GetBlockReturn, GetCode, GetTransactionCount, JsonRpcNewHeadsNotification, NewHeadsSubscriptionData, PersonalSignParams, RequestPermissions, SendTransactionParams, SignTypedDataV4Params, SwitchEthereumChainParams, TransactionByHashParams, TransactionReceiptParams } from '../utils/wire-types.js'
import { postMessageIfStillConnected } from './background.js'
import { WebsiteAccess } from './settings.js'
import { openChangeChainDialog } from './windows/changeChain.js'
Expand Down Expand Up @@ -221,8 +221,16 @@ export async function signTypedDataV4(_simulator: Simulator, port: browser.runti

}

export async function switchEthereumChain(_simulator: Simulator, port: browser.runtime.Port, request: InterceptedRequest) {
export async function switchEthereumChain(simulator: Simulator, port: browser.runtime.Port, request: InterceptedRequest) {
const params = SwitchEthereumChainParams.parse(request.options)
if (await simulator.ethereum.getChainId() === params.params[0].chainId) {
return postMessageIfStillConnected(port, {
interceptorApproved: true,
requestId: request.requestId,
options: request.options,
result: []
})
}
return openChangeChainDialog(port, request, params.params[0].chainId)
}

Expand Down Expand Up @@ -250,3 +258,13 @@ export async function getPermissions(_simulator: Simulator, port: browser.runtim
result: [ { "eth_accounts": {} } ]
})
}

export async function getTransactionCount(simulator: Simulator, port: browser.runtime.Port, request: InterceptedRequest) {
const params = GetTransactionCount.parse(request.options)
return postMessageIfStillConnected(port, {
interceptorApproved: true,
requestId: request.requestId,
options: request.options,
result: EthereumQuantity.serialize(await simulator.ethereum.getTransactionCount(params.params[0], params.params[1]))
})
}
Loading

0 comments on commit c8a5cff

Please sign in to comment.