@1tokenfe/onetoken-ton-provider 2.2.46

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.md ADDED
@@ -0,0 +1,51 @@
1
+ # ONETOKEN STANDARD SOURCE LICENSE (O-SSL)
2
+
3
+ This license governs use of the accompanying software. If you use the software,
4
+ you accept this license. If you do not accept the license, do not use the
5
+ software.
6
+
7
+ ## 1. Definitions
8
+
9
+ The terms "reproduce," "reproduction" and "distribution" have the same meaning
10
+ here as under Hong Kong copyright law.
11
+
12
+ "You" means the licensee of the software.
13
+
14
+ "Your company" means the company you worked for when you downloaded the
15
+ software.
16
+
17
+ "Reference use" means use of the software within your company as a reference,
18
+ in read only form, for the sole purposes of debugging your products,
19
+ maintaining your products, or enhancing the interoperability of your products
20
+ with the software, and specifically excludes the right to distribute the
21
+ software outside of your company.
22
+
23
+ "Licensed patents" means any Licensor patent claims which read directly on the
24
+ software as distributed by the Licensor under this license.
25
+
26
+ ## 2. Grant of Rights
27
+
28
+ (A) Copyright Grant - Subject to the terms of this license, the Licensor grants
29
+ you a non-transferable, non-exclusive, worldwide, royalty-free copyright
30
+ license to reproduce the software for reference use.
31
+
32
+ (B) Patent Grant - Subject to the terms of this license, the Licensor grants
33
+ you a non-transferable, non-exclusive, worldwide, royalty-free patent license
34
+ under licensed patents for reference use.
35
+
36
+ ## 3. Limitations
37
+
38
+ (A) No Trademark License - This license does not grant you any rights to use
39
+ the Licensor's name, logo, or trademarks.
40
+
41
+ (B) If you begin patent litigation against the Licensor over patents that you
42
+ think may apply to the software (including a cross-claim or counterclaim in
43
+ a lawsuit), your license to the software ends automatically.
44
+
45
+ (C) The software is licensed "as-is." You bear the risk of using it. The
46
+ Licensor gives no express warranties, guarantees or conditions. You may have
47
+ additional consumer rights under your local laws which this license cannot
48
+ change. To the extent permitted under your local laws, the Licensor excludes
49
+ the implied warranties of merchantability, fitness for a particular purpose and
50
+ non-infringement.This license agreement is governed by the laws of Hong Kong,
51
+ and any disputes related to this license agreement shall be resolved in accordance with Hong Kong law.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # cross-inpage-provider
@@ -0,0 +1,63 @@
1
+ import { IInpageProviderConfig, IProviderBaseConnectionStatus } from '@1tokenfe/cross-inpage-provider-core';
2
+ import { ProviderTonBase } from './ProviderTonBase';
3
+ import { AppRequest, ConnectEvent, ConnectRequest, DeviceInfo, RpcMethod, WalletEvent, WalletResponse, WalletResponseError } from '@tonconnect/protocol';
4
+ import { AccountInfo, SignDataRequest, SignDataResult, SignProofRequest, SignProofResult, TransactionRequest, WalletInfo } from './types';
5
+ declare const PROVIDER_EVENTS: {
6
+ readonly disconnect: "disconnect";
7
+ readonly accountChanged: "accountChanged";
8
+ readonly message_low_level: "message_low_level";
9
+ };
10
+ export type TonRequest = {
11
+ 'connect': (protocolVersion?: number, message?: ConnectRequest) => Promise<AccountInfo>;
12
+ 'disconnect': () => Promise<void>;
13
+ 'sendTransaction': (payload: TransactionRequest) => Promise<string>;
14
+ 'signData': (payload: SignDataRequest) => Promise<SignDataResult>;
15
+ 'signProof': (request: SignProofRequest) => Promise<SignProofResult>;
16
+ 'getDeviceInfo': () => Promise<Partial<DeviceInfo>>;
17
+ };
18
+ export type PROVIDER_EVENTS_STRINGS = keyof typeof PROVIDER_EVENTS;
19
+ export interface IProviderTon extends ProviderTonBase {
20
+ deviceInfo: DeviceInfo;
21
+ walletInfo?: WalletInfo;
22
+ protocolVersion: number;
23
+ isWalletBrowser: boolean;
24
+ connect(protocolVersion: number, message: ConnectRequest): Promise<ConnectEvent>;
25
+ restoreConnection(): Promise<ConnectEvent>;
26
+ send<T extends RpcMethod>(message: AppRequest<T>): Promise<WalletResponse<T>>;
27
+ listen(callback: (event: WalletEvent) => void): void;
28
+ }
29
+ type OneTokenTonProviderProps = IInpageProviderConfig & {
30
+ timeout?: number;
31
+ };
32
+ export declare function createTonProviderOpenMask(originalProvider: ProviderTon): ProviderTon;
33
+ export declare function createTonProvider(originalProvider: ProviderTon, customDeviceInfo: Partial<DeviceInfo>, customWalletInfo: Partial<WalletInfo>): ProviderTon;
34
+ export declare class ProviderTon extends ProviderTonBase implements IProviderTon {
35
+ private _accountInfo;
36
+ deviceInfo: DeviceInfo;
37
+ walletInfo?: WalletInfo;
38
+ protocolVersion: number;
39
+ isWalletBrowser: boolean;
40
+ connectionStatus: IProviderBaseConnectionStatus;
41
+ constructor(props: OneTokenTonProviderProps);
42
+ private _getPlatform;
43
+ private _getDeviceInfo;
44
+ private _registerEvents;
45
+ private _callBridge;
46
+ private _handleConnected;
47
+ private _handleDisconnected;
48
+ isAccountsChanged(accountInfo: AccountInfo | undefined): boolean;
49
+ private _handleAccountChange;
50
+ private _network;
51
+ isNetworkChanged(network: string): boolean;
52
+ _connect(protocolVersion?: number, message?: ConnectRequest): Promise<ConnectEvent>;
53
+ connect(protocolVersion?: number, message?: ConnectRequest): Promise<ConnectEvent>;
54
+ restoreConnection(): Promise<ConnectEvent>;
55
+ convertError<T extends RpcMethod>(id: string, error: unknown, method: string): WalletResponseError<T>;
56
+ send<T extends RpcMethod>(message: AppRequest<T>): Promise<WalletResponse<T>>;
57
+ private _sendTransaction;
58
+ private _signData;
59
+ disconnect(): Promise<void>;
60
+ private _disconnect;
61
+ listen(callback: (event: WalletEvent) => void): void;
62
+ }
63
+ export {};
@@ -0,0 +1,397 @@
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 { getOrCreateExtInjectedJsBridge } from '@1tokenfe/extension-bridge-injected';
11
+ import { ProviderTonBase } from './ProviderTonBase';
12
+ import { CONNECT_EVENT_ERROR_CODES, SEND_TRANSACTION_ERROR_CODES, } from '@tonconnect/protocol';
13
+ import { ConnectEventErrorMessage, SendTransactionErrorMessage, } from './types';
14
+ const PROVIDER_EVENTS = {
15
+ 'disconnect': 'disconnect',
16
+ 'accountChanged': 'accountChanged',
17
+ 'message_low_level': 'message_low_level',
18
+ };
19
+ const TonResponseError = {
20
+ ParameterError: 1,
21
+ InvalidManifestUrl: 2,
22
+ ContentManifest: 3,
23
+ };
24
+ function isWalletEventMethodMatch({ method, name }) {
25
+ return method === `wallet_events_${name}`;
26
+ }
27
+ export function createTonProviderOpenMask(originalProvider) {
28
+ return createTonProvider(originalProvider, {
29
+ appName: 'openmask',
30
+ appVersion: '0.21.1',
31
+ }, {
32
+ name: 'OpenMask',
33
+ image: 'https://raw.githubusercontent.com/OpenProduct/openmask-extension/main/public/openmask-logo-288.png',
34
+ about_url: 'https://www.openmask.app/',
35
+ });
36
+ }
37
+ export function createTonProvider(originalProvider, customDeviceInfo, customWalletInfo) {
38
+ return new Proxy(originalProvider, {
39
+ get(target, prop, receiver) {
40
+ if (prop === 'deviceInfo') {
41
+ return Object.assign(Object.assign({}, target.deviceInfo), customDeviceInfo);
42
+ }
43
+ if (prop === 'walletInfo') {
44
+ return Object.assign(Object.assign({}, target.walletInfo), customWalletInfo);
45
+ }
46
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
47
+ return Reflect.get(target, prop, receiver);
48
+ },
49
+ });
50
+ }
51
+ // Doc: https://github.com/ton-blockchain/ton-connect/blob/main/requests-responses.md
52
+ export class ProviderTon extends ProviderTonBase {
53
+ constructor(props) {
54
+ super(Object.assign(Object.assign({}, props), { bridge: props.bridge || getOrCreateExtInjectedJsBridge({ timeout: props.timeout }) }));
55
+ this._accountInfo = null;
56
+ this.deviceInfo = {
57
+ platform: this._getPlatform(),
58
+ appName: 'onetoken',
59
+ appVersion: this.version,
60
+ maxProtocolVersion: 2,
61
+ features: ["SendTransaction", { name: 'SendTransaction', maxMessages: 4 }],
62
+ };
63
+ this.walletInfo = {
64
+ name: 'OneToken',
65
+ image: 'https://common.onetoken-asset.com/logo/onetoken-x288.png',
66
+ about_url: 'https://onetoken.so',
67
+ };
68
+ this.protocolVersion = 2;
69
+ this.isWalletBrowser = false;
70
+ this.connectionStatus = 'disconnected';
71
+ // void this._getDeviceInfo();
72
+ this._registerEvents();
73
+ }
74
+ _getPlatform() {
75
+ const userAgent = window.navigator.userAgent, platform = window.navigator.platform, macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'], iosPlatforms = ['iPhone', 'iPad'];
76
+ let os = 'windows';
77
+ if (macosPlatforms.indexOf(platform) !== -1) {
78
+ os = 'mac';
79
+ }
80
+ else if (iosPlatforms.indexOf(platform) !== -1) {
81
+ if (platform === 'iPhone') {
82
+ os = 'iphone';
83
+ }
84
+ else {
85
+ os = 'ipad';
86
+ }
87
+ }
88
+ else if (windowsPlatforms.indexOf(platform) !== -1) {
89
+ os = 'windows';
90
+ }
91
+ else if (/Android/.test(userAgent)) {
92
+ os = 'android';
93
+ }
94
+ else if (!os && /Linux/.test(platform)) {
95
+ os = 'linux';
96
+ }
97
+ return os;
98
+ }
99
+ _getDeviceInfo() {
100
+ return __awaiter(this, void 0, void 0, function* () {
101
+ const deviceInfo = yield this._callBridge({
102
+ method: 'getDeviceInfo',
103
+ params: [],
104
+ });
105
+ Object.assign(this.deviceInfo, deviceInfo);
106
+ });
107
+ }
108
+ _registerEvents() {
109
+ window.addEventListener('onetoken_bridge_disconnect', () => {
110
+ this._handleDisconnected();
111
+ });
112
+ this.on(PROVIDER_EVENTS.message_low_level, (payload) => {
113
+ if (!payload)
114
+ return;
115
+ const { method, params } = payload;
116
+ if (isWalletEventMethodMatch({ method, name: PROVIDER_EVENTS.accountChanged })) {
117
+ this._handleAccountChange(params);
118
+ }
119
+ });
120
+ }
121
+ _callBridge(params) {
122
+ return this.bridgeRequest(params);
123
+ }
124
+ _handleConnected(accountInfo, options = { emit: true }) {
125
+ var _a;
126
+ this._accountInfo = accountInfo;
127
+ if (options.emit && this.isConnectionStatusChanged('connected')) {
128
+ this.connectionStatus = 'connected';
129
+ const address = (_a = accountInfo.address) !== null && _a !== void 0 ? _a : null;
130
+ this.emit('connect', address);
131
+ this.emit('accountChanged', address);
132
+ }
133
+ }
134
+ _handleDisconnected(options = { emit: true }) {
135
+ this._accountInfo = null;
136
+ if (options.emit && this.isConnectionStatusChanged('disconnected')) {
137
+ this.connectionStatus = 'disconnected';
138
+ this.emit('disconnect');
139
+ this.emit('accountChanged', null);
140
+ }
141
+ }
142
+ isAccountsChanged(accountInfo) {
143
+ var _a;
144
+ return (accountInfo === null || accountInfo === void 0 ? void 0 : accountInfo.address) !== ((_a = this._accountInfo) === null || _a === void 0 ? void 0 : _a.address);
145
+ }
146
+ // trigger by bridge account change event
147
+ _handleAccountChange(payload) {
148
+ const accountInfo = payload;
149
+ if (this.isAccountsChanged(accountInfo)) {
150
+ this.emit('accountChanged', (accountInfo === null || accountInfo === void 0 ? void 0 : accountInfo.address) || null);
151
+ }
152
+ if (!accountInfo) {
153
+ this._handleDisconnected();
154
+ return;
155
+ }
156
+ this._handleConnected(accountInfo, { emit: false });
157
+ }
158
+ isNetworkChanged(network) {
159
+ return this._network === undefined || network !== this._network;
160
+ }
161
+ _connect(protocolVersion, message) {
162
+ return __awaiter(this, void 0, void 0, function* () {
163
+ const id = Date.now();
164
+ const isGetTonAddr = !message || (message && message.items.some((item) => item.name === 'ton_addr'));
165
+ const proofItem = message &&
166
+ message.items.find((item) => item.name === 'ton_proof');
167
+ const items = [];
168
+ if (isGetTonAddr) {
169
+ if (this._accountInfo) {
170
+ items.push(Object.assign({ name: 'ton_addr' }, this._accountInfo));
171
+ }
172
+ else {
173
+ let result;
174
+ try {
175
+ result = yield this._callBridge({
176
+ method: 'connect',
177
+ params: protocolVersion && message ? [protocolVersion, message] : [],
178
+ });
179
+ }
180
+ catch (error) {
181
+ const { code, message } = error;
182
+ if (code === 4001) {
183
+ return {
184
+ event: 'connect_error',
185
+ id,
186
+ payload: {
187
+ code: CONNECT_EVENT_ERROR_CODES.USER_REJECTS_ERROR,
188
+ message: ConnectEventErrorMessage.USER_DECLINED,
189
+ },
190
+ };
191
+ }
192
+ else if (code === TonResponseError.InvalidManifestUrl || code === TonResponseError.ContentManifest) {
193
+ return {
194
+ event: 'connect_error',
195
+ id,
196
+ payload: {
197
+ code,
198
+ message: message !== null && message !== void 0 ? message : "",
199
+ },
200
+ };
201
+ }
202
+ }
203
+ if (!result) {
204
+ return {
205
+ event: 'connect_error',
206
+ id,
207
+ payload: {
208
+ code: CONNECT_EVENT_ERROR_CODES.UNKNOWN_ERROR,
209
+ message: ConnectEventErrorMessage.UNKNOWN_ERROR,
210
+ },
211
+ };
212
+ }
213
+ items.push(Object.assign({ name: 'ton_addr' }, result));
214
+ this._handleConnected(result, { emit: true });
215
+ }
216
+ }
217
+ if (proofItem) {
218
+ let result;
219
+ try {
220
+ result = yield this._callBridge({
221
+ method: 'signProof',
222
+ params: [
223
+ {
224
+ payload: proofItem.payload,
225
+ },
226
+ ],
227
+ });
228
+ }
229
+ catch (error) {
230
+ const { code } = error;
231
+ if (code === 4001) {
232
+ return {
233
+ event: 'connect_error',
234
+ id,
235
+ payload: {
236
+ code: CONNECT_EVENT_ERROR_CODES.USER_REJECTS_ERROR,
237
+ message: ConnectEventErrorMessage.USER_DECLINED,
238
+ },
239
+ };
240
+ }
241
+ }
242
+ if (!result) {
243
+ return {
244
+ event: 'connect_error',
245
+ id,
246
+ payload: {
247
+ code: CONNECT_EVENT_ERROR_CODES.UNKNOWN_ERROR,
248
+ message: ConnectEventErrorMessage.UNKNOWN_ERROR,
249
+ },
250
+ };
251
+ }
252
+ items.push({
253
+ name: 'ton_proof',
254
+ proof: Object.assign(Object.assign({}, result), { payload: proofItem.payload }),
255
+ });
256
+ }
257
+ return {
258
+ event: 'connect',
259
+ id,
260
+ payload: {
261
+ items,
262
+ device: this.deviceInfo,
263
+ },
264
+ };
265
+ });
266
+ }
267
+ connect(protocolVersion, message) {
268
+ try {
269
+ return this._connect(protocolVersion, message);
270
+ }
271
+ catch (error) {
272
+ console.error('=====>>>>> connect error', error);
273
+ throw error;
274
+ }
275
+ }
276
+ restoreConnection() {
277
+ return this._connect();
278
+ }
279
+ convertError(id, error, method) {
280
+ const { code, message } = error;
281
+ if (code === 4001) {
282
+ let errorMessage = ConnectEventErrorMessage.USER_DECLINED;
283
+ if (method === 'sendTransaction' || method === 'signData') {
284
+ errorMessage = SendTransactionErrorMessage.USER_REJECTS_ERROR;
285
+ }
286
+ return {
287
+ id,
288
+ error: {
289
+ code: SEND_TRANSACTION_ERROR_CODES.USER_REJECTS_ERROR,
290
+ message: errorMessage,
291
+ },
292
+ };
293
+ }
294
+ else if (code === TonResponseError.ParameterError) {
295
+ return {
296
+ id,
297
+ error: {
298
+ code: SEND_TRANSACTION_ERROR_CODES.BAD_REQUEST_ERROR,
299
+ message: message,
300
+ },
301
+ };
302
+ }
303
+ else {
304
+ return {
305
+ id,
306
+ error: {
307
+ code: SEND_TRANSACTION_ERROR_CODES.UNKNOWN_APP_ERROR,
308
+ message: message !== null && message !== void 0 ? message : '',
309
+ },
310
+ };
311
+ }
312
+ }
313
+ send(message) {
314
+ return __awaiter(this, void 0, void 0, function* () {
315
+ const id = message.id;
316
+ let res;
317
+ try {
318
+ const params = message.params.map((p) => {
319
+ if (typeof p === 'string') {
320
+ return JSON.parse(p);
321
+ }
322
+ return p;
323
+ });
324
+ if (message.method === 'sendTransaction') {
325
+ res = yield this._sendTransaction(params[0]);
326
+ }
327
+ else if (message.method === 'signData') {
328
+ res = yield this._signData(params[0]);
329
+ }
330
+ else if (message.method === 'disconnect') {
331
+ yield this._disconnect();
332
+ // @ts-expect-error
333
+ return;
334
+ }
335
+ else {
336
+ return {
337
+ id,
338
+ error: {
339
+ code: SEND_TRANSACTION_ERROR_CODES.METHOD_NOT_SUPPORTED,
340
+ message: SendTransactionErrorMessage.METHOD_NOT_SUPPORTED,
341
+ },
342
+ };
343
+ }
344
+ }
345
+ catch (error) {
346
+ return this.convertError(id, error, message.method);
347
+ }
348
+ if (res === undefined) {
349
+ return {
350
+ id,
351
+ error: {
352
+ code: SEND_TRANSACTION_ERROR_CODES.UNKNOWN_ERROR,
353
+ message: SendTransactionErrorMessage.UNKNOWN_ERROR,
354
+ },
355
+ };
356
+ }
357
+ return {
358
+ id,
359
+ result: res,
360
+ };
361
+ });
362
+ }
363
+ _sendTransaction(request) {
364
+ return __awaiter(this, void 0, void 0, function* () {
365
+ return yield this._callBridge({
366
+ method: 'sendTransaction',
367
+ params: [request],
368
+ });
369
+ });
370
+ }
371
+ _signData(request) {
372
+ return __awaiter(this, void 0, void 0, function* () {
373
+ const res = yield this._callBridge({
374
+ method: 'signData',
375
+ params: [request],
376
+ });
377
+ return res;
378
+ });
379
+ }
380
+ disconnect() {
381
+ return __awaiter(this, void 0, void 0, function* () {
382
+ yield this._disconnect();
383
+ });
384
+ }
385
+ _disconnect() {
386
+ return __awaiter(this, void 0, void 0, function* () {
387
+ yield this._callBridge({
388
+ method: 'disconnect',
389
+ params: [],
390
+ });
391
+ this._handleDisconnected({ emit: true });
392
+ });
393
+ }
394
+ listen(callback) {
395
+ super.on('event', callback);
396
+ }
397
+ }
@@ -0,0 +1,8 @@
1
+ import { IInjectedProviderNames } from '@1tokenfe/cross-inpage-provider-types';
2
+ import { ProviderBase, IInpageProviderConfig } from '@1tokenfe/cross-inpage-provider-core';
3
+ declare class ProviderTonBase extends ProviderBase {
4
+ constructor(props: IInpageProviderConfig);
5
+ protected providerName: IInjectedProviderNames;
6
+ request(data: unknown): Promise<unknown>;
7
+ }
8
+ export { ProviderTonBase };
@@ -0,0 +1,12 @@
1
+ import { IInjectedProviderNames } from '@1tokenfe/cross-inpage-provider-types';
2
+ import { ProviderBase } from '@1tokenfe/cross-inpage-provider-core';
3
+ class ProviderTonBase extends ProviderBase {
4
+ constructor(props) {
5
+ super(props);
6
+ this.providerName = IInjectedProviderNames.ton;
7
+ }
8
+ request(data) {
9
+ return this.bridgeRequest(data);
10
+ }
11
+ }
12
+ export { ProviderTonBase };
@@ -0,0 +1,403 @@
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.ProviderTon = void 0;
13
+ exports.createTonProviderOpenMask = createTonProviderOpenMask;
14
+ exports.createTonProvider = createTonProvider;
15
+ const extension_bridge_injected_1 = require("@1tokenfe/extension-bridge-injected");
16
+ const ProviderTonBase_1 = require("./ProviderTonBase");
17
+ const protocol_1 = require("@tonconnect/protocol");
18
+ const types_1 = require("./types");
19
+ const PROVIDER_EVENTS = {
20
+ 'disconnect': 'disconnect',
21
+ 'accountChanged': 'accountChanged',
22
+ 'message_low_level': 'message_low_level',
23
+ };
24
+ const TonResponseError = {
25
+ ParameterError: 1,
26
+ InvalidManifestUrl: 2,
27
+ ContentManifest: 3,
28
+ };
29
+ function isWalletEventMethodMatch({ method, name }) {
30
+ return method === `wallet_events_${name}`;
31
+ }
32
+ function createTonProviderOpenMask(originalProvider) {
33
+ return createTonProvider(originalProvider, {
34
+ appName: 'openmask',
35
+ appVersion: '0.21.1',
36
+ }, {
37
+ name: 'OpenMask',
38
+ image: 'https://raw.githubusercontent.com/OpenProduct/openmask-extension/main/public/openmask-logo-288.png',
39
+ about_url: 'https://www.openmask.app/',
40
+ });
41
+ }
42
+ function createTonProvider(originalProvider, customDeviceInfo, customWalletInfo) {
43
+ return new Proxy(originalProvider, {
44
+ get(target, prop, receiver) {
45
+ if (prop === 'deviceInfo') {
46
+ return Object.assign(Object.assign({}, target.deviceInfo), customDeviceInfo);
47
+ }
48
+ if (prop === 'walletInfo') {
49
+ return Object.assign(Object.assign({}, target.walletInfo), customWalletInfo);
50
+ }
51
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
52
+ return Reflect.get(target, prop, receiver);
53
+ },
54
+ });
55
+ }
56
+ // Doc: https://github.com/ton-blockchain/ton-connect/blob/main/requests-responses.md
57
+ class ProviderTon extends ProviderTonBase_1.ProviderTonBase {
58
+ constructor(props) {
59
+ super(Object.assign(Object.assign({}, props), { bridge: props.bridge || (0, extension_bridge_injected_1.getOrCreateExtInjectedJsBridge)({ timeout: props.timeout }) }));
60
+ this._accountInfo = null;
61
+ this.deviceInfo = {
62
+ platform: this._getPlatform(),
63
+ appName: 'onetoken',
64
+ appVersion: this.version,
65
+ maxProtocolVersion: 2,
66
+ features: ["SendTransaction", { name: 'SendTransaction', maxMessages: 4 }],
67
+ };
68
+ this.walletInfo = {
69
+ name: 'OneToken',
70
+ image: 'https://common.onetoken-asset.com/logo/onetoken-x288.png',
71
+ about_url: 'https://onetoken.so',
72
+ };
73
+ this.protocolVersion = 2;
74
+ this.isWalletBrowser = false;
75
+ this.connectionStatus = 'disconnected';
76
+ // void this._getDeviceInfo();
77
+ this._registerEvents();
78
+ }
79
+ _getPlatform() {
80
+ const userAgent = window.navigator.userAgent, platform = window.navigator.platform, macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'], iosPlatforms = ['iPhone', 'iPad'];
81
+ let os = 'windows';
82
+ if (macosPlatforms.indexOf(platform) !== -1) {
83
+ os = 'mac';
84
+ }
85
+ else if (iosPlatforms.indexOf(platform) !== -1) {
86
+ if (platform === 'iPhone') {
87
+ os = 'iphone';
88
+ }
89
+ else {
90
+ os = 'ipad';
91
+ }
92
+ }
93
+ else if (windowsPlatforms.indexOf(platform) !== -1) {
94
+ os = 'windows';
95
+ }
96
+ else if (/Android/.test(userAgent)) {
97
+ os = 'android';
98
+ }
99
+ else if (!os && /Linux/.test(platform)) {
100
+ os = 'linux';
101
+ }
102
+ return os;
103
+ }
104
+ _getDeviceInfo() {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ const deviceInfo = yield this._callBridge({
107
+ method: 'getDeviceInfo',
108
+ params: [],
109
+ });
110
+ Object.assign(this.deviceInfo, deviceInfo);
111
+ });
112
+ }
113
+ _registerEvents() {
114
+ window.addEventListener('onetoken_bridge_disconnect', () => {
115
+ this._handleDisconnected();
116
+ });
117
+ this.on(PROVIDER_EVENTS.message_low_level, (payload) => {
118
+ if (!payload)
119
+ return;
120
+ const { method, params } = payload;
121
+ if (isWalletEventMethodMatch({ method, name: PROVIDER_EVENTS.accountChanged })) {
122
+ this._handleAccountChange(params);
123
+ }
124
+ });
125
+ }
126
+ _callBridge(params) {
127
+ return this.bridgeRequest(params);
128
+ }
129
+ _handleConnected(accountInfo, options = { emit: true }) {
130
+ var _a;
131
+ this._accountInfo = accountInfo;
132
+ if (options.emit && this.isConnectionStatusChanged('connected')) {
133
+ this.connectionStatus = 'connected';
134
+ const address = (_a = accountInfo.address) !== null && _a !== void 0 ? _a : null;
135
+ this.emit('connect', address);
136
+ this.emit('accountChanged', address);
137
+ }
138
+ }
139
+ _handleDisconnected(options = { emit: true }) {
140
+ this._accountInfo = null;
141
+ if (options.emit && this.isConnectionStatusChanged('disconnected')) {
142
+ this.connectionStatus = 'disconnected';
143
+ this.emit('disconnect');
144
+ this.emit('accountChanged', null);
145
+ }
146
+ }
147
+ isAccountsChanged(accountInfo) {
148
+ var _a;
149
+ return (accountInfo === null || accountInfo === void 0 ? void 0 : accountInfo.address) !== ((_a = this._accountInfo) === null || _a === void 0 ? void 0 : _a.address);
150
+ }
151
+ // trigger by bridge account change event
152
+ _handleAccountChange(payload) {
153
+ const accountInfo = payload;
154
+ if (this.isAccountsChanged(accountInfo)) {
155
+ this.emit('accountChanged', (accountInfo === null || accountInfo === void 0 ? void 0 : accountInfo.address) || null);
156
+ }
157
+ if (!accountInfo) {
158
+ this._handleDisconnected();
159
+ return;
160
+ }
161
+ this._handleConnected(accountInfo, { emit: false });
162
+ }
163
+ isNetworkChanged(network) {
164
+ return this._network === undefined || network !== this._network;
165
+ }
166
+ _connect(protocolVersion, message) {
167
+ return __awaiter(this, void 0, void 0, function* () {
168
+ const id = Date.now();
169
+ const isGetTonAddr = !message || (message && message.items.some((item) => item.name === 'ton_addr'));
170
+ const proofItem = message &&
171
+ message.items.find((item) => item.name === 'ton_proof');
172
+ const items = [];
173
+ if (isGetTonAddr) {
174
+ if (this._accountInfo) {
175
+ items.push(Object.assign({ name: 'ton_addr' }, this._accountInfo));
176
+ }
177
+ else {
178
+ let result;
179
+ try {
180
+ result = yield this._callBridge({
181
+ method: 'connect',
182
+ params: protocolVersion && message ? [protocolVersion, message] : [],
183
+ });
184
+ }
185
+ catch (error) {
186
+ const { code, message } = error;
187
+ if (code === 4001) {
188
+ return {
189
+ event: 'connect_error',
190
+ id,
191
+ payload: {
192
+ code: protocol_1.CONNECT_EVENT_ERROR_CODES.USER_REJECTS_ERROR,
193
+ message: types_1.ConnectEventErrorMessage.USER_DECLINED,
194
+ },
195
+ };
196
+ }
197
+ else if (code === TonResponseError.InvalidManifestUrl || code === TonResponseError.ContentManifest) {
198
+ return {
199
+ event: 'connect_error',
200
+ id,
201
+ payload: {
202
+ code,
203
+ message: message !== null && message !== void 0 ? message : "",
204
+ },
205
+ };
206
+ }
207
+ }
208
+ if (!result) {
209
+ return {
210
+ event: 'connect_error',
211
+ id,
212
+ payload: {
213
+ code: protocol_1.CONNECT_EVENT_ERROR_CODES.UNKNOWN_ERROR,
214
+ message: types_1.ConnectEventErrorMessage.UNKNOWN_ERROR,
215
+ },
216
+ };
217
+ }
218
+ items.push(Object.assign({ name: 'ton_addr' }, result));
219
+ this._handleConnected(result, { emit: true });
220
+ }
221
+ }
222
+ if (proofItem) {
223
+ let result;
224
+ try {
225
+ result = yield this._callBridge({
226
+ method: 'signProof',
227
+ params: [
228
+ {
229
+ payload: proofItem.payload,
230
+ },
231
+ ],
232
+ });
233
+ }
234
+ catch (error) {
235
+ const { code } = error;
236
+ if (code === 4001) {
237
+ return {
238
+ event: 'connect_error',
239
+ id,
240
+ payload: {
241
+ code: protocol_1.CONNECT_EVENT_ERROR_CODES.USER_REJECTS_ERROR,
242
+ message: types_1.ConnectEventErrorMessage.USER_DECLINED,
243
+ },
244
+ };
245
+ }
246
+ }
247
+ if (!result) {
248
+ return {
249
+ event: 'connect_error',
250
+ id,
251
+ payload: {
252
+ code: protocol_1.CONNECT_EVENT_ERROR_CODES.UNKNOWN_ERROR,
253
+ message: types_1.ConnectEventErrorMessage.UNKNOWN_ERROR,
254
+ },
255
+ };
256
+ }
257
+ items.push({
258
+ name: 'ton_proof',
259
+ proof: Object.assign(Object.assign({}, result), { payload: proofItem.payload }),
260
+ });
261
+ }
262
+ return {
263
+ event: 'connect',
264
+ id,
265
+ payload: {
266
+ items,
267
+ device: this.deviceInfo,
268
+ },
269
+ };
270
+ });
271
+ }
272
+ connect(protocolVersion, message) {
273
+ try {
274
+ return this._connect(protocolVersion, message);
275
+ }
276
+ catch (error) {
277
+ console.error('=====>>>>> connect error', error);
278
+ throw error;
279
+ }
280
+ }
281
+ restoreConnection() {
282
+ return this._connect();
283
+ }
284
+ convertError(id, error, method) {
285
+ const { code, message } = error;
286
+ if (code === 4001) {
287
+ let errorMessage = types_1.ConnectEventErrorMessage.USER_DECLINED;
288
+ if (method === 'sendTransaction' || method === 'signData') {
289
+ errorMessage = types_1.SendTransactionErrorMessage.USER_REJECTS_ERROR;
290
+ }
291
+ return {
292
+ id,
293
+ error: {
294
+ code: protocol_1.SEND_TRANSACTION_ERROR_CODES.USER_REJECTS_ERROR,
295
+ message: errorMessage,
296
+ },
297
+ };
298
+ }
299
+ else if (code === TonResponseError.ParameterError) {
300
+ return {
301
+ id,
302
+ error: {
303
+ code: protocol_1.SEND_TRANSACTION_ERROR_CODES.BAD_REQUEST_ERROR,
304
+ message: message,
305
+ },
306
+ };
307
+ }
308
+ else {
309
+ return {
310
+ id,
311
+ error: {
312
+ code: protocol_1.SEND_TRANSACTION_ERROR_CODES.UNKNOWN_APP_ERROR,
313
+ message: message !== null && message !== void 0 ? message : '',
314
+ },
315
+ };
316
+ }
317
+ }
318
+ send(message) {
319
+ return __awaiter(this, void 0, void 0, function* () {
320
+ const id = message.id;
321
+ let res;
322
+ try {
323
+ const params = message.params.map((p) => {
324
+ if (typeof p === 'string') {
325
+ return JSON.parse(p);
326
+ }
327
+ return p;
328
+ });
329
+ if (message.method === 'sendTransaction') {
330
+ res = yield this._sendTransaction(params[0]);
331
+ }
332
+ else if (message.method === 'signData') {
333
+ res = yield this._signData(params[0]);
334
+ }
335
+ else if (message.method === 'disconnect') {
336
+ yield this._disconnect();
337
+ // @ts-expect-error
338
+ return;
339
+ }
340
+ else {
341
+ return {
342
+ id,
343
+ error: {
344
+ code: protocol_1.SEND_TRANSACTION_ERROR_CODES.METHOD_NOT_SUPPORTED,
345
+ message: types_1.SendTransactionErrorMessage.METHOD_NOT_SUPPORTED,
346
+ },
347
+ };
348
+ }
349
+ }
350
+ catch (error) {
351
+ return this.convertError(id, error, message.method);
352
+ }
353
+ if (res === undefined) {
354
+ return {
355
+ id,
356
+ error: {
357
+ code: protocol_1.SEND_TRANSACTION_ERROR_CODES.UNKNOWN_ERROR,
358
+ message: types_1.SendTransactionErrorMessage.UNKNOWN_ERROR,
359
+ },
360
+ };
361
+ }
362
+ return {
363
+ id,
364
+ result: res,
365
+ };
366
+ });
367
+ }
368
+ _sendTransaction(request) {
369
+ return __awaiter(this, void 0, void 0, function* () {
370
+ return yield this._callBridge({
371
+ method: 'sendTransaction',
372
+ params: [request],
373
+ });
374
+ });
375
+ }
376
+ _signData(request) {
377
+ return __awaiter(this, void 0, void 0, function* () {
378
+ const res = yield this._callBridge({
379
+ method: 'signData',
380
+ params: [request],
381
+ });
382
+ return res;
383
+ });
384
+ }
385
+ disconnect() {
386
+ return __awaiter(this, void 0, void 0, function* () {
387
+ yield this._disconnect();
388
+ });
389
+ }
390
+ _disconnect() {
391
+ return __awaiter(this, void 0, void 0, function* () {
392
+ yield this._callBridge({
393
+ method: 'disconnect',
394
+ params: [],
395
+ });
396
+ this._handleDisconnected({ emit: true });
397
+ });
398
+ }
399
+ listen(callback) {
400
+ super.on('event', callback);
401
+ }
402
+ }
403
+ exports.ProviderTon = ProviderTon;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProviderTonBase = void 0;
4
+ const cross_inpage_provider_types_1 = require("@1tokenfe/cross-inpage-provider-types");
5
+ const cross_inpage_provider_core_1 = require("@1tokenfe/cross-inpage-provider-core");
6
+ class ProviderTonBase extends cross_inpage_provider_core_1.ProviderBase {
7
+ constructor(props) {
8
+ super(props);
9
+ this.providerName = cross_inpage_provider_types_1.IInjectedProviderNames.ton;
10
+ }
11
+ request(data) {
12
+ return this.bridgeRequest(data);
13
+ }
14
+ }
15
+ exports.ProviderTonBase = ProviderTonBase;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = 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);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types"), exports);
18
+ __exportStar(require("./OnetokenTonProvider"), exports);
19
+ __exportStar(require("./ProviderTonBase"), exports);
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SendTransactionErrorMessage = exports.ConnectEventErrorMessage = void 0;
4
+ var ConnectEventErrorMessage;
5
+ (function (ConnectEventErrorMessage) {
6
+ ConnectEventErrorMessage["UNKNOWN_ERROR"] = "Unknown error";
7
+ ConnectEventErrorMessage["BAD_REQUEST"] = "Bad request";
8
+ ConnectEventErrorMessage["APP_MANIFEST_NOT_FOUND"] = "App manifest not found";
9
+ ConnectEventErrorMessage["APP_MANIFEST_CONTENT_ERROR"] = "App manifest content error";
10
+ ConnectEventErrorMessage["UNKNOWN_APP"] = "Unknown app";
11
+ ConnectEventErrorMessage["USER_DECLINED"] = "User declined the connection";
12
+ })(ConnectEventErrorMessage || (exports.ConnectEventErrorMessage = ConnectEventErrorMessage = {}));
13
+ var SendTransactionErrorMessage;
14
+ (function (SendTransactionErrorMessage) {
15
+ SendTransactionErrorMessage["UNKNOWN_ERROR"] = "Unknown error";
16
+ SendTransactionErrorMessage["BAD_REQUEST_ERROR"] = "Bad request";
17
+ SendTransactionErrorMessage["UNKNOWN_APP_ERROR"] = "Unknown app";
18
+ SendTransactionErrorMessage["USER_REJECTS_ERROR"] = "User declined the transaction";
19
+ SendTransactionErrorMessage["METHOD_NOT_SUPPORTED"] = "Method is not supported";
20
+ })(SendTransactionErrorMessage || (exports.SendTransactionErrorMessage = SendTransactionErrorMessage = {}));
@@ -0,0 +1,3 @@
1
+ export * from './types';
2
+ export * from './OnetokenTonProvider';
3
+ export * from './ProviderTonBase';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './types';
2
+ export * from './OnetokenTonProvider';
3
+ export * from './ProviderTonBase';
@@ -0,0 +1,4 @@
1
+ export 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 type ResolvePromise<T> = T extends Promise<infer P> ? P : T;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,60 @@
1
+ import { CHAIN } from "@tonconnect/protocol";
2
+ export declare enum ConnectEventErrorMessage {
3
+ UNKNOWN_ERROR = "Unknown error",
4
+ BAD_REQUEST = "Bad request",
5
+ APP_MANIFEST_NOT_FOUND = "App manifest not found",
6
+ APP_MANIFEST_CONTENT_ERROR = "App manifest content error",
7
+ UNKNOWN_APP = "Unknown app",
8
+ USER_DECLINED = "User declined the connection"
9
+ }
10
+ export interface WalletInfo {
11
+ name: string;
12
+ image: string;
13
+ tondns?: string;
14
+ about_url: string;
15
+ }
16
+ export declare enum SendTransactionErrorMessage {
17
+ UNKNOWN_ERROR = "Unknown error",
18
+ BAD_REQUEST_ERROR = "Bad request",
19
+ UNKNOWN_APP_ERROR = "Unknown app",
20
+ USER_REJECTS_ERROR = "User declined the transaction",
21
+ METHOD_NOT_SUPPORTED = "Method is not supported"
22
+ }
23
+ export interface AccountInfo {
24
+ address: string;
25
+ network: CHAIN;
26
+ publicKey: string;
27
+ walletStateInit: string;
28
+ }
29
+ export interface Message {
30
+ address: string;
31
+ amount: string;
32
+ payload?: string;
33
+ stateInit?: string;
34
+ }
35
+ export interface TransactionRequest {
36
+ valid_until?: number;
37
+ network?: CHAIN;
38
+ from?: string;
39
+ messages: Message[];
40
+ }
41
+ export interface SignDataRequest {
42
+ schema_crc: number;
43
+ cell: string;
44
+ publicKey?: string;
45
+ }
46
+ export interface SignDataResult {
47
+ signature: string;
48
+ timestamp: number;
49
+ }
50
+ export interface SignProofRequest {
51
+ payload: string;
52
+ }
53
+ export interface SignProofResult {
54
+ signature: string;
55
+ timestamp: number;
56
+ domain: {
57
+ lengthBytes: number;
58
+ value: string;
59
+ };
60
+ }
package/dist/types.js ADDED
@@ -0,0 +1,17 @@
1
+ export var ConnectEventErrorMessage;
2
+ (function (ConnectEventErrorMessage) {
3
+ ConnectEventErrorMessage["UNKNOWN_ERROR"] = "Unknown error";
4
+ ConnectEventErrorMessage["BAD_REQUEST"] = "Bad request";
5
+ ConnectEventErrorMessage["APP_MANIFEST_NOT_FOUND"] = "App manifest not found";
6
+ ConnectEventErrorMessage["APP_MANIFEST_CONTENT_ERROR"] = "App manifest content error";
7
+ ConnectEventErrorMessage["UNKNOWN_APP"] = "Unknown app";
8
+ ConnectEventErrorMessage["USER_DECLINED"] = "User declined the connection";
9
+ })(ConnectEventErrorMessage || (ConnectEventErrorMessage = {}));
10
+ export var SendTransactionErrorMessage;
11
+ (function (SendTransactionErrorMessage) {
12
+ SendTransactionErrorMessage["UNKNOWN_ERROR"] = "Unknown error";
13
+ SendTransactionErrorMessage["BAD_REQUEST_ERROR"] = "Bad request";
14
+ SendTransactionErrorMessage["UNKNOWN_APP_ERROR"] = "Unknown app";
15
+ SendTransactionErrorMessage["USER_REJECTS_ERROR"] = "User declined the transaction";
16
+ SendTransactionErrorMessage["METHOD_NOT_SUPPORTED"] = "Method is not supported";
17
+ })(SendTransactionErrorMessage || (SendTransactionErrorMessage = {}));
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@1tokenfe/onetoken-ton-provider",
3
+ "version": "2.2.46",
4
+ "keywords": [
5
+ "cross-inpage-provider"
6
+ ],
7
+ "author": "dev-fe@onetoken.so",
8
+ "repository": "https://github.com/OneTokenHQ/cross-inpage-provider",
9
+ "license": "Apache-2.0",
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "files": [
14
+ "dist/*"
15
+ ],
16
+ "exports": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js",
19
+ "require": "./dist/cjs/index.js"
20
+ },
21
+ "types": "./dist/index.d.ts",
22
+ "module": "./dist/index.js",
23
+ "main": "./dist/cjs/index.js",
24
+ "scripts": {
25
+ "prebuild": "rm -rf dist",
26
+ "build": "tsc && tsc --project tsconfig.cjs.json",
27
+ "start": "tsc --watch"
28
+ },
29
+ "dependencies": {
30
+ "@1tokenfe/cross-inpage-provider-core": "2.2.46",
31
+ "@1tokenfe/cross-inpage-provider-errors": "2.2.46",
32
+ "@1tokenfe/cross-inpage-provider-types": "2.2.46",
33
+ "@1tokenfe/extension-bridge-injected": "2.2.46",
34
+ "@tonconnect/protocol": "^2.3.0"
35
+ },
36
+ "gitHead": "dadd71e7e07ab7aaf87961aecc01255586848e16"
37
+ }