@tomo-inc/inject-providers 0.0.1

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.
@@ -0,0 +1,304 @@
1
+ import { ethErrors } from "eth-rpc-errors";
2
+ import { EventEmitter } from "events";
3
+
4
+ import { ReadyPromise, domReadyCall, getDappInfo } from "../utils/index";
5
+ import { TxType } from "./types";
6
+
7
+ import { ChainTypes, IConnectors, IProductInfo } from "../types";
8
+
9
+ const chainType = ChainTypes.DOGE;
10
+
11
+ interface StateProvider {
12
+ accounts: string[] | null;
13
+ isConnected: boolean;
14
+ isUnlocked: boolean;
15
+ initialized: boolean;
16
+ isPermanentlyDisconnected: boolean;
17
+ }
18
+
19
+ export class DogecoinProvider extends EventEmitter {
20
+ _selectedAddress: string | null = null;
21
+ _network: string | null = null;
22
+ _isConnected = false;
23
+ _initialized = false;
24
+ _isUnlocked = false;
25
+ rdns = "";
26
+ name = "";
27
+ sendRequest: (chainType: string, data: any) => void;
28
+ onResponse: any;
29
+
30
+ _state: StateProvider = {
31
+ accounts: null,
32
+ isConnected: false,
33
+ isUnlocked: false,
34
+ initialized: false,
35
+ isPermanentlyDisconnected: false,
36
+ };
37
+
38
+ private _requestPromise = new ReadyPromise(0);
39
+
40
+ constructor(productInfo: IProductInfo, { sendRequest, onResponse }: IConnectors) {
41
+ super();
42
+ this.name = productInfo.name;
43
+ this.rdns = productInfo.rdns;
44
+ this.setMaxListeners(100);
45
+ this.sendRequest = sendRequest;
46
+ this.onResponse = onResponse;
47
+ this.initialize();
48
+ }
49
+
50
+ initialize = async () => {
51
+ // dapp tab switch send data;
52
+ document.addEventListener("visibilitychange", async () => {
53
+ if (document.visibilityState === "visible") {
54
+ this._request({
55
+ method: "wallet_sendDomainMetadata",
56
+ params: await getDappInfo(),
57
+ });
58
+ }
59
+ });
60
+
61
+ // this._bcm.connect().on("message", this._handleBackgroundMessage);
62
+ domReadyCall(async () => {
63
+ this._request({
64
+ method: "wallet_sendDomainMetadata",
65
+ params: await getDappInfo(),
66
+ });
67
+ });
68
+
69
+ this._state.initialized = true;
70
+ this._state.isConnected = true;
71
+
72
+ this.keepAlive();
73
+ };
74
+
75
+ /**
76
+ * Sending a message to the extension to receive will keep the service worker alive.
77
+ */
78
+ private keepAlive = () => {
79
+ this._request({
80
+ method: "keepAlive",
81
+ params: {},
82
+ }).then((v) => {
83
+ setTimeout(() => {
84
+ this.keepAlive();
85
+ }, 1000);
86
+ });
87
+ };
88
+
89
+ //adapter data by reuqest function
90
+ _request = async ({ method, params }: { method: string; params?: any }, adapter?: any) => {
91
+ if (!method) {
92
+ throw ethErrors.rpc.invalidRequest();
93
+ }
94
+
95
+ //api call -> ("0: dapp -> injector -> content");
96
+ const dappInfo = await getDappInfo();
97
+ this.sendRequest(chainType, { method, params, dappInfo });
98
+
99
+ //check result by method
100
+ return this.onResponse({ method }).then((res: any) => {
101
+ const { data } = res || {};
102
+
103
+ //maybe need some adaptor for doge api
104
+ return adapter ? adapter(data) : data;
105
+ });
106
+ };
107
+
108
+ request = async ({ method, params }: { method: string; params: any }) => {
109
+ if (!method) {
110
+ throw ethErrors.rpc.invalidRequest();
111
+ }
112
+ return this._request({
113
+ method,
114
+ params,
115
+ });
116
+ };
117
+
118
+ //res = { address, approved, balance, publicKey }
119
+ connect = async () => {
120
+ return this._request({
121
+ method: "connect",
122
+ params: {},
123
+ });
124
+ };
125
+
126
+ //res = { address, balance }
127
+ getBalance = async () => {
128
+ return this._request({
129
+ method: "getBalance",
130
+ });
131
+ };
132
+
133
+ //res = { disconnected }
134
+ disconnect = async () => {
135
+ return this._request({
136
+ method: "disconnect",
137
+ params: {},
138
+ });
139
+ };
140
+
141
+ //res = { "connected, address, selectedWalletAddress }
142
+ getConnectionStatus = async () => {
143
+ return this._request({
144
+ method: "getConnectionStatus",
145
+ params: {},
146
+ });
147
+ };
148
+
149
+ //res = { txId }
150
+ requestTransaction = async ({ recipientAddress, dogeAmount }: { recipientAddress: string; dogeAmount: number }) => {
151
+ return this._request({
152
+ method: "requestTransaction",
153
+ params: {
154
+ to: recipientAddress,
155
+ amount: dogeAmount,
156
+ type: TxType.SEND_DOGECOIN,
157
+ },
158
+ });
159
+ };
160
+
161
+ //res = {status === 'confirmed', confirmations > 1}
162
+ getTransactionStatus = async ({ txId }: { txId: string }) => {
163
+ return this._request({
164
+ method: "getTransactionStatus",
165
+ params: { txId },
166
+ });
167
+ };
168
+
169
+ //res = { signedMessage }
170
+ requestSignedMessage = async ({ message, type = "" }: { message: string; type?: string }) => {
171
+ return this._request({
172
+ method: "requestSignedMessage",
173
+ params: {
174
+ text: message,
175
+ type,
176
+ },
177
+ });
178
+ };
179
+
180
+ //res = { decryptedMessage }
181
+ requestDecryptedMessage = async ({ message }: { message: string }) => {
182
+ return this._request({
183
+ method: "requestDecryptedMessage",
184
+ params: {
185
+ message,
186
+ },
187
+ });
188
+ };
189
+
190
+ //res = { signedMessage }
191
+ getDRC20Balances = async (address: string, ticker?: string) => {
192
+ return this._request({
193
+ method: "getDRC20Balances",
194
+ params: {
195
+ address,
196
+ ticker,
197
+ },
198
+ });
199
+ };
200
+
201
+ //res = { availableBalance, transferableBalance, ticker, address }
202
+ getDRC20Balance = async ({ ticker }: { ticker?: string }) => {
203
+ return this._request({
204
+ method: "getDRC20Balance",
205
+ params: {
206
+ ticker,
207
+ },
208
+ });
209
+ };
210
+
211
+ //res = { inscriptions, ticker, address }
212
+ getTransferableDRC20 = async ({ ticker }: { ticker?: string }) => {
213
+ return this._request({
214
+ method: "getTransferableDRC20",
215
+ params: {
216
+ ticker,
217
+ },
218
+ });
219
+ };
220
+
221
+ //res = { txId, ticker, amount }
222
+ requestAvailableDRC20Transaction = async ({ ticker, amount }: { ticker: string; amount: number }) => {
223
+ return this._request({
224
+ method: "requestAvailableDRC20Transaction",
225
+ params: {
226
+ ticker,
227
+ amount,
228
+ },
229
+ });
230
+ };
231
+
232
+ //res = { txId }
233
+ requestInscriptionTransaction = async ({
234
+ location,
235
+ recipientAddress,
236
+ }: {
237
+ location: string;
238
+ recipientAddress: string;
239
+ }) => {
240
+ return this._request({
241
+ method: "requestInscriptionTransaction",
242
+ params: {
243
+ location,
244
+ recipientAddress,
245
+ },
246
+ });
247
+ };
248
+
249
+ //res = { ?signedRawTx, ?txId }
250
+ requestPsbt = async ({
251
+ rawTx,
252
+ indexes,
253
+ feeOnly,
254
+ signOnly,
255
+ partial,
256
+ sighashType,
257
+ }: {
258
+ rawTx: string;
259
+ indexes?: [];
260
+ feeOnly?: boolean;
261
+ signOnly?: boolean;
262
+ partial?: boolean;
263
+ sighashType?: string;
264
+ }) => {
265
+ return this._request({
266
+ method: "requestPsbt",
267
+ params: {
268
+ rawTx,
269
+ indexes,
270
+ feeOnly,
271
+ signOnly,
272
+ partial,
273
+ sighashType,
274
+ },
275
+ });
276
+ };
277
+
278
+ //---------//dunes
279
+ getDunesBalance = async (params: { ticker: string }) => {
280
+ return this._request({
281
+ method: "getDunesBalance",
282
+ params,
283
+ });
284
+ };
285
+
286
+ requestDunesTransaction = async ({
287
+ ticker,
288
+ amount,
289
+ recipientAddress,
290
+ }: {
291
+ ticker: string;
292
+ amount: number;
293
+ recipientAddress: string;
294
+ }) => {
295
+ return this._request({
296
+ method: "requestDunesTransaction",
297
+ params: {
298
+ ticker,
299
+ amount,
300
+ recipientAddress,
301
+ },
302
+ });
303
+ };
304
+ }
@@ -0,0 +1,3 @@
1
+ import { DogecoinProvider } from "./dogecoin";
2
+
3
+ export { DogecoinProvider };
@@ -0,0 +1,38 @@
1
+ import { DappInfo } from "../types";
2
+
3
+ export enum TxType {
4
+ SIGN_TX,
5
+ SEND_BITCOIN,
6
+ SEND_INSCRIPTION,
7
+ SEND_DOGECOIN,
8
+ }
9
+
10
+ export interface IDogeService {
11
+ connect(dappInfo: DappInfo): Promise<any>;
12
+ disconnect(dappInfo: DappInfo): Promise<any>;
13
+ requestAccounts(dappInfo: DappInfo): Promise<any>;
14
+ getAccounts(): Promise<any>;
15
+ getPublicKey(): Promise<any>;
16
+ getConnectionStatus(): Promise<any>;
17
+ getBalance(): Promise<any>;
18
+
19
+ signMessage(params: { text: string; type: string }): Promise<any>;
20
+ requestSignedMessage(params: { text: string; type: string }): Promise<any>;
21
+ requestDecryptedMessage(params: { message: string }): Promise<any>;
22
+
23
+ requestPsbt(params: { rawTx: string; signOnly?: boolean }): Promise<any>;
24
+
25
+ requestTransaction(txData: any): Promise<any>;
26
+ getTransactionStatus(params: { txId: string }): Promise<any>;
27
+
28
+ getDRC20Balance(params: { ticker: string }): Promise<any>;
29
+ getTransferableDRC20(params: { ticker: string }): Promise<any>;
30
+ requestAvailableDRC20Transaction(params: { ticker: string; amount: number }): Promise<any>;
31
+
32
+ requestInscriptionTransaction(params: {
33
+ recipientAddress: string;
34
+ location: string;
35
+ data?: string;
36
+ feeRate?: number;
37
+ }): Promise<any>;
38
+ }
@@ -0,0 +1,3 @@
1
+ import { EvmProvider } from "./metamask";
2
+
3
+ export { EvmProvider };
@@ -0,0 +1,39 @@
1
+ const ProductInfo = { name: "ethereum.provider" };
2
+
3
+ const messages = {
4
+ errors: {
5
+ disconnected: () => `${ProductInfo.name}: Disconnected from chain. Attempting to connect.`,
6
+ permanentlyDisconnected: () =>
7
+ `${ProductInfo.name}: Disconnected from ${ProductInfo.name} background. Page reload required.`,
8
+ sendSiteMetadata: () =>
9
+ `${ProductInfo.name}: Failed to send site metadata. This is an internal error, please report this bug.`,
10
+ unsupportedSync: (method: string) =>
11
+ `${ProductInfo.name}: The ${ProductInfo.name} Ethereum provider does not support synchronous methods like ${method} without a callback parameter.`,
12
+ invalidDuplexStream: () => "Must provide a Node.js-style duplex stream.",
13
+ invalidOptions: (maxEventListeners: unknown, shouldSendMetadata: unknown) =>
14
+ `Invalid options. Received: { maxEventListeners: ${maxEventListeners}, shouldSendMetadata: ${shouldSendMetadata} }`,
15
+ invalidRequestArgs: () => `Expected a single, non-array, object argument.`,
16
+ invalidRequestMethod: () => `'args.method' must be a non-empty string.`,
17
+ invalidRequestParams: () => `'args.params' must be an object or array if provided.`,
18
+ invalidLoggerObject: () => `'args.logger' must be an object if provided.`,
19
+ invalidLoggerMethod: (method: string) => `'args.logger' must include required method '${method}'.`,
20
+ },
21
+ info: {
22
+ connected: (chainId: string) => `${ProductInfo.name}: Connected to chain with ID "${chainId}".`,
23
+ },
24
+ warnings: {
25
+ // deprecated methods
26
+ enableDeprecation: `${ProductInfo.name}: 'ethereum.enable()' is deprecated and may be removed in the future. Please use the 'eth_requestAccounts' RPC method instead.\nFor more information, see: https://eips.ethereum.org/EIPS/eip-1102`,
27
+ sendDeprecation: `${ProductInfo.name}: 'ethereum.send(...)' is deprecated and may be removed in the future. Please use 'ethereum.sendAsync(...)' or 'ethereum.request(...)' instead.\nFor more information, see: https://eips.ethereum.org/EIPS/eip-1193`,
28
+ // deprecated events
29
+ events: {
30
+ close: `${ProductInfo.name}: The event 'close' is deprecated and may be removed in the future. Please use 'disconnect' instead.\nFor more information, see: https://eips.ethereum.org/EIPS/eip-1193#disconnect`,
31
+ data: `${ProductInfo.name}: The event 'data' is deprecated and will be removed in the future. Use 'message' instead.\nFor more information, see: https://eips.ethereum.org/EIPS/eip-1193#message`,
32
+ networkChanged: `${ProductInfo.name}: The event 'networkChanged' is deprecated and may be removed in the future. Use 'chainChanged' instead.\nFor more information, see: https://eips.ethereum.org/EIPS/eip-1193#chainchanged`,
33
+ notification: `${ProductInfo.name}: The event 'notification' is deprecated and may be removed in the future. Use 'message' instead.\nFor more information, see: https://eips.ethereum.org/EIPS/eip-1193#message`,
34
+ },
35
+ // misc
36
+ experimentalMethods: `${ProductInfo.name}: 'ethereum._${ProductInfo.name}' exposes non-standard, experimental methods. They may be removed or changed without warning.`,
37
+ },
38
+ };
39
+ export default messages;