@cowprotocol/iframe-transport 2.0.8 → 2.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/package.json +25 -3
- package/src/IframeTransport.d.ts +11 -0
- package/src/IframeTransport.js +42 -0
- package/src/IframeTransport.js.map +1 -0
- package/src/iframeRpcProvider/IframeRpcProviderBridge.d.ts +45 -0
- package/src/iframeRpcProvider/IframeRpcProviderBridge.js +143 -0
- package/src/iframeRpcProvider/IframeRpcProviderBridge.js.map +1 -0
- package/src/iframeRpcProvider/WidgetEthereumProvider.d.ts +134 -0
- package/src/iframeRpcProvider/WidgetEthereumProvider.js +300 -0
- package/src/iframeRpcProvider/WidgetEthereumProvider.js.map +1 -0
- package/src/iframeRpcProvider/iframeRpcProviderEvents.d.ts +31 -0
- package/src/iframeRpcProvider/iframeRpcProviderEvents.js +11 -0
- package/src/iframeRpcProvider/iframeRpcProviderEvents.js.map +1 -0
- package/src/iframeRpcProvider/utils.d.ts +4 -0
- package/src/iframeRpcProvider/utils.js +11 -0
- package/src/iframeRpcProvider/utils.js.map +1 -0
- package/src/index.d.ts +5 -0
- package/src/index.js +6 -0
- package/src/index.js.map +1 -0
- package/src/types.d.ts +59 -0
- package/src/types.js +2 -0
- package/src/types.js.map +1 -0
- package/.babelrc +0 -20
- package/jest.config.ts +0 -11
- package/project.json +0 -42
- package/src/IframeTransport.ts +0 -73
- package/src/iframeRpcProvider/IframeRpcProviderBridge.ts +0 -192
- package/src/iframeRpcProvider/WidgetEthereumProvider.ts +0 -489
- package/src/iframeRpcProvider/iframeRpcProviderEvents.ts +0 -40
- package/src/iframeRpcProvider/utils.ts +0 -18
- package/src/index.ts +0 -5
- package/src/types.ts +0 -75
- package/tsconfig.json +0 -21
- package/tsconfig.lib.json +0 -10
- package/tsconfig.spec.json +0 -20
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import type { EIP6963AnnounceProviderEvent, EIP6963ProviderDetail } from '@cowprotocol/types'
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
IframeRpcProviderEvents,
|
|
5
|
-
iframeRpcProviderTransport,
|
|
6
|
-
ProviderRpcRequestPayload,
|
|
7
|
-
ProviderRpcResponsePayload,
|
|
8
|
-
} from './iframeRpcProviderEvents'
|
|
9
|
-
import { getEip6963ProviderInfo, getProviderWcMetadata } from './utils'
|
|
10
|
-
|
|
11
|
-
import type { EthereumProvider, JsonRpcRequestMessage } from '../types'
|
|
12
|
-
|
|
13
|
-
const EVENTS_TO_FORWARD_TO_IFRAME = ['connect', 'disconnect', 'close', 'chainChanged', 'accountsChanged']
|
|
14
|
-
const eip6963Providers: EIP6963ProviderDetail[] = []
|
|
15
|
-
|
|
16
|
-
if (typeof window !== 'undefined') {
|
|
17
|
-
window.addEventListener('eip6963:announceProvider', (event: Event) => {
|
|
18
|
-
const providerEvent = event as EIP6963AnnounceProviderEvent
|
|
19
|
-
eip6963Providers.push(providerEvent.detail)
|
|
20
|
-
})
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Handles JSON-RPC request coming from an iFrame by delegating to a given Ethereum provider.
|
|
25
|
-
* The result will be passed back to the iFrame.
|
|
26
|
-
*
|
|
27
|
-
* Additionally, it will forward some special events from the wallet, to the iFrame window, for example connect/disconnect/chainChanged
|
|
28
|
-
*/
|
|
29
|
-
export class IframeRpcProviderBridge {
|
|
30
|
-
/**
|
|
31
|
-
* The Ethereum provider instance.
|
|
32
|
-
* When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
|
|
33
|
-
* */
|
|
34
|
-
private ethereumProvider: EthereumProvider | null = null
|
|
35
|
-
|
|
36
|
-
/** Stored JSON-RPC requests, to queue them when disconnected. */
|
|
37
|
-
private requestWaitingForConnection: { [key: string]: JsonRpcRequestMessage } = {}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Creates an instance of IframeRpcProviderBridge.
|
|
41
|
-
* @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
|
|
42
|
-
* Also it will receive some special RPC events coming from the wallet, like connect/chainChanged,accountChanged
|
|
43
|
-
*/
|
|
44
|
-
constructor(private iframeWidow: Window) {}
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Disconnects the JSON-RPC bridge from the Ethereum provider.
|
|
48
|
-
*/
|
|
49
|
-
disconnect(): void {
|
|
50
|
-
if (typeof window === 'undefined') return
|
|
51
|
-
|
|
52
|
-
// Disconnect provider
|
|
53
|
-
this.ethereumProvider = null
|
|
54
|
-
iframeRpcProviderTransport.stopListeningToMessageFromWindow(
|
|
55
|
-
window,
|
|
56
|
-
IframeRpcProviderEvents.PROVIDER_RPC_REQUEST,
|
|
57
|
-
this.processRpcCallFromWindow,
|
|
58
|
-
)
|
|
59
|
-
|
|
60
|
-
iframeRpcProviderTransport.stopListeningToMessageFromWindow(
|
|
61
|
-
window,
|
|
62
|
-
IframeRpcProviderEvents.REQUEST_PROVIDER_META_INFO,
|
|
63
|
-
this.processProviderMetaInfoRequest,
|
|
64
|
-
)
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Handles the 'connect' event and sets up event listeners for Ethereum provider events.
|
|
69
|
-
* @param newProvider - The Ethereum provider to connect.
|
|
70
|
-
*/
|
|
71
|
-
onConnect(newProvider: EthereumProvider): void {
|
|
72
|
-
if (typeof window === 'undefined') return
|
|
73
|
-
|
|
74
|
-
// Disconnect the previous provider
|
|
75
|
-
if (this.ethereumProvider) {
|
|
76
|
-
this.disconnect()
|
|
77
|
-
} else {
|
|
78
|
-
// Listen for messages coming to the main window (from the iFrame window)
|
|
79
|
-
iframeRpcProviderTransport.listenToMessageFromWindow(
|
|
80
|
-
window,
|
|
81
|
-
IframeRpcProviderEvents.PROVIDER_RPC_REQUEST,
|
|
82
|
-
this.processRpcCallFromWindow,
|
|
83
|
-
)
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// Save the provider
|
|
87
|
-
this.ethereumProvider = newProvider
|
|
88
|
-
|
|
89
|
-
// Process pending requests
|
|
90
|
-
this.processPendingRequests()
|
|
91
|
-
|
|
92
|
-
// Register in the provider, the events that needs to be forwarded to the iFrame window
|
|
93
|
-
EVENTS_TO_FORWARD_TO_IFRAME.forEach((event) => {
|
|
94
|
-
newProvider.on(event, (params: unknown) => this.onProviderEvent(event, params))
|
|
95
|
-
})
|
|
96
|
-
|
|
97
|
-
// Listen for provider meta info request
|
|
98
|
-
iframeRpcProviderTransport.listenToMessageFromWindow(
|
|
99
|
-
window,
|
|
100
|
-
IframeRpcProviderEvents.REQUEST_PROVIDER_META_INFO,
|
|
101
|
-
this.processProviderMetaInfoRequest,
|
|
102
|
-
)
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// TODO: Add proper return type annotation
|
|
106
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
107
|
-
private processPendingRequests() {
|
|
108
|
-
// Process pending requests
|
|
109
|
-
Object.keys(this.requestWaitingForConnection).forEach((key) => {
|
|
110
|
-
this.processRpcRequest(this.requestWaitingForConnection[key])
|
|
111
|
-
})
|
|
112
|
-
|
|
113
|
-
// Clear pending requests
|
|
114
|
-
this.requestWaitingForConnection = {}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Processes a JSON-RPC request and sends appropriate response or error via the content window.
|
|
119
|
-
* @param request - The JSON-RPC request to be processed.
|
|
120
|
-
*/
|
|
121
|
-
// TODO: Add proper return type annotation
|
|
122
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
123
|
-
processRpcRequest(request: JsonRpcRequestMessage) {
|
|
124
|
-
const { id, jsonrpc, method } = request
|
|
125
|
-
if (!this.ethereumProvider || !id) {
|
|
126
|
-
return
|
|
127
|
-
}
|
|
128
|
-
const requestPromise =
|
|
129
|
-
// Keep the legacy "enable" method for backward compatibility
|
|
130
|
-
method === 'enable'
|
|
131
|
-
? this.ethereumProvider.request({ method: 'eth_requestAccounts', id })
|
|
132
|
-
: this.ethereumProvider.request({ ...request, id })
|
|
133
|
-
|
|
134
|
-
// Do request, and forward the result or error to the iFrame window
|
|
135
|
-
requestPromise
|
|
136
|
-
.then((result) =>
|
|
137
|
-
this.forwardRpcResponseToIframe({
|
|
138
|
-
rpcResponse: { jsonrpc, id, result },
|
|
139
|
-
}),
|
|
140
|
-
)
|
|
141
|
-
.catch((error) =>
|
|
142
|
-
this.forwardRpcResponseToIframe({
|
|
143
|
-
rpcResponse: { jsonrpc, id, error },
|
|
144
|
-
}),
|
|
145
|
-
)
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
private processRpcCallFromWindow = ({ rpcRequest }: ProviderRpcRequestPayload): void => {
|
|
149
|
-
// If disconnected, ignore the message. Also persist the request
|
|
150
|
-
if (!this.ethereumProvider) {
|
|
151
|
-
if (rpcRequest.id) {
|
|
152
|
-
this.requestWaitingForConnection[rpcRequest.id] = rpcRequest
|
|
153
|
-
}
|
|
154
|
-
return
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
this.processRpcRequest(rpcRequest)
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
private processProviderMetaInfoRequest = (): void => {
|
|
161
|
-
if (!this.ethereumProvider) return
|
|
162
|
-
// We assume, that all EIP-6963 providers are already announced
|
|
163
|
-
const providerEip6963Info = getEip6963ProviderInfo(this.ethereumProvider, eip6963Providers)
|
|
164
|
-
const providerWcMetadata = getProviderWcMetadata(this.ethereumProvider)
|
|
165
|
-
|
|
166
|
-
// Send the provider meta info to the iFrame window
|
|
167
|
-
iframeRpcProviderTransport.postMessageToWindow(this.iframeWidow, IframeRpcProviderEvents.SEND_PROVIDER_META_INFO, {
|
|
168
|
-
providerEip6963Info,
|
|
169
|
-
providerWcMetadata,
|
|
170
|
-
})
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
private onProviderEvent(event: string, params: unknown): void {
|
|
174
|
-
iframeRpcProviderTransport.postMessageToWindow(this.iframeWidow, IframeRpcProviderEvents.PROVIDER_ON_EVENT, {
|
|
175
|
-
event,
|
|
176
|
-
params,
|
|
177
|
-
})
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Forward a JSON-RPC message to the content window.
|
|
182
|
-
*/
|
|
183
|
-
// TODO: Add proper return type annotation
|
|
184
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
185
|
-
private forwardRpcResponseToIframe(params: ProviderRpcResponsePayload) {
|
|
186
|
-
iframeRpcProviderTransport.postMessageToWindow(
|
|
187
|
-
this.iframeWidow,
|
|
188
|
-
IframeRpcProviderEvents.PROVIDER_RPC_RESPONSE,
|
|
189
|
-
params,
|
|
190
|
-
)
|
|
191
|
-
}
|
|
192
|
-
}
|
|
@@ -1,489 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ===========================================================================
|
|
3
|
-
* This is a modified version of the original iframe-provider library.
|
|
4
|
-
*
|
|
5
|
-
* The original had some deprecated methods and events, and it was hard to debug for the format used in the messages.
|
|
6
|
-
* This modified version makes use of the Widget library typed subscriptions
|
|
7
|
-
*
|
|
8
|
-
* https://github.com/ethvault/iframe-provider/blob/master/src/index.ts
|
|
9
|
-
*
|
|
10
|
-
* ===========================================================================
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import { EventEmitter } from 'eventemitter3'
|
|
14
|
-
|
|
15
|
-
import {
|
|
16
|
-
IframeRpcProviderEvents,
|
|
17
|
-
iframeRpcProviderTransport,
|
|
18
|
-
ProviderMetaInfoPayload,
|
|
19
|
-
ProviderOnEventPayload,
|
|
20
|
-
ProviderRpcResponsePayload,
|
|
21
|
-
} from './iframeRpcProviderEvents'
|
|
22
|
-
|
|
23
|
-
import {
|
|
24
|
-
JsonRpcErrorResponseMessage,
|
|
25
|
-
JsonRpcRequest,
|
|
26
|
-
JsonRpcRequestMessage,
|
|
27
|
-
JsonRpcSucessfulResponseMessage,
|
|
28
|
-
} from '../types'
|
|
29
|
-
|
|
30
|
-
interface ProviderConnectInfo {
|
|
31
|
-
readonly chainId: string
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
interface ProviderRpcError extends Error {
|
|
35
|
-
message: string
|
|
36
|
-
code: number
|
|
37
|
-
data?: unknown
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
interface ProviderMessage {
|
|
41
|
-
type: string
|
|
42
|
-
data: unknown
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
// TODO: Replace any with proper type definitions
|
|
46
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
47
|
-
type RpcCallback = (error: any, response: any) => void
|
|
48
|
-
|
|
49
|
-
// By default timeout is 10 minutes
|
|
50
|
-
const DEFAULT_TIMEOUT_MILLISECONDS = 600000
|
|
51
|
-
|
|
52
|
-
const JSON_RPC_VERSION = '2.0'
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Options for constructing the iframe ethereum provider.
|
|
56
|
-
*/
|
|
57
|
-
interface IFrameEthereumProviderOptions {
|
|
58
|
-
// The origin to communicate with. Default '*'
|
|
59
|
-
targetOrigin?: string
|
|
60
|
-
// How long to time out waiting for responses. Default 60 seconds.
|
|
61
|
-
timeoutMilliseconds?: number
|
|
62
|
-
|
|
63
|
-
// The event source. By default we use the window. This can be mocked for tests, or it can wrap
|
|
64
|
-
// a different interface, e.g. workers.
|
|
65
|
-
eventSource?: Window
|
|
66
|
-
|
|
67
|
-
// The event target. By default we use the window parent. This can be mocked for tests, or it can wrap
|
|
68
|
-
// a different interface, e.g. workers.
|
|
69
|
-
eventTarget?: Window
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* This is what we store in the state to keep track of pending promises.
|
|
74
|
-
*/
|
|
75
|
-
interface PromiseCompleter<T, D> {
|
|
76
|
-
// A response was received (either error or result response).
|
|
77
|
-
resolve(result: JsonRpcSucessfulResponseMessage<T> | JsonRpcErrorResponseMessage<D>): void
|
|
78
|
-
|
|
79
|
-
// An error with executing the request was encountered.
|
|
80
|
-
reject(error: Error): void
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* We return a random number between the 0 and the maximum safe integer so that we always generate a unique identifier,
|
|
85
|
-
* across all communication channels.
|
|
86
|
-
*/
|
|
87
|
-
function getUniqueId(): number {
|
|
88
|
-
return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
export type IFrameEthereumProviderEventTypes =
|
|
92
|
-
| 'message'
|
|
93
|
-
| 'connect'
|
|
94
|
-
| 'disconnect'
|
|
95
|
-
| 'chainChanged'
|
|
96
|
-
| 'close' // Deprecated, use 'disconnect' instead
|
|
97
|
-
| 'notification'
|
|
98
|
-
| 'networkChanged' // Deprecated, use 'chainChanged' instead
|
|
99
|
-
| 'accountsChanged'
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Export the type information about the different events that are emitted.
|
|
103
|
-
*/
|
|
104
|
-
export interface IFrameEthereumProviderEvents {
|
|
105
|
-
on(event: 'message', handler: (message: ProviderMessage) => void): this
|
|
106
|
-
|
|
107
|
-
on(event: 'connect', handler: (connectInfo: ProviderConnectInfo) => void): this
|
|
108
|
-
|
|
109
|
-
on(event: 'disconnect', handler: (error: ProviderRpcError) => void): this
|
|
110
|
-
|
|
111
|
-
on(event: 'close', handler: (code: number, reason: string) => void): this
|
|
112
|
-
|
|
113
|
-
// TODO: Replace any with proper type definitions
|
|
114
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
115
|
-
on(event: 'notification', handler: (result: any) => void): this
|
|
116
|
-
|
|
117
|
-
on(event: 'chainChanged', handler: (chainId: string) => void): this
|
|
118
|
-
|
|
119
|
-
on(event: 'networkChanged', handler: (networkId: string) => void): this
|
|
120
|
-
|
|
121
|
-
on(event: 'accountsChanged', handler: (accounts: string[]) => void): this
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Represents an error in an RPC returned from the event source. Always contains a code and a reason. The message
|
|
126
|
-
* is constructed from both.
|
|
127
|
-
*/
|
|
128
|
-
export class RpcError extends Error {
|
|
129
|
-
public readonly isRpcError = true
|
|
130
|
-
|
|
131
|
-
public readonly code: number
|
|
132
|
-
public readonly reason: string
|
|
133
|
-
|
|
134
|
-
constructor(code: number, reason: string) {
|
|
135
|
-
super(`${code}: ${reason}`)
|
|
136
|
-
|
|
137
|
-
this.code = code
|
|
138
|
-
this.reason = reason
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* This is the primary artifact of this library.
|
|
144
|
-
*/
|
|
145
|
-
export class WidgetEthereumProvider extends EventEmitter<IFrameEthereumProviderEventTypes> {
|
|
146
|
-
// TODO: Add proper return type annotation
|
|
147
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
148
|
-
request({ method, params }: JsonRpcRequest) {
|
|
149
|
-
return this.send(method, params)
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
isConnected(): true {
|
|
153
|
-
return true
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Differentiate this provider from other providers by providing an isIFrame property that always returns true.
|
|
158
|
-
*/
|
|
159
|
-
public get isIFrame(): true {
|
|
160
|
-
return true
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Always return this for currentProvider.
|
|
165
|
-
*/
|
|
166
|
-
public get currentProvider(): WidgetEthereumProvider {
|
|
167
|
-
return this
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
private enabled: Promise<string[]> | null = null
|
|
171
|
-
private readonly timeoutMilliseconds: number
|
|
172
|
-
private readonly eventSource: Window
|
|
173
|
-
private readonly eventTarget: Window
|
|
174
|
-
private readonly completers: {
|
|
175
|
-
// TODO: Replace any with proper type definitions
|
|
176
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
177
|
-
[id: string]: PromiseCompleter<any, any>
|
|
178
|
-
} = {}
|
|
179
|
-
private providerMetaInfo: ProviderMetaInfoPayload | null = null
|
|
180
|
-
private providerMetaInfoCallback?: (data: ProviderMetaInfoPayload) => void
|
|
181
|
-
|
|
182
|
-
public constructor({
|
|
183
|
-
timeoutMilliseconds = DEFAULT_TIMEOUT_MILLISECONDS,
|
|
184
|
-
eventSource = window,
|
|
185
|
-
eventTarget = window.parent,
|
|
186
|
-
}: IFrameEthereumProviderOptions = {}) {
|
|
187
|
-
// Call super for `this` to be defined
|
|
188
|
-
super()
|
|
189
|
-
|
|
190
|
-
this.timeoutMilliseconds = timeoutMilliseconds
|
|
191
|
-
this.eventSource = eventSource
|
|
192
|
-
this.eventTarget = eventTarget
|
|
193
|
-
|
|
194
|
-
iframeRpcProviderTransport.listenToMessageFromWindow(
|
|
195
|
-
this.eventSource,
|
|
196
|
-
IframeRpcProviderEvents.PROVIDER_RPC_RESPONSE,
|
|
197
|
-
(message) => {
|
|
198
|
-
this.handleRpcRequests(message)
|
|
199
|
-
},
|
|
200
|
-
)
|
|
201
|
-
|
|
202
|
-
iframeRpcProviderTransport.listenToMessageFromWindow(
|
|
203
|
-
this.eventSource,
|
|
204
|
-
IframeRpcProviderEvents.PROVIDER_ON_EVENT,
|
|
205
|
-
(message) => {
|
|
206
|
-
this.handleOnEvent(message)
|
|
207
|
-
},
|
|
208
|
-
)
|
|
209
|
-
|
|
210
|
-
iframeRpcProviderTransport.listenToMessageFromWindow(
|
|
211
|
-
this.eventSource,
|
|
212
|
-
IframeRpcProviderEvents.SEND_PROVIDER_META_INFO,
|
|
213
|
-
(message) => {
|
|
214
|
-
this.providerMetaInfo = message
|
|
215
|
-
|
|
216
|
-
if (this.providerMetaInfoCallback) {
|
|
217
|
-
this.providerMetaInfoCallback(this.providerMetaInfo)
|
|
218
|
-
}
|
|
219
|
-
},
|
|
220
|
-
)
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* Helper method that handles transport and request wrapping
|
|
225
|
-
* @param method method to execute
|
|
226
|
-
* @param params params to pass the method
|
|
227
|
-
*/
|
|
228
|
-
private async execute<TResult, TErrorData>(
|
|
229
|
-
method: string,
|
|
230
|
-
params: unknown[] | undefined,
|
|
231
|
-
): Promise<JsonRpcSucessfulResponseMessage<TResult> | JsonRpcErrorResponseMessage<TErrorData>> {
|
|
232
|
-
const id = getUniqueId()
|
|
233
|
-
|
|
234
|
-
const rpcRequest: JsonRpcRequestMessage = {
|
|
235
|
-
jsonrpc: JSON_RPC_VERSION,
|
|
236
|
-
id,
|
|
237
|
-
method,
|
|
238
|
-
params,
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
const promise = new Promise<JsonRpcSucessfulResponseMessage<TResult> | JsonRpcErrorResponseMessage<TErrorData>>(
|
|
242
|
-
(resolve, reject) => (this.completers[id] = { resolve, reject }),
|
|
243
|
-
)
|
|
244
|
-
|
|
245
|
-
// Send the JSON RPC to the event source.
|
|
246
|
-
iframeRpcProviderTransport.postMessageToWindow(this.eventTarget, IframeRpcProviderEvents.PROVIDER_RPC_REQUEST, {
|
|
247
|
-
rpcRequest,
|
|
248
|
-
})
|
|
249
|
-
|
|
250
|
-
// Delete the completer within the timeout and reject the promise.
|
|
251
|
-
setTimeout(() => {
|
|
252
|
-
if (this.completers[id]) {
|
|
253
|
-
this.completers[id].reject(new Error('Request timed out. Please try again and submit it faster.'))
|
|
254
|
-
delete this.completers[id]
|
|
255
|
-
}
|
|
256
|
-
}, this.timeoutMilliseconds)
|
|
257
|
-
|
|
258
|
-
return promise
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
/**
|
|
262
|
-
* Send the JSON RPC and return the result.
|
|
263
|
-
*/
|
|
264
|
-
// TODO: Replace any with proper type definitions
|
|
265
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
266
|
-
public async send<TResult = any>(request: JsonRpcRequest, callback: RpcCallback): Promise<TResult>
|
|
267
|
-
// TODO: Replace any with proper type definitions
|
|
268
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
269
|
-
public async send<TResult = any>(method: string, params: unknown[] | undefined): Promise<TResult>
|
|
270
|
-
// TODO: Replace any with proper type definitions
|
|
271
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
272
|
-
public async send<TResult = any>(
|
|
273
|
-
methodOrRequest: string | JsonRpcRequest,
|
|
274
|
-
paramsOrCallback: unknown[] | undefined | RpcCallback,
|
|
275
|
-
): Promise<TResult> {
|
|
276
|
-
const { method, params } =
|
|
277
|
-
typeof methodOrRequest === 'string'
|
|
278
|
-
? { method: methodOrRequest, params: paramsOrCallback as unknown[] }
|
|
279
|
-
: { method: methodOrRequest.method, params: methodOrRequest.params }
|
|
280
|
-
|
|
281
|
-
// TODO: Replace any with proper type definitions
|
|
282
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
283
|
-
const response = await this.execute<TResult, any>(method, params)
|
|
284
|
-
|
|
285
|
-
if ('error' in response) {
|
|
286
|
-
throw new RpcError(response.error.code, response.error.message)
|
|
287
|
-
} else {
|
|
288
|
-
return response.result
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* Request the parent window to enable access to the user's web3 provider. Return accounts list immediately if already enabled.
|
|
294
|
-
* Keep the legacy method for backward compatibility.
|
|
295
|
-
*/
|
|
296
|
-
public async enable(): Promise<string[]> {
|
|
297
|
-
if (this.enabled === null) {
|
|
298
|
-
const promise = (this.enabled = this.send('eth_requestAccounts', []).catch((error) => {
|
|
299
|
-
// Clear this.enabled if it's this promise so we try again next call.
|
|
300
|
-
// this.enabled might be set from elsewhere if, e.g. the accounts changed event is emitted
|
|
301
|
-
if (this.enabled === promise) {
|
|
302
|
-
this.enabled = null
|
|
303
|
-
}
|
|
304
|
-
// Rethrow the error.
|
|
305
|
-
throw error
|
|
306
|
-
}))
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
return this.enabled
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
/**
|
|
313
|
-
* Backwards compatibility method for web3.
|
|
314
|
-
* @param payload payload to send to the provider
|
|
315
|
-
* @param callback callback to be called when the provider resolves
|
|
316
|
-
*/
|
|
317
|
-
public async sendAsync(
|
|
318
|
-
payload: JsonRpcRequest,
|
|
319
|
-
// TODO: Replace any with proper type definitions
|
|
320
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
321
|
-
callback: (error: string | null, result: { method: string; params?: any[]; result: any } | any) => void,
|
|
322
|
-
): Promise<void> {
|
|
323
|
-
try {
|
|
324
|
-
const result = await this.execute(payload.method, payload.params)
|
|
325
|
-
|
|
326
|
-
callback(null, result)
|
|
327
|
-
} catch (error) {
|
|
328
|
-
callback(error, null)
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
/**
|
|
333
|
-
* Subscribe to provider meta info
|
|
334
|
-
* @param callback
|
|
335
|
-
*/
|
|
336
|
-
// TODO: Add proper return type annotation
|
|
337
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
338
|
-
public onProviderMetaInfo(callback: (data: ProviderMetaInfoPayload) => void) {
|
|
339
|
-
if (this.providerMetaInfo) {
|
|
340
|
-
callback(this.providerMetaInfo)
|
|
341
|
-
} else {
|
|
342
|
-
this.providerMetaInfoCallback = callback
|
|
343
|
-
|
|
344
|
-
iframeRpcProviderTransport.postMessageToWindow(
|
|
345
|
-
this.eventTarget,
|
|
346
|
-
IframeRpcProviderEvents.REQUEST_PROVIDER_META_INFO,
|
|
347
|
-
null,
|
|
348
|
-
)
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
/**
|
|
353
|
-
* Handle a Rpc Request
|
|
354
|
-
*/
|
|
355
|
-
// TODO: Add proper return type annotation
|
|
356
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
357
|
-
private handleRpcRequests = ({ rpcResponse }: ProviderRpcResponsePayload) => {
|
|
358
|
-
if (rpcResponse.id === undefined || rpcResponse.id === null) {
|
|
359
|
-
return
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
const completer = this.completers['' + rpcResponse.id]
|
|
363
|
-
|
|
364
|
-
// True if we haven't timed out and this is a response to a message we sent.
|
|
365
|
-
if (completer) {
|
|
366
|
-
// Handle pending promise
|
|
367
|
-
if ('error' in rpcResponse || 'result' in rpcResponse) {
|
|
368
|
-
completer.resolve(rpcResponse)
|
|
369
|
-
} else {
|
|
370
|
-
completer.reject(new Error('Response from provider did not have error or result key'))
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
delete this.completers[rpcResponse.id]
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
// TODO: Add proper return type annotation
|
|
378
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
379
|
-
private handleOnEvent(message: ProviderOnEventPayload) {
|
|
380
|
-
// TODO: Replace any with proper type definitions
|
|
381
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
382
|
-
const params = message.params as any
|
|
383
|
-
switch (message.event) {
|
|
384
|
-
case 'notification':
|
|
385
|
-
this.emitNotification(params)
|
|
386
|
-
break
|
|
387
|
-
|
|
388
|
-
case 'connect':
|
|
389
|
-
this.emitConnect(params)
|
|
390
|
-
break
|
|
391
|
-
|
|
392
|
-
case 'disconnect':
|
|
393
|
-
this.emitDisconnect(params)
|
|
394
|
-
break
|
|
395
|
-
|
|
396
|
-
case 'chainChanged':
|
|
397
|
-
this.emitChainChanged(params)
|
|
398
|
-
break
|
|
399
|
-
|
|
400
|
-
case 'accountsChanged':
|
|
401
|
-
this.emitAccountsChanged(params)
|
|
402
|
-
break
|
|
403
|
-
|
|
404
|
-
case 'message':
|
|
405
|
-
this.emitMessage(params)
|
|
406
|
-
break
|
|
407
|
-
|
|
408
|
-
// Deprecated events below 👇 --------------------------------------
|
|
409
|
-
case 'networkChanged':
|
|
410
|
-
this.emitNetworkChanged(params)
|
|
411
|
-
break
|
|
412
|
-
|
|
413
|
-
case 'close':
|
|
414
|
-
this.emitClose(params)
|
|
415
|
-
break
|
|
416
|
-
|
|
417
|
-
// END OF: Deprecated events --------------------------------------
|
|
418
|
-
|
|
419
|
-
default:
|
|
420
|
-
console.warn(`[WidgetEthereumProvider] Unknown event type: ${message.event}`)
|
|
421
|
-
break
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
// TODO: Add proper return type annotation
|
|
426
|
-
// TODO: Replace any with proper type definitions
|
|
427
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-explicit-any
|
|
428
|
-
private emitNotification(result: any) {
|
|
429
|
-
this.emit('notification', result)
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
// TODO: Add proper return type annotation
|
|
433
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
434
|
-
private emitConnect(connectInfo: ProviderConnectInfo) {
|
|
435
|
-
// If the provider isn't enabled but it emits a connect event, assume that it's enabled and initialize
|
|
436
|
-
// with an empty list of accounts.
|
|
437
|
-
if (this.enabled === null) {
|
|
438
|
-
this.enabled = Promise.resolve([])
|
|
439
|
-
}
|
|
440
|
-
this.emit('connect', connectInfo)
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
/**
|
|
444
|
-
* @deprecated See https://eips.ethereum.org/EIPS/eip-1193
|
|
445
|
-
*/
|
|
446
|
-
// TODO: Add proper return type annotation
|
|
447
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
448
|
-
private emitClose(params: unknown) {
|
|
449
|
-
if (Array.isArray(params) && params.length === 2) {
|
|
450
|
-
this.emit('close', params[0], params[1])
|
|
451
|
-
} else {
|
|
452
|
-
this.emit('close')
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
// TODO: Add proper return type annotation
|
|
457
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
458
|
-
private emitDisconnect(error: ProviderRpcError) {
|
|
459
|
-
this.emit('disconnect', error)
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
// TODO: Add proper return type annotation
|
|
463
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
464
|
-
private emitChainChanged(chainId: string) {
|
|
465
|
-
this.emit('chainChanged', chainId)
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
/**
|
|
469
|
-
* @deprecated See https://eips.ethereum.org/EIPS/eip-1193
|
|
470
|
-
*/
|
|
471
|
-
// TODO: Add proper return type annotation
|
|
472
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
473
|
-
private emitNetworkChanged(networkId: string) {
|
|
474
|
-
this.emit('networkChanged', networkId)
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
// TODO: Add proper return type annotation
|
|
478
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
479
|
-
private emitAccountsChanged(accounts: string[]) {
|
|
480
|
-
this.enabled = Promise.resolve(accounts)
|
|
481
|
-
this.emit('accountsChanged', accounts)
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
// TODO: Add proper return type annotation
|
|
485
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
486
|
-
private emitMessage(message: ProviderMessage) {
|
|
487
|
-
this.emit('message', message)
|
|
488
|
-
}
|
|
489
|
-
}
|