@onekeyfe/onekey-cosmos-provider 2.0.0-alpha.8 → 2.0.0

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.
@@ -10,13 +10,13 @@ declare const PROVIDER_EVENTS: {
10
10
  readonly accountChanged: "accountChanged";
11
11
  readonly message_low_level: "message_low_level";
12
12
  };
13
- declare type CosmosProviderEventsMap = {
13
+ type CosmosProviderEventsMap = {
14
14
  [PROVIDER_EVENTS.connect]: (account: Key) => void;
15
15
  [PROVIDER_EVENTS.disconnect]: () => void;
16
16
  [PROVIDER_EVENTS.keplr_keystorechange]: () => void;
17
17
  [PROVIDER_EVENTS.message_low_level]: (payload: IJsonRpcRequest) => void;
18
18
  };
19
- export declare type CosmosRequest = {
19
+ export type CosmosRequest = {
20
20
  'enable': (chainIds: string[]) => Promise<void>;
21
21
  'disconnect': (chainIds: string[]) => Promise<void>;
22
22
  'experimentalSuggestChain': (chain: any) => Promise<void>;
@@ -37,7 +37,7 @@ export declare type CosmosRequest = {
37
37
  'verifyArbitrary': (chainId: string, signer: string, data: string | Uint8Array, signature: StdSignature) => Promise<boolean>;
38
38
  'signEthereum': (chainId: string, signer: string, data: string | Uint8Array, type: EthSignType) => Promise<string>;
39
39
  };
40
- export declare type PROVIDER_EVENTS_STRINGS = keyof typeof PROVIDER_EVENTS;
40
+ export type PROVIDER_EVENTS_STRINGS = keyof typeof PROVIDER_EVENTS;
41
41
  export interface IProviderCosmos {
42
42
  readonly mode: KeplrMode;
43
43
  defaultOptions: KeplrIntereactionOptions;
@@ -63,7 +63,7 @@ export interface IProviderCosmos {
63
63
  getOfflineSignerOnlyAmino(chainId: string): OfflineAminoSigner;
64
64
  getOfflineSignerAuto(chainId: string): Promise<OfflineAminoSigner | OfflineDirectSigner>;
65
65
  }
66
- export declare type OneKeySuiProviderProps = IInpageProviderConfig & {
66
+ export type OneKeySuiProviderProps = IInpageProviderConfig & {
67
67
  timeout?: number;
68
68
  };
69
69
  declare class ProviderCosmos extends ProviderCosmosBase implements IProviderCosmos {
@@ -75,7 +75,7 @@ declare class ProviderCosmos extends ProviderCosmosBase implements IProviderCosm
75
75
  private _callBridge;
76
76
  private _handleConnected;
77
77
  private _handleDisconnected;
78
- isAccountsChanged(account: Key | undefined): boolean;
78
+ isAccountsChanged(account: KeyHex | undefined): boolean;
79
79
  private _handleAccountChange;
80
80
  private _network;
81
81
  isNetworkChanged(network: string): boolean;
@@ -85,6 +85,7 @@ declare class ProviderCosmos extends ProviderCosmosBase implements IProviderCosm
85
85
  enable(chainIds: string | string[]): Promise<void>;
86
86
  disconnect(): Promise<void>;
87
87
  getKey(chainId: string): Promise<Key>;
88
+ ping(): Promise<void>;
88
89
  experimentalSuggestChain(chain: any): Promise<void>;
89
90
  signAmino(chainId: string, signer: string, signDoc: StdSignDoc, signOptions?: KeplrSignOptions | undefined): Promise<AminoSignResponse>;
90
91
  signDirect(chainId: string, signer: string, signDoc: {
@@ -15,6 +15,7 @@ import { ProviderCosmosBase } from './ProviderCosmosBase';
15
15
  import Long from 'long';
16
16
  import { CosmJSOfflineSigner, CosmJSOfflineSignerOnlyAmino } from './cosmjs';
17
17
  import { isArray } from 'lodash';
18
+ import { JSONUint8Array } from './utils/uint8-array';
18
19
  const PROVIDER_EVENTS = {
19
20
  'connect': 'connect',
20
21
  'disconnect': 'disconnect',
@@ -25,6 +26,7 @@ const PROVIDER_EVENTS = {
25
26
  function isWalletEventMethodMatch({ method, name }) {
26
27
  return method === `wallet_events_${name}`;
27
28
  }
29
+ const USING_MESSAGE_SITES = ['https://wallet.keplr.app', 'https://testnet.keplr.app'];
28
30
  class ProviderCosmos extends ProviderCosmosBase {
29
31
  constructor(props) {
30
32
  super(Object.assign(Object.assign({}, props), { bridge: props.bridge || getOrCreateExtInjectedJsBridge({ timeout: props.timeout }) }));
@@ -45,6 +47,47 @@ class ProviderCosmos extends ProviderCosmosBase {
45
47
  this._handleAccountChange(params);
46
48
  }
47
49
  });
50
+ this.on(PROVIDER_EVENTS.keplr_keystorechange, () => {
51
+ window.dispatchEvent(new Event(PROVIDER_EVENTS.keplr_keystorechange));
52
+ });
53
+ const isUsingMessage = USING_MESSAGE_SITES.includes(window.location.origin);
54
+ if (isUsingMessage) {
55
+ window.addEventListener('message', (e) => {
56
+ const data = e.data;
57
+ if (data && data.type === 'proxy-request' && data.method) {
58
+ const method = data.method;
59
+ if (this[method]) {
60
+ const unwrapedArgs = JSONUint8Array.unwrap(data.args);
61
+ this[method](...unwrapedArgs).then((res) => {
62
+ window.postMessage({
63
+ type: 'proxy-request-response',
64
+ id: data.id,
65
+ result: JSONUint8Array.wrap({
66
+ return: res,
67
+ }),
68
+ });
69
+ }).catch((err) => {
70
+ window.postMessage({
71
+ type: 'proxy-request-response',
72
+ id: data.id,
73
+ result: {
74
+ error: err.message,
75
+ },
76
+ });
77
+ });
78
+ }
79
+ else {
80
+ window.postMessage({
81
+ type: 'proxy-request-response',
82
+ id: data.id,
83
+ result: {
84
+ error: true,
85
+ },
86
+ });
87
+ }
88
+ }
89
+ });
90
+ }
48
91
  }
49
92
  _callBridge(params) {
50
93
  return this.bridgeRequest(params);
@@ -71,13 +114,13 @@ class ProviderCosmos extends ProviderCosmosBase {
71
114
  return false;
72
115
  if (!this._account)
73
116
  return true;
74
- return bytesToHex(account.pubKey) !== bytesToHex(this._account.pubKey);
117
+ return account.pubKey !== this._account.pubKey;
75
118
  }
76
119
  // trigger by bridge account change event
77
120
  _handleAccountChange(payload) {
78
121
  const account = payload;
79
122
  if (this.isAccountsChanged(account)) {
80
- this.emit('keplr_keystorechange');
123
+ this.emit(PROVIDER_EVENTS.keplr_keystorechange);
81
124
  }
82
125
  if (!account) {
83
126
  this._handleDisconnected();
@@ -123,6 +166,9 @@ class ProviderCosmos extends ProviderCosmosBase {
123
166
  address: hexToBytes(key.address) });
124
167
  });
125
168
  }
169
+ ping() {
170
+ return Promise.resolve();
171
+ }
126
172
  experimentalSuggestChain(chain) {
127
173
  return this._callBridge({
128
174
  method: 'experimentalSuggestChain',
@@ -21,6 +21,7 @@ const ProviderCosmosBase_1 = require("./ProviderCosmosBase");
21
21
  const long_1 = __importDefault(require("long"));
22
22
  const cosmjs_1 = require("./cosmjs");
23
23
  const lodash_1 = require("lodash");
24
+ const uint8_array_1 = require("./utils/uint8-array");
24
25
  const PROVIDER_EVENTS = {
25
26
  'connect': 'connect',
26
27
  'disconnect': 'disconnect',
@@ -31,6 +32,7 @@ const PROVIDER_EVENTS = {
31
32
  function isWalletEventMethodMatch({ method, name }) {
32
33
  return method === `wallet_events_${name}`;
33
34
  }
35
+ const USING_MESSAGE_SITES = ['https://wallet.keplr.app', 'https://testnet.keplr.app'];
34
36
  class ProviderCosmos extends ProviderCosmosBase_1.ProviderCosmosBase {
35
37
  constructor(props) {
36
38
  super(Object.assign(Object.assign({}, props), { bridge: props.bridge || (0, extension_bridge_injected_1.getOrCreateExtInjectedJsBridge)({ timeout: props.timeout }) }));
@@ -51,6 +53,47 @@ class ProviderCosmos extends ProviderCosmosBase_1.ProviderCosmosBase {
51
53
  this._handleAccountChange(params);
52
54
  }
53
55
  });
56
+ this.on(PROVIDER_EVENTS.keplr_keystorechange, () => {
57
+ window.dispatchEvent(new Event(PROVIDER_EVENTS.keplr_keystorechange));
58
+ });
59
+ const isUsingMessage = USING_MESSAGE_SITES.includes(window.location.origin);
60
+ if (isUsingMessage) {
61
+ window.addEventListener('message', (e) => {
62
+ const data = e.data;
63
+ if (data && data.type === 'proxy-request' && data.method) {
64
+ const method = data.method;
65
+ if (this[method]) {
66
+ const unwrapedArgs = uint8_array_1.JSONUint8Array.unwrap(data.args);
67
+ this[method](...unwrapedArgs).then((res) => {
68
+ window.postMessage({
69
+ type: 'proxy-request-response',
70
+ id: data.id,
71
+ result: uint8_array_1.JSONUint8Array.wrap({
72
+ return: res,
73
+ }),
74
+ });
75
+ }).catch((err) => {
76
+ window.postMessage({
77
+ type: 'proxy-request-response',
78
+ id: data.id,
79
+ result: {
80
+ error: err.message,
81
+ },
82
+ });
83
+ });
84
+ }
85
+ else {
86
+ window.postMessage({
87
+ type: 'proxy-request-response',
88
+ id: data.id,
89
+ result: {
90
+ error: true,
91
+ },
92
+ });
93
+ }
94
+ }
95
+ });
96
+ }
54
97
  }
55
98
  _callBridge(params) {
56
99
  return this.bridgeRequest(params);
@@ -77,13 +120,13 @@ class ProviderCosmos extends ProviderCosmosBase_1.ProviderCosmosBase {
77
120
  return false;
78
121
  if (!this._account)
79
122
  return true;
80
- return (0, utils_1.bytesToHex)(account.pubKey) !== (0, utils_1.bytesToHex)(this._account.pubKey);
123
+ return account.pubKey !== this._account.pubKey;
81
124
  }
82
125
  // trigger by bridge account change event
83
126
  _handleAccountChange(payload) {
84
127
  const account = payload;
85
128
  if (this.isAccountsChanged(account)) {
86
- this.emit('keplr_keystorechange');
129
+ this.emit(PROVIDER_EVENTS.keplr_keystorechange);
87
130
  }
88
131
  if (!account) {
89
132
  this._handleDisconnected();
@@ -129,6 +172,9 @@ class ProviderCosmos extends ProviderCosmosBase_1.ProviderCosmosBase {
129
172
  address: (0, utils_1.hexToBytes)(key.address) });
130
173
  });
131
174
  }
175
+ ping() {
176
+ return Promise.resolve();
177
+ }
132
178
  experimentalSuggestChain(chain) {
133
179
  return this._callBridge({
134
180
  method: 'experimentalSuggestChain',
package/dist/cjs/index.js CHANGED
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ /*
3
+ Belows are from @cosmjs/encoding library.
4
+ To reduce the bundle size of provider, put them directly here.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.fromHex = exports.toHex = void 0;
8
+ function toHex(data) {
9
+ let out = "";
10
+ for (const byte of data) {
11
+ out += (`0${byte.toString(16)}`).slice(-2);
12
+ }
13
+ return out;
14
+ }
15
+ exports.toHex = toHex;
16
+ function fromHex(hexstring) {
17
+ if (hexstring.length % 2 !== 0) {
18
+ throw new Error("hex string length must be a multiple of 2");
19
+ }
20
+ const listOfInts = [];
21
+ for (let i = 0; i < hexstring.length; i += 2) {
22
+ const hexByteAsString = hexstring.substr(i, 2);
23
+ if (!hexByteAsString.match(/[0-9a-f]{2}/i)) {
24
+ throw new Error("hex string contains invalid characters");
25
+ }
26
+ listOfInts.push(parseInt(hexByteAsString, 16));
27
+ }
28
+ return new Uint8Array(listOfInts);
29
+ }
30
+ exports.fromHex = fromHex;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JSONUint8Array = void 0;
4
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
5
+ /* eslint-disable @typescript-eslint/no-unsafe-return */
6
+ // The JSON encoder that supports the `Uint8Array`.
7
+ const hex_1 = require("./hex");
8
+ class JSONUint8Array {
9
+ static parse(text) {
10
+ return JSON.parse(text, (key, value) => {
11
+ // Prevent potential prototype poisoning.
12
+ if (key === "__proto__") {
13
+ throw new Error("__proto__ is disallowed");
14
+ }
15
+ if (value &&
16
+ typeof value === "string" &&
17
+ value.startsWith("__uint8array__")) {
18
+ return (0, hex_1.fromHex)(value.replace("__uint8array__", ""));
19
+ }
20
+ return value;
21
+ });
22
+ }
23
+ static stringify(obj) {
24
+ return JSON.stringify(obj, (key, value) => {
25
+ // Prevent potential prototype poisoning.
26
+ if (key === "__proto__") {
27
+ throw new Error("__proto__ is disallowed");
28
+ }
29
+ if (value &&
30
+ (value instanceof Uint8Array ||
31
+ (typeof value === "object" &&
32
+ "type" in value &&
33
+ "data" in value &&
34
+ value.type === "Buffer" &&
35
+ Array.isArray(value.data)))) {
36
+ const array = value instanceof Uint8Array ? value : new Uint8Array(value.data);
37
+ return `__uint8array__${(0, hex_1.toHex)(array)}`;
38
+ }
39
+ return value;
40
+ });
41
+ }
42
+ static wrap(obj) {
43
+ if (obj === undefined)
44
+ return undefined;
45
+ return JSON.parse(JSONUint8Array.stringify(obj));
46
+ }
47
+ static unwrap(obj) {
48
+ if (obj === undefined)
49
+ return undefined;
50
+ return JSONUint8Array.parse(JSON.stringify(obj));
51
+ }
52
+ }
53
+ exports.JSONUint8Array = JSONUint8Array;
@@ -1,4 +1,4 @@
1
- export declare type WireStringified<T> = T extends Array<infer P> ? Array<WireStringified<P>> : T extends object ? {
1
+ export type WireStringified<T> = T extends Array<infer P> ? Array<WireStringified<P>> : T extends object ? {
2
2
  [K in keyof T]: WireStringified<T[K]>;
3
3
  } : T;
4
- export declare type ResolvePromise<T> = T extends Promise<infer P> ? P : T;
4
+ export type ResolvePromise<T> = T extends Promise<infer P> ? P : T;
@@ -68,7 +68,7 @@ export interface SignDoc {
68
68
  /** account_number is the account number of the account in state */
69
69
  accountNumber: string;
70
70
  }
71
- export declare type SignDocHex = {
71
+ export type SignDocHex = {
72
72
  bodyBytes: string;
73
73
  authInfoBytes: string;
74
74
  accountNumber: string;
@@ -95,7 +95,7 @@ export interface DirectSignResponse {
95
95
  readonly signed: SignDoc;
96
96
  readonly signature: StdSignature;
97
97
  }
98
- export declare type DirectSignResponseHex = DirectSignResponse & {
98
+ export type DirectSignResponseHex = DirectSignResponse & {
99
99
  readonly signed: SignDocHex;
100
100
  };
101
101
  export interface OfflineDirectSigner {
@@ -46,14 +46,14 @@ export interface IBCCurrency extends Currency {
46
46
  /**
47
47
  * Any type of currency that Kepler applications can support.
48
48
  */
49
- export declare type AppCurrency = Currency | CW20Currency | Secret20Currency | IBCCurrency;
49
+ export type AppCurrency = Currency | CW20Currency | Secret20Currency | IBCCurrency;
50
50
  export interface FiatCurrency {
51
51
  readonly currency: string;
52
52
  readonly symbol: string;
53
53
  readonly maxDecimals: number;
54
54
  readonly locale: string;
55
55
  }
56
- export declare type WithGasPriceStep<T> = T & {
56
+ export type WithGasPriceStep<T> = T & {
57
57
  /**
58
58
  * This is used to set the fee of the transaction.
59
59
  * If this field is empty, it just use the default gas price step (low: 0.01, average: 0.025, high: 0.04).
@@ -64,4 +64,4 @@ export declare type WithGasPriceStep<T> = T & {
64
64
  readonly high: number;
65
65
  };
66
66
  };
67
- export declare type FeeCurrency = WithGasPriceStep<AppCurrency>;
67
+ export type FeeCurrency = WithGasPriceStep<AppCurrency>;
@@ -6,11 +6,11 @@ export interface Key {
6
6
  readonly bech32Address: string;
7
7
  readonly isNanoLedger: boolean;
8
8
  }
9
- export declare type KeyHex = Key & {
9
+ export type KeyHex = Key & {
10
10
  pubKey: string;
11
11
  address: string;
12
12
  };
13
- export declare type KeplrMode = 'extension' | 'mobile-web' | 'walletconnect';
13
+ export type KeplrMode = 'extension' | 'mobile-web' | 'walletconnect';
14
14
  export interface KeplrIntereactionOptions {
15
15
  readonly sign?: KeplrSignOptions;
16
16
  }
@@ -0,0 +1,2 @@
1
+ export declare function toHex(data: Uint8Array): string;
2
+ export declare function fromHex(hexstring: string): Uint8Array;
@@ -0,0 +1,25 @@
1
+ /*
2
+ Belows are from @cosmjs/encoding library.
3
+ To reduce the bundle size of provider, put them directly here.
4
+ */
5
+ export function toHex(data) {
6
+ let out = "";
7
+ for (const byte of data) {
8
+ out += (`0${byte.toString(16)}`).slice(-2);
9
+ }
10
+ return out;
11
+ }
12
+ export function fromHex(hexstring) {
13
+ if (hexstring.length % 2 !== 0) {
14
+ throw new Error("hex string length must be a multiple of 2");
15
+ }
16
+ const listOfInts = [];
17
+ for (let i = 0; i < hexstring.length; i += 2) {
18
+ const hexByteAsString = hexstring.substr(i, 2);
19
+ if (!hexByteAsString.match(/[0-9a-f]{2}/i)) {
20
+ throw new Error("hex string contains invalid characters");
21
+ }
22
+ listOfInts.push(parseInt(hexByteAsString, 16));
23
+ }
24
+ return new Uint8Array(listOfInts);
25
+ }
@@ -0,0 +1,6 @@
1
+ export declare class JSONUint8Array {
2
+ static parse(text: string): any;
3
+ static stringify(obj: unknown): string;
4
+ static wrap(obj: unknown): unknown;
5
+ static unwrap(obj: unknown): unknown;
6
+ }
@@ -0,0 +1,49 @@
1
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
2
+ /* eslint-disable @typescript-eslint/no-unsafe-return */
3
+ // The JSON encoder that supports the `Uint8Array`.
4
+ import { fromHex, toHex } from "./hex";
5
+ export class JSONUint8Array {
6
+ static parse(text) {
7
+ return JSON.parse(text, (key, value) => {
8
+ // Prevent potential prototype poisoning.
9
+ if (key === "__proto__") {
10
+ throw new Error("__proto__ is disallowed");
11
+ }
12
+ if (value &&
13
+ typeof value === "string" &&
14
+ value.startsWith("__uint8array__")) {
15
+ return fromHex(value.replace("__uint8array__", ""));
16
+ }
17
+ return value;
18
+ });
19
+ }
20
+ static stringify(obj) {
21
+ return JSON.stringify(obj, (key, value) => {
22
+ // Prevent potential prototype poisoning.
23
+ if (key === "__proto__") {
24
+ throw new Error("__proto__ is disallowed");
25
+ }
26
+ if (value &&
27
+ (value instanceof Uint8Array ||
28
+ (typeof value === "object" &&
29
+ "type" in value &&
30
+ "data" in value &&
31
+ value.type === "Buffer" &&
32
+ Array.isArray(value.data)))) {
33
+ const array = value instanceof Uint8Array ? value : new Uint8Array(value.data);
34
+ return `__uint8array__${toHex(array)}`;
35
+ }
36
+ return value;
37
+ });
38
+ }
39
+ static wrap(obj) {
40
+ if (obj === undefined)
41
+ return undefined;
42
+ return JSON.parse(JSONUint8Array.stringify(obj));
43
+ }
44
+ static unwrap(obj) {
45
+ if (obj === undefined)
46
+ return undefined;
47
+ return JSONUint8Array.parse(JSON.stringify(obj));
48
+ }
49
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/onekey-cosmos-provider",
3
- "version": "2.0.0-alpha.8",
3
+ "version": "2.0.0",
4
4
  "keywords": [
5
5
  "cross-inpage-provider"
6
6
  ],
@@ -29,13 +29,13 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "@noble/hashes": "^1.3.0",
32
- "@onekeyfe/cross-inpage-provider-core": "2.0.0-alpha.8",
33
- "@onekeyfe/cross-inpage-provider-errors": "2.0.0-alpha.8",
34
- "@onekeyfe/cross-inpage-provider-types": "2.0.0-alpha.8",
35
- "@onekeyfe/extension-bridge-injected": "2.0.0-alpha.8",
32
+ "@onekeyfe/cross-inpage-provider-core": "2.0.0",
33
+ "@onekeyfe/cross-inpage-provider-errors": "2.0.0",
34
+ "@onekeyfe/cross-inpage-provider-types": "2.0.0",
35
+ "@onekeyfe/extension-bridge-injected": "2.0.0",
36
36
  "eth-rpc-errors": "^4.0.3",
37
37
  "long": "^5.2.1",
38
38
  "mitt": "^3.0.0"
39
39
  },
40
- "gitHead": "a72404c2d39b3910aa62c137be02e4643c3b59f0"
40
+ "gitHead": "4e9109e35064cc7dafe3a4f86a33f497ad9567ec"
41
41
  }