@onekeyfe/onekey-cardano-provider 1.1.13

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # cross-inpage-provider
@@ -0,0 +1,95 @@
1
+ import { ProviderBase } from '@onekeyfe/cross-inpage-provider-core';
2
+ import { ProviderCardanoBase } from './ProviderCardanoBase';
3
+ import { IInpageProviderConfig } from '@onekeyfe/cross-inpage-provider-core';
4
+ import { IJsonRpcRequest } from '@onekeyfe/cross-inpage-provider-types';
5
+ import { Cbor, Bytes, Cip30DataSignature, Cip30Wallet, NetworkId, Paginate, WalletApi } from './types';
6
+ import * as TypeUtils from './type-utils';
7
+ export declare type CardanoRequest = WalletApi & {
8
+ connect: () => Promise<{
9
+ account: string;
10
+ }>;
11
+ getUtxos: (params: {
12
+ amount?: Cbor;
13
+ paginate?: Paginate;
14
+ }) => Promise<Cbor[] | undefined>;
15
+ signTx: (params: {
16
+ tx: Cbor;
17
+ partialSign?: boolean;
18
+ }) => Promise<Cbor>;
19
+ signData: (params: {
20
+ addr: Cbor;
21
+ payload: Bytes;
22
+ }) => Promise<Cip30DataSignature>;
23
+ };
24
+ export declare type JsBridgeRequest = {
25
+ [K in keyof CardanoRequest]: (params: Parameters<CardanoRequest[K]>[0]) => Promise<TypeUtils.WireStringified<TypeUtils.ResolvePromise<ReturnType<CardanoRequest[K]>>>>;
26
+ };
27
+ declare const PROVIDER_EVENTS: {
28
+ readonly connect: "connect";
29
+ readonly disconnect: "disconnect";
30
+ readonly accountChanged: "accountChanged";
31
+ readonly message_low_level: "message_low_level";
32
+ };
33
+ declare type CardanoProviderEventsMap = {
34
+ [PROVIDER_EVENTS.connect]: (account: string) => void;
35
+ [PROVIDER_EVENTS.disconnect]: () => void;
36
+ [PROVIDER_EVENTS.accountChanged]: (account: string | null) => void;
37
+ [PROVIDER_EVENTS.message_low_level]: (payload: IJsonRpcRequest) => void;
38
+ };
39
+ interface IProviderCardano extends ProviderBase {
40
+ isConnected: boolean;
41
+ onekey: Cip30Wallet;
42
+ getNetworkId(): Promise<NetworkId>;
43
+ }
44
+ declare type OneKeyCardanoProviderProps = IInpageProviderConfig & {
45
+ timeout?: number;
46
+ };
47
+ declare class ProviderCardano extends ProviderCardanoBase implements IProviderCardano {
48
+ private _account;
49
+ get account(): string | null;
50
+ get isConnected(): boolean;
51
+ get onekey(): Cip30Wallet;
52
+ get nami(): Cip30Wallet;
53
+ constructor(props: OneKeyCardanoProviderProps);
54
+ private _registerEvents;
55
+ private _callBridge;
56
+ private postMessage;
57
+ private _handleConnected;
58
+ private _handleDisconnected;
59
+ isAccountsChanged(address: string): boolean;
60
+ private _handleAccountChange;
61
+ on<E extends keyof CardanoProviderEventsMap>(event: E, listener: CardanoProviderEventsMap[E]): this;
62
+ emit<E extends keyof CardanoProviderEventsMap>(event: E, ...args: Parameters<CardanoProviderEventsMap[E]>): boolean;
63
+ walletInfo(): Cip30Wallet;
64
+ enable(): Promise<{
65
+ getNetworkId: () => Promise<NetworkId>;
66
+ getUtxos: (amount?: string | undefined, paginate?: Paginate | undefined) => Promise<string[] | undefined>;
67
+ getCollateral: () => Promise<null>;
68
+ getBalance: () => Promise<string>;
69
+ getUsedAddresses: () => Promise<string[]>;
70
+ getUnusedAddresses: () => Promise<string[]>;
71
+ getChangeAddress: () => Promise<string>;
72
+ getRewardAddresses: () => Promise<string[]>;
73
+ signTx: (tx: Cbor, partialSign?: boolean | undefined) => Promise<string>;
74
+ signData: (addr: Cbor, payload: Bytes) => Promise<{
75
+ key: string;
76
+ signature: string;
77
+ }>;
78
+ submitTx: (tx: Cbor) => Promise<string>;
79
+ }>;
80
+ getNetworkId(): Promise<NetworkId>;
81
+ getUtxos(amount?: Cbor, paginate?: Paginate): Promise<string[] | undefined>;
82
+ getCollateral(): Promise<null>;
83
+ getBalance(): Promise<string>;
84
+ getUsedAddresses(): Promise<Cbor[]>;
85
+ getUnUsedAddress(): Promise<string[]>;
86
+ getChangeAddress(): Promise<string>;
87
+ getRewardAddresses(): Promise<string[]>;
88
+ signTx(tx: Cbor, partialSign?: boolean): Promise<string>;
89
+ signData(addr: Cbor, payload: Bytes): Promise<{
90
+ key: string;
91
+ signature: string;
92
+ }>;
93
+ submitTx(tx: Cbor): Promise<string>;
94
+ }
95
+ export { ProviderCardano };
@@ -0,0 +1,224 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { ProviderCardanoBase } from './ProviderCardanoBase';
11
+ import { getOrCreateExtInjectedJsBridge } from '@onekeyfe/extension-bridge-injected';
12
+ import { isWalletEventMethodMatch } from './utils';
13
+ const PROVIDER_EVENTS = {
14
+ 'connect': 'connect',
15
+ 'disconnect': 'disconnect',
16
+ 'accountChanged': 'accountChanged',
17
+ 'message_low_level': 'message_low_level',
18
+ };
19
+ class ProviderCardano extends ProviderCardanoBase {
20
+ constructor(props) {
21
+ super(Object.assign(Object.assign({}, props), { bridge: props.bridge || getOrCreateExtInjectedJsBridge({ timeout: props.timeout }) }));
22
+ this._account = null;
23
+ this._registerEvents();
24
+ }
25
+ get account() {
26
+ return this._account;
27
+ }
28
+ get isConnected() {
29
+ return this._account !== null;
30
+ }
31
+ get onekey() {
32
+ return this.walletInfo();
33
+ }
34
+ get nami() {
35
+ return this.walletInfo();
36
+ }
37
+ _registerEvents() {
38
+ window.addEventListener('onekey_bridge_disconnect', () => {
39
+ this._handleDisconnected();
40
+ });
41
+ this.on(PROVIDER_EVENTS.message_low_level, (payload) => {
42
+ const { method, params } = payload;
43
+ if (isWalletEventMethodMatch(method, PROVIDER_EVENTS.accountChanged)) {
44
+ this._handleAccountChange(params);
45
+ }
46
+ });
47
+ }
48
+ _callBridge(params) {
49
+ return this.bridgeRequest(params);
50
+ }
51
+ postMessage(param) {
52
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
53
+ return this._callBridge(param);
54
+ }
55
+ _handleConnected(account, options) {
56
+ this._account = account;
57
+ if (options.emit && this.isConnectionStatusChanged('connected')) {
58
+ this.connectionStatus = 'connected';
59
+ this.emit('connect', account);
60
+ this.emit('accountChanged', account);
61
+ }
62
+ }
63
+ _handleDisconnected(options = { emit: true }) {
64
+ if (options.emit && this.isConnectionStatusChanged('disconnected')) {
65
+ this.connectionStatus = 'disconnected';
66
+ this.emit('disconnect');
67
+ this.emit('accountChanged', null);
68
+ }
69
+ }
70
+ isAccountsChanged(address) {
71
+ return address !== this._account;
72
+ }
73
+ _handleAccountChange(payload) {
74
+ const account = payload.accounts.address;
75
+ if (this.isAccountsChanged(account)) {
76
+ this.emit('accountChanged', account || null);
77
+ }
78
+ if (!account) {
79
+ this._handleDisconnected();
80
+ return;
81
+ }
82
+ if (account) {
83
+ this._handleConnected(account, { emit: false });
84
+ }
85
+ }
86
+ on(event, listener) {
87
+ return super.on(event, listener);
88
+ }
89
+ emit(event, ...args) {
90
+ return super.emit(event, ...args);
91
+ }
92
+ // CIP30 Wallet API 👇
93
+ walletInfo() {
94
+ return {
95
+ apiVersion: '0.1.0',
96
+ name: 'OneKey',
97
+ icon: 'https://theme.zdassets.com/theme_assets/10237731/cd8f795ce97bdd7657dd4fb4b19fde3f32b50349.png',
98
+ isEnabled: () => Promise.resolve(true),
99
+ enable: () => this.enable()
100
+ };
101
+ }
102
+ enable() {
103
+ return __awaiter(this, void 0, void 0, function* () {
104
+ const API = {
105
+ getNetworkId: () => this.getNetworkId(),
106
+ getUtxos: (amount, paginate) => this.getUtxos(amount, paginate),
107
+ getCollateral: () => this.getCollateral(),
108
+ getBalance: () => this.getBalance(),
109
+ getUsedAddresses: () => this.getUsedAddresses(),
110
+ getUnusedAddresses: () => this.getUnUsedAddress(),
111
+ getChangeAddress: () => this.getChangeAddress(),
112
+ getRewardAddresses: () => this.getRewardAddresses(),
113
+ signTx: (tx, partialSign) => this.signTx(tx, partialSign),
114
+ signData: (addr, payload) => this.signData(addr, payload),
115
+ submitTx: (tx) => this.submitTx(tx)
116
+ };
117
+ if (!this.account) {
118
+ const result = yield this._callBridge({
119
+ method: 'connect',
120
+ params: undefined
121
+ });
122
+ this._handleConnected(result.account, { emit: true });
123
+ return API;
124
+ }
125
+ return Promise.resolve(API);
126
+ });
127
+ }
128
+ // CIP30 Dapp API 👇
129
+ getNetworkId() {
130
+ return __awaiter(this, void 0, void 0, function* () {
131
+ return this._callBridge({
132
+ method: 'getNetworkId',
133
+ params: undefined
134
+ });
135
+ });
136
+ }
137
+ getUtxos(amount, paginate) {
138
+ return __awaiter(this, void 0, void 0, function* () {
139
+ return this._callBridge({
140
+ method: 'getUtxos',
141
+ params: {
142
+ amount,
143
+ paginate
144
+ }
145
+ });
146
+ });
147
+ }
148
+ getCollateral() {
149
+ return __awaiter(this, void 0, void 0, function* () {
150
+ return Promise.resolve(null);
151
+ });
152
+ }
153
+ getBalance() {
154
+ return __awaiter(this, void 0, void 0, function* () {
155
+ return this._callBridge({
156
+ method: 'getBalance',
157
+ params: undefined
158
+ });
159
+ });
160
+ }
161
+ getUsedAddresses() {
162
+ return __awaiter(this, void 0, void 0, function* () {
163
+ return this._callBridge({
164
+ method: 'getUsedAddresses',
165
+ params: undefined
166
+ });
167
+ });
168
+ }
169
+ getUnUsedAddress() {
170
+ return __awaiter(this, void 0, void 0, function* () {
171
+ return this._callBridge({
172
+ method: 'getUnusedAddresses',
173
+ params: undefined
174
+ });
175
+ });
176
+ }
177
+ getChangeAddress() {
178
+ return __awaiter(this, void 0, void 0, function* () {
179
+ return this._callBridge({
180
+ method: 'getChangeAddress',
181
+ params: undefined
182
+ });
183
+ });
184
+ }
185
+ getRewardAddresses() {
186
+ return __awaiter(this, void 0, void 0, function* () {
187
+ return this._callBridge({
188
+ method: 'getRewardAddresses',
189
+ params: undefined
190
+ });
191
+ });
192
+ }
193
+ signTx(tx, partialSign) {
194
+ return __awaiter(this, void 0, void 0, function* () {
195
+ return this._callBridge({
196
+ method: 'signTx',
197
+ params: {
198
+ tx,
199
+ partialSign
200
+ }
201
+ });
202
+ });
203
+ }
204
+ signData(addr, payload) {
205
+ return __awaiter(this, void 0, void 0, function* () {
206
+ return this._callBridge({
207
+ method: 'signData',
208
+ params: {
209
+ addr,
210
+ payload
211
+ }
212
+ });
213
+ });
214
+ }
215
+ submitTx(tx) {
216
+ return __awaiter(this, void 0, void 0, function* () {
217
+ return this._callBridge({
218
+ method: 'submitTx',
219
+ params: tx
220
+ });
221
+ });
222
+ }
223
+ }
224
+ export { ProviderCardano };
@@ -0,0 +1,8 @@
1
+ import { IInjectedProviderNames } from '@onekeyfe/cross-inpage-provider-types';
2
+ import { ProviderBase, IInpageProviderConfig } from '@onekeyfe/cross-inpage-provider-core';
3
+ declare class ProviderCardanoBase extends ProviderBase {
4
+ constructor(props: IInpageProviderConfig);
5
+ protected providerName: IInjectedProviderNames;
6
+ request(data: unknown): Promise<unknown>;
7
+ }
8
+ export { ProviderCardanoBase };
@@ -0,0 +1,12 @@
1
+ import { IInjectedProviderNames } from '@onekeyfe/cross-inpage-provider-types';
2
+ import { ProviderBase } from '@onekeyfe/cross-inpage-provider-core';
3
+ class ProviderCardanoBase extends ProviderBase {
4
+ constructor(props) {
5
+ super(props);
6
+ this.providerName = IInjectedProviderNames.cardano;
7
+ }
8
+ request(data) {
9
+ return this.bridgeRequest(data);
10
+ }
11
+ }
12
+ export { ProviderCardanoBase };
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ProviderCardano = void 0;
13
+ const ProviderCardanoBase_1 = require("./ProviderCardanoBase");
14
+ const extension_bridge_injected_1 = require("@onekeyfe/extension-bridge-injected");
15
+ const utils_1 = require("./utils");
16
+ const PROVIDER_EVENTS = {
17
+ 'connect': 'connect',
18
+ 'disconnect': 'disconnect',
19
+ 'accountChanged': 'accountChanged',
20
+ 'message_low_level': 'message_low_level',
21
+ };
22
+ class ProviderCardano extends ProviderCardanoBase_1.ProviderCardanoBase {
23
+ constructor(props) {
24
+ super(Object.assign(Object.assign({}, props), { bridge: props.bridge || (0, extension_bridge_injected_1.getOrCreateExtInjectedJsBridge)({ timeout: props.timeout }) }));
25
+ this._account = null;
26
+ this._registerEvents();
27
+ }
28
+ get account() {
29
+ return this._account;
30
+ }
31
+ get isConnected() {
32
+ return this._account !== null;
33
+ }
34
+ get onekey() {
35
+ return this.walletInfo();
36
+ }
37
+ get nami() {
38
+ return this.walletInfo();
39
+ }
40
+ _registerEvents() {
41
+ window.addEventListener('onekey_bridge_disconnect', () => {
42
+ this._handleDisconnected();
43
+ });
44
+ this.on(PROVIDER_EVENTS.message_low_level, (payload) => {
45
+ const { method, params } = payload;
46
+ if ((0, utils_1.isWalletEventMethodMatch)(method, PROVIDER_EVENTS.accountChanged)) {
47
+ this._handleAccountChange(params);
48
+ }
49
+ });
50
+ }
51
+ _callBridge(params) {
52
+ return this.bridgeRequest(params);
53
+ }
54
+ postMessage(param) {
55
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
56
+ return this._callBridge(param);
57
+ }
58
+ _handleConnected(account, options) {
59
+ this._account = account;
60
+ if (options.emit && this.isConnectionStatusChanged('connected')) {
61
+ this.connectionStatus = 'connected';
62
+ this.emit('connect', account);
63
+ this.emit('accountChanged', account);
64
+ }
65
+ }
66
+ _handleDisconnected(options = { emit: true }) {
67
+ if (options.emit && this.isConnectionStatusChanged('disconnected')) {
68
+ this.connectionStatus = 'disconnected';
69
+ this.emit('disconnect');
70
+ this.emit('accountChanged', null);
71
+ }
72
+ }
73
+ isAccountsChanged(address) {
74
+ return address !== this._account;
75
+ }
76
+ _handleAccountChange(payload) {
77
+ const account = payload.accounts.address;
78
+ if (this.isAccountsChanged(account)) {
79
+ this.emit('accountChanged', account || null);
80
+ }
81
+ if (!account) {
82
+ this._handleDisconnected();
83
+ return;
84
+ }
85
+ if (account) {
86
+ this._handleConnected(account, { emit: false });
87
+ }
88
+ }
89
+ on(event, listener) {
90
+ return super.on(event, listener);
91
+ }
92
+ emit(event, ...args) {
93
+ return super.emit(event, ...args);
94
+ }
95
+ // CIP30 Wallet API 👇
96
+ walletInfo() {
97
+ return {
98
+ apiVersion: '0.1.0',
99
+ name: 'OneKey',
100
+ icon: 'https://theme.zdassets.com/theme_assets/10237731/cd8f795ce97bdd7657dd4fb4b19fde3f32b50349.png',
101
+ isEnabled: () => Promise.resolve(true),
102
+ enable: () => this.enable()
103
+ };
104
+ }
105
+ enable() {
106
+ return __awaiter(this, void 0, void 0, function* () {
107
+ const API = {
108
+ getNetworkId: () => this.getNetworkId(),
109
+ getUtxos: (amount, paginate) => this.getUtxos(amount, paginate),
110
+ getCollateral: () => this.getCollateral(),
111
+ getBalance: () => this.getBalance(),
112
+ getUsedAddresses: () => this.getUsedAddresses(),
113
+ getUnusedAddresses: () => this.getUnUsedAddress(),
114
+ getChangeAddress: () => this.getChangeAddress(),
115
+ getRewardAddresses: () => this.getRewardAddresses(),
116
+ signTx: (tx, partialSign) => this.signTx(tx, partialSign),
117
+ signData: (addr, payload) => this.signData(addr, payload),
118
+ submitTx: (tx) => this.submitTx(tx)
119
+ };
120
+ if (!this.account) {
121
+ const result = yield this._callBridge({
122
+ method: 'connect',
123
+ params: undefined
124
+ });
125
+ this._handleConnected(result.account, { emit: true });
126
+ return API;
127
+ }
128
+ return Promise.resolve(API);
129
+ });
130
+ }
131
+ // CIP30 Dapp API 👇
132
+ getNetworkId() {
133
+ return __awaiter(this, void 0, void 0, function* () {
134
+ return this._callBridge({
135
+ method: 'getNetworkId',
136
+ params: undefined
137
+ });
138
+ });
139
+ }
140
+ getUtxos(amount, paginate) {
141
+ return __awaiter(this, void 0, void 0, function* () {
142
+ return this._callBridge({
143
+ method: 'getUtxos',
144
+ params: {
145
+ amount,
146
+ paginate
147
+ }
148
+ });
149
+ });
150
+ }
151
+ getCollateral() {
152
+ return __awaiter(this, void 0, void 0, function* () {
153
+ return Promise.resolve(null);
154
+ });
155
+ }
156
+ getBalance() {
157
+ return __awaiter(this, void 0, void 0, function* () {
158
+ return this._callBridge({
159
+ method: 'getBalance',
160
+ params: undefined
161
+ });
162
+ });
163
+ }
164
+ getUsedAddresses() {
165
+ return __awaiter(this, void 0, void 0, function* () {
166
+ return this._callBridge({
167
+ method: 'getUsedAddresses',
168
+ params: undefined
169
+ });
170
+ });
171
+ }
172
+ getUnUsedAddress() {
173
+ return __awaiter(this, void 0, void 0, function* () {
174
+ return this._callBridge({
175
+ method: 'getUnusedAddresses',
176
+ params: undefined
177
+ });
178
+ });
179
+ }
180
+ getChangeAddress() {
181
+ return __awaiter(this, void 0, void 0, function* () {
182
+ return this._callBridge({
183
+ method: 'getChangeAddress',
184
+ params: undefined
185
+ });
186
+ });
187
+ }
188
+ getRewardAddresses() {
189
+ return __awaiter(this, void 0, void 0, function* () {
190
+ return this._callBridge({
191
+ method: 'getRewardAddresses',
192
+ params: undefined
193
+ });
194
+ });
195
+ }
196
+ signTx(tx, partialSign) {
197
+ return __awaiter(this, void 0, void 0, function* () {
198
+ return this._callBridge({
199
+ method: 'signTx',
200
+ params: {
201
+ tx,
202
+ partialSign
203
+ }
204
+ });
205
+ });
206
+ }
207
+ signData(addr, payload) {
208
+ return __awaiter(this, void 0, void 0, function* () {
209
+ return this._callBridge({
210
+ method: 'signData',
211
+ params: {
212
+ addr,
213
+ payload
214
+ }
215
+ });
216
+ });
217
+ }
218
+ submitTx(tx) {
219
+ return __awaiter(this, void 0, void 0, function* () {
220
+ return this._callBridge({
221
+ method: 'submitTx',
222
+ params: tx
223
+ });
224
+ });
225
+ }
226
+ }
227
+ exports.ProviderCardano = ProviderCardano;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProviderCardanoBase = void 0;
4
+ const cross_inpage_provider_types_1 = require("@onekeyfe/cross-inpage-provider-types");
5
+ const cross_inpage_provider_core_1 = require("@onekeyfe/cross-inpage-provider-core");
6
+ class ProviderCardanoBase extends cross_inpage_provider_core_1.ProviderBase {
7
+ constructor(props) {
8
+ super(props);
9
+ this.providerName = cross_inpage_provider_types_1.IInjectedProviderNames.cardano;
10
+ }
11
+ request(data) {
12
+ return this.bridgeRequest(data);
13
+ }
14
+ }
15
+ exports.ProviderCardanoBase = ProviderCardanoBase;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ __exportStar(require("./ProviderCardano"), exports);
14
+ __exportStar(require("./ProviderCardanoBase"), exports);
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NetworkId = void 0;
4
+ var NetworkId;
5
+ (function (NetworkId) {
6
+ NetworkId[NetworkId["mainnet"] = 1] = "mainnet";
7
+ NetworkId[NetworkId["testnet"] = 0] = "testnet";
8
+ })(NetworkId = exports.NetworkId || (exports.NetworkId = {}));
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isWalletEventMethodMatch = void 0;
4
+ function isWalletEventMethodMatch(method, name) {
5
+ return method === `metamask_${name}` || method === `wallet_events_${name}`;
6
+ }
7
+ exports.isWalletEventMethodMatch = isWalletEventMethodMatch;
@@ -0,0 +1,2 @@
1
+ export * from './ProviderCardano';
2
+ export * from './ProviderCardanoBase';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './ProviderCardano';
2
+ export * from './ProviderCardanoBase';
@@ -0,0 +1,4 @@
1
+ export declare type WireStringified<T> = T extends Array<infer P> ? Array<WireStringified<P>> : T extends object ? {
2
+ [K in keyof T]: WireStringified<T[K]>;
3
+ } : T;
4
+ export declare type ResolvePromise<T> = T extends Promise<infer P> ? P : T;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,173 @@
1
+ export declare enum NetworkId {
2
+ mainnet = 1,
3
+ testnet = 0
4
+ }
5
+ /**
6
+ * DataSignature type as described in CIP-0030.
7
+ */
8
+ declare type CoseSign1CborHex = string;
9
+ declare type CoseKeyCborHex = string;
10
+ export interface Cip30DataSignature {
11
+ key: CoseKeyCborHex;
12
+ signature: CoseSign1CborHex;
13
+ }
14
+ /**
15
+ * A hex-encoded string of the corresponding bytes.
16
+ */
17
+ export declare type Bytes = string;
18
+ /**
19
+ * A hex-encoded string representing CBOR either inside
20
+ * of the Shelley Multi-asset binary spec or, if not present there,
21
+ * from the CIP-0008 signing spec.
22
+ */
23
+ export declare type Cbor = string;
24
+ /**
25
+ * Used to specify optional pagination for some API calls.
26
+ * Limits results to {limit} each page, and uses a 0-indexing {page}
27
+ * to refer to which of those pages of {limit} items each.
28
+ */
29
+ export declare type Paginate = {
30
+ page: number;
31
+ limit: number;
32
+ };
33
+ /**
34
+ * Returns the network id of the currently connected account.
35
+ * 0 is testnet and 1 is mainnet but other networks can possibly be returned by wallets.
36
+ * Those other network ID values are not governed by this document.
37
+ *
38
+ * This result will stay the same unless the connected account has changed.
39
+ *
40
+ * @throws ApiError
41
+ */
42
+ export declare type GetNetworkId = () => Promise<NetworkId>;
43
+ /**
44
+ * If `amount` is `undefined`, this shall return a list of all UTxOs (unspent transaction outputs)
45
+ * controlled by the wallet.
46
+ *
47
+ * If `amount` is not `undefined`, this request shall be limited to just the UTxOs that are required
48
+ * to reach the combined ADA/multi-asset value target specified in `amount`,
49
+ * and if this cannot be attained, `undefined` shall be returned.
50
+ *
51
+ * The results can be further paginated by `paginate` if it is not `undefined`.
52
+ *
53
+ * @throws ApiError
54
+ * @throws PaginateError
55
+ */
56
+ export declare type GetUtxos = (amount?: Cbor, paginate?: Paginate) => Promise<Cbor[] | undefined>;
57
+ /**
58
+ * @returns a list of one or more UTxOs (unspent transaction outputs) controlled by the wallet
59
+ * that are required to reach AT LEAST the combined ADA value target specified in amount
60
+ * AND the best suitable to be used as collateral inputs
61
+ * for transactions with plutus script inputs (pure ADA-only UTxOs).
62
+ * @throws ApiError
63
+ */
64
+ export declare type GetCollateral = (params?: {
65
+ amount?: Cbor;
66
+ }) => Promise<Cbor[] | null>;
67
+ /**
68
+ * Returns the total balance available of the wallet.
69
+ *
70
+ * This is the same as summing the results of `api.getUtxos()`, but it is both useful to dApps
71
+ * and likely already maintained by the implementing wallet in a more efficient manner
72
+ * so it has been included in the API as well.
73
+ *
74
+ * @throws ApiError
75
+ */
76
+ export declare type GetBalance = () => Promise<Cbor>;
77
+ /**
78
+ * Returns a list of all used (included in some on-chain transaction) addresses controlled by the wallet.
79
+ *
80
+ * The results can be further paginated by `paginate` if it is not `undefined`.
81
+ *
82
+ * @throws ApiError
83
+ * @throws PaginateError
84
+ */
85
+ export declare type GetUsedAddresses = (paginate?: Paginate) => Promise<Cbor[]>;
86
+ /**
87
+ * Returns a list of unused addresses controlled by the wallet.
88
+ *
89
+ * @throws ApiError
90
+ */
91
+ export declare type GetUnusedAddresses = () => Promise<Cbor[]>;
92
+ /**
93
+ * Returns an address owned by the wallet that should be used as a change address to return
94
+ * leftover assets during transaction creation back to the connected wallet.
95
+ *
96
+ * This can be used as a generic receive address as well.
97
+ *
98
+ * @throws ApiError
99
+ */
100
+ export declare type GetChangeAddress = () => Promise<Cbor>;
101
+ /**
102
+ * Returns the reward addresses owned by the wallet. This can return multiple addresses e.g. CIP-0018.
103
+ *
104
+ * @throws ApiError
105
+ */
106
+ export declare type GetRewardAddresses = () => Promise<Cbor[]>;
107
+ /**
108
+ * Requests that a user sign the unsigned portions of the supplied transaction.
109
+ *
110
+ * The wallet should ask the user for permission, and if given,
111
+ * try to sign the supplied body and return a signed transaction.
112
+ *
113
+ * If `partialSign` is `true`, the wallet only tries to sign what it can.
114
+ *
115
+ * If `partialSign` is `false` and the wallet could not sign the entire transaction,
116
+ * `TxSignError` shall be returned with the `ProofGeneration` code.
117
+ *
118
+ * Likewise if the user declined in either case it shall return the `UserDeclined` code.
119
+ *
120
+ * Only the portions of the witness set that were signed as a result of this call are
121
+ * returned to encourage dApps to verify the contents returned by this endpoint while building the final transaction.
122
+ *
123
+ * @throws ApiError
124
+ * @throws TxSignError
125
+ */
126
+ export declare type SignTx = (tx: Cbor, partialSign?: boolean) => Promise<Cbor>;
127
+ /**
128
+ * This endpoint utilizes the CIP-0008 signing spec for standardization/safety reasons.
129
+ *
130
+ * It allows the dApp to request the user to sign data conforming to said spec.
131
+ *
132
+ * The user's consent should be requested and the details of `sig_structure` shown to them in an informative way.
133
+ *
134
+ * Please refer to the CIP-0008 spec for details on how to construct the sig structure.
135
+ *
136
+ * @throws ApiError
137
+ * @throws DataSignError
138
+ */
139
+ export declare type SignData = (addr: Cbor, payload: Bytes) => Promise<Cip30DataSignature>;
140
+ /**
141
+ * As wallets should already have this ability, we allow dApps to request that a transaction be sent through it.
142
+ *
143
+ * If the wallet accepts the transaction and tries to send it, it shall return the transaction id for the dApp to track.
144
+ *
145
+ * The wallet is free to return the `TxSendError` with code `Refused` if they do not wish to send it,
146
+ * or `Failure` if there was an error in sending it (e.g. preliminary checks failed on signatures).
147
+ *
148
+ * @throws ApiError
149
+ * @throws TxSendError
150
+ */
151
+ export declare type SubmitTx = (tx: Cbor) => Promise<string>;
152
+ export interface WalletApi {
153
+ getNetworkId: GetNetworkId;
154
+ getUtxos: GetUtxos;
155
+ getBalance: GetBalance;
156
+ getCollateral: GetCollateral;
157
+ getUsedAddresses: GetUsedAddresses;
158
+ getUnusedAddresses: GetUnusedAddresses;
159
+ getChangeAddress: GetChangeAddress;
160
+ getRewardAddresses: GetRewardAddresses;
161
+ signTx: SignTx;
162
+ signData: SignData;
163
+ submitTx: SubmitTx;
164
+ }
165
+ export declare type WalletMethod = keyof WalletApi;
166
+ export declare type Cip30Wallet = {
167
+ enable(): Promise<WalletApi>;
168
+ isEnabled(): Promise<boolean>;
169
+ apiVersion: string;
170
+ name: string;
171
+ icon: string;
172
+ };
173
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ export var NetworkId;
2
+ (function (NetworkId) {
3
+ NetworkId[NetworkId["mainnet"] = 1] = "mainnet";
4
+ NetworkId[NetworkId["testnet"] = 0] = "testnet";
5
+ })(NetworkId || (NetworkId = {}));
@@ -0,0 +1 @@
1
+ export declare function isWalletEventMethodMatch(method: string, name: string): boolean;
package/dist/utils.js ADDED
@@ -0,0 +1,3 @@
1
+ export function isWalletEventMethodMatch(method, name) {
2
+ return method === `metamask_${name}` || method === `wallet_events_${name}`;
3
+ }
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@onekeyfe/onekey-cardano-provider",
3
+ "version": "1.1.13",
4
+ "keywords": [
5
+ "cross-inpage-provider",
6
+ "cardano"
7
+ ],
8
+ "author": "dev-fe@onekey.so",
9
+ "repository": "https://github.com/OneKeyHQ/cross-inpage-provider",
10
+ "license": "Apache-2.0",
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "files": [
16
+ "dist/*"
17
+ ],
18
+ "exports": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/cjs/index.js"
22
+ },
23
+ "types": "./dist/index.d.ts",
24
+ "module": "./dist/index.js",
25
+ "main": "./dist/cjs/index.js",
26
+ "scripts": {
27
+ "prebuild": "rm -rf dist",
28
+ "build": "tsc && tsc --project tsconfig.cjs.json",
29
+ "start": "tsc --watch"
30
+ },
31
+ "dependencies": {
32
+ "@onekeyfe/cross-inpage-provider-core": "1.1.13",
33
+ "@onekeyfe/cross-inpage-provider-errors": "1.1.13",
34
+ "@onekeyfe/cross-inpage-provider-types": "1.1.13",
35
+ "@onekeyfe/extension-bridge-injected": "1.1.13",
36
+ "@onekeyfe/onekey-cardano-provider": "1.1.13"
37
+ },
38
+ "gitHead": "d52492ad818797ee832931bb6e1d6c8b6f7460d0"
39
+ }