@fastnear/api 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/cjs/index.cjs +40 -0
  2. package/dist/cjs/index.cjs.map +1 -0
  3. package/dist/cjs/index.d.cts +3339 -0
  4. package/dist/esm/index.d.ts +3339 -0
  5. package/dist/esm/index.js +9 -60
  6. package/dist/esm/index.js.map +1 -7
  7. package/dist/umd/{index.js → browser.global.js} +272 -120
  8. package/dist/umd/browser.global.js.map +1 -0
  9. package/package.json +9 -8
  10. package/dist/cjs/cryptoUtils.js +0 -89
  11. package/dist/cjs/cryptoUtils.js.map +0 -7
  12. package/dist/cjs/index.esm.js +0 -1219
  13. package/dist/cjs/index.esm.js.map +0 -7
  14. package/dist/cjs/index.js +0 -1274
  15. package/dist/cjs/index.js.map +0 -7
  16. package/dist/cjs/near.js +0 -1219
  17. package/dist/cjs/near.js.map +0 -7
  18. package/dist/cjs/transaction.js +0 -360
  19. package/dist/cjs/transaction.js.map +0 -7
  20. package/dist/cjs/utils.js +0 -105
  21. package/dist/cjs/utils.js.map +0 -7
  22. package/dist/esm/chunk-2SCAGR3F.js +0 -68
  23. package/dist/esm/chunk-2SCAGR3F.js.map +0 -7
  24. package/dist/esm/chunk-OR3WITSY.js +0 -842
  25. package/dist/esm/chunk-OR3WITSY.js.map +0 -7
  26. package/dist/esm/chunk-S5Q2EM2B.js +0 -48
  27. package/dist/esm/chunk-S5Q2EM2B.js.map +0 -7
  28. package/dist/esm/chunk-YKPILPMX.js +0 -301
  29. package/dist/esm/chunk-YKPILPMX.js.map +0 -7
  30. package/dist/esm/cryptoUtils.js +0 -21
  31. package/dist/esm/cryptoUtils.js.map +0 -7
  32. package/dist/esm/index.esm.js +0 -13
  33. package/dist/esm/index.esm.js.map +0 -7
  34. package/dist/esm/near.js +0 -15
  35. package/dist/esm/near.js.map +0 -7
  36. package/dist/esm/transaction.js +0 -16
  37. package/dist/esm/transaction.js.map +0 -7
  38. package/dist/esm/utils.js +0 -24
  39. package/dist/esm/utils.js.map +0 -7
  40. package/dist/umd/index.js.map +0 -7
@@ -1,1219 +0,0 @@
1
- /* ⋈ 🏃🏻💨 FastNEAR API - https://github.com/fastnear */
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.esm.ts
31
- var index_esm_exports = {};
32
- __export(index_esm_exports, {
33
- $$: () => convertUnit,
34
- near: () => api
35
- });
36
- module.exports = __toCommonJS(index_esm_exports);
37
-
38
- // src/near.ts
39
- var import_big2 = __toESM(require("big.js"), 1);
40
-
41
- // ../wallet-adapter/src/index.ts
42
- var WalletAdapter = class _WalletAdapter {
43
- /** @type {HTMLIFrameElement} */
44
- #iframe = null;
45
- /** @type {string} */
46
- #targetOrigin;
47
- /** @type {string} */
48
- #widgetUrl;
49
- /** @type {Map<string, Function>} */
50
- #pending = /* @__PURE__ */ new Map();
51
- /** @type {WalletState} */
52
- #state;
53
- /** @type {Function} */
54
- #onStateUpdate;
55
- /** @type {string} */
56
- #callbackUrl;
57
- /** @type {string} */
58
- static defaultWidgetUrl = "https://wallet-adapter.fastnear.com";
59
- /**
60
- * @param {WalletAdapterConfig} [config]
61
- */
62
- constructor({
63
- widgetUrl = _WalletAdapter.defaultWidgetUrl,
64
- targetOrigin = "*",
65
- onStateUpdate,
66
- lastState,
67
- callbackUrl = window.location.href
68
- } = {}) {
69
- this.#targetOrigin = targetOrigin;
70
- this.#widgetUrl = widgetUrl;
71
- this.#onStateUpdate = onStateUpdate;
72
- this.#callbackUrl = callbackUrl;
73
- this.#state = lastState || {};
74
- window.addEventListener("message", this.#handleMessage.bind(this));
75
- }
76
- /**
77
- * Creates an iframe for wallet interaction
78
- * @param {string} path - Path to load in iframe
79
- * @returns {HTMLIFrameElement}
80
- */
81
- #createIframe(path) {
82
- if (this.#iframe) {
83
- this.#iframe.remove();
84
- }
85
- const url = new URL(path, this.#widgetUrl);
86
- const iframe = document.createElement("iframe");
87
- iframe.src = url.toString();
88
- iframe.allow = "usb";
89
- iframe.style.border = "none";
90
- iframe.style.zIndex = "10000";
91
- iframe.style.position = "fixed";
92
- iframe.style.display = "block";
93
- iframe.style.top = "0";
94
- iframe.style.left = "0";
95
- iframe.style.width = "100%";
96
- iframe.style.height = "100%";
97
- document.body.appendChild(iframe);
98
- this.#iframe = iframe;
99
- return iframe;
100
- }
101
- /**
102
- * Handles messages from the wallet widget
103
- * @param {MessageEvent} event
104
- */
105
- #handleMessage(event) {
106
- if (this.#targetOrigin !== "*" && event.origin !== this.#targetOrigin) {
107
- return;
108
- }
109
- const { id, type, action, payload } = event.data;
110
- if (type !== "wallet-adapter") return;
111
- if (action === "close") {
112
- this.#iframe?.remove();
113
- this.#iframe = null;
114
- return;
115
- }
116
- if (payload?.state) {
117
- this.#state = { ...this.#state, ...payload.state };
118
- this.#onStateUpdate?.(this.#state);
119
- }
120
- const resolve = this.#pending.get(id);
121
- if (resolve) {
122
- this.#pending.delete(id);
123
- this.#iframe?.remove();
124
- this.#iframe = null;
125
- resolve(payload);
126
- }
127
- }
128
- /**
129
- * Sends a message to the wallet widget
130
- * @param {string} path - Path to load in iframe
131
- * @param {string} method - Method to call
132
- * @param {Object} params - Parameters to pass
133
- * @returns {Promise<any>}
134
- */
135
- async #sendMessage(path, method, params) {
136
- return new Promise((resolve) => {
137
- const id = Math.random().toString(36).slice(2);
138
- this.#pending.set(id, resolve);
139
- const iframe = this.#createIframe(path);
140
- iframe.onload = () => {
141
- iframe.contentWindow?.postMessage(
142
- {
143
- type: "wallet-adapter",
144
- method,
145
- params: {
146
- id,
147
- ...params,
148
- state: this.#state,
149
- callbackUrl: params.callbackUrl || this.#callbackUrl
150
- }
151
- },
152
- this.#targetOrigin
153
- );
154
- };
155
- });
156
- }
157
- /**
158
- * Get current wallet state
159
- * @returns {WalletState}
160
- */
161
- getState() {
162
- return { ...this.#state };
163
- }
164
- /**
165
- * Set current wallet state
166
- * @param state
167
- */
168
- setState(state) {
169
- this.#state = state;
170
- }
171
- /**
172
- * Sign in with a NEAR wallet
173
- * @param {SignInConfig} config
174
- * @returns {Promise<SignInResult>}
175
- */
176
- async signIn(config) {
177
- return this.#sendMessage("/login.html", "signIn", config);
178
- }
179
- /**
180
- * Send a transaction using connected wallet
181
- * @param {TransactionConfig} config
182
- * @returns {Promise<TransactionResult>}
183
- */
184
- async sendTransactions(config) {
185
- return this.#sendMessage("/send.html", "sendTransactions", config);
186
- }
187
- /**
188
- * Clean up adapter resources
189
- */
190
- destroy() {
191
- window.removeEventListener("message", this.#handleMessage);
192
- this.#iframe?.remove();
193
- this.#iframe = null;
194
- }
195
- };
196
-
197
- // src/cryptoUtils.ts
198
- var import_ed25519 = require("@noble/curves/ed25519");
199
- var import_sha2 = require("@noble/hashes/sha2");
200
-
201
- // src/utils.ts
202
- var import_base58_js = require("base58-js");
203
- var import_big = __toESM(require("big.js"), 1);
204
- var import_js_base64 = require("js-base64");
205
- var LsPrefix = "__fastnear_";
206
- function toBase64(data) {
207
- if (typeof data === "string") {
208
- return (0, import_js_base64.encode)(data);
209
- } else {
210
- const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
211
- const str = String.fromCharCode(...bytes);
212
- return (0, import_js_base64.encode)(str);
213
- }
214
- }
215
- function fromBase64(str) {
216
- const binaryString = (0, import_js_base64.decode)(str);
217
- const len = binaryString.length;
218
- const bytes = new Uint8Array(len);
219
- for (let i = 0; i < len; i++) {
220
- bytes[i] = binaryString.charCodeAt(i);
221
- }
222
- return bytes;
223
- }
224
- function lsSet(key, value) {
225
- if (value === null || value === void 0) {
226
- localStorage.removeItem(LsPrefix + key);
227
- } else {
228
- localStorage.setItem(LsPrefix + key, JSON.stringify(value));
229
- }
230
- }
231
- function lsGet(key) {
232
- const value = localStorage.getItem(LsPrefix + key);
233
- return tryParseJson(value, null);
234
- }
235
- function tryParseJson(...args) {
236
- try {
237
- return JSON.parse(args[0]);
238
- } catch {
239
- if (args.length > 1) {
240
- return args[1];
241
- }
242
- return args[0];
243
- }
244
- }
245
- function canSignWithLAK(actions) {
246
- return actions.length === 1 && actions[0].type === "FunctionCall" && (0, import_big.default)(actions[0]?.deposit ?? "0").eq(0);
247
- }
248
-
249
- // src/cryptoUtils.ts
250
- var keyFromString = (key) => (0, import_base58_js.base58_to_binary)(
251
- key.includes(":") ? (() => {
252
- const [curve, keyPart] = key.split(":");
253
- if (curve !== "ed25519") {
254
- throw new Error(`Unsupported curve: ${curve}`);
255
- }
256
- return keyPart;
257
- })() : key
258
- );
259
- var keyToString = (key) => `ed25519:${(0, import_base58_js.binary_to_base58)(key)}`;
260
- function publicKeyFromPrivate(privateKey) {
261
- privateKey = keyFromString(privateKey).slice(0, 32);
262
- const publicKey = import_ed25519.ed25519.getPublicKey(privateKey);
263
- return keyToString(publicKey);
264
- }
265
- function privateKeyFromRandom() {
266
- const privateKey = crypto.getRandomValues(new Uint8Array(64));
267
- return keyToString(privateKey);
268
- }
269
- function signHash(hash, privateKey) {
270
- privateKey = keyFromString(privateKey).slice(0, 32);
271
- const signature = import_ed25519.ed25519.sign((0, import_base58_js.base58_to_binary)(hash), privateKey);
272
- return (0, import_base58_js.binary_to_base58)(signature);
273
- }
274
-
275
- // src/transaction.ts
276
- var import_borsh = require("borsh");
277
- function mapTransaction(jsonTransaction) {
278
- return {
279
- signerId: jsonTransaction.signerId,
280
- publicKey: {
281
- ed25519Key: {
282
- data: keyFromString(jsonTransaction.publicKey)
283
- }
284
- },
285
- nonce: BigInt(jsonTransaction.nonce),
286
- receiverId: jsonTransaction.receiverId,
287
- blockHash: (0, import_base58_js.base58_to_binary)(jsonTransaction.blockHash),
288
- actions: jsonTransaction.actions.map(mapAction)
289
- };
290
- }
291
- function serializeTransaction(jsonTransaction) {
292
- const transaction = mapTransaction(jsonTransaction);
293
- return (0, import_borsh.serialize)(SCHEMA.Transaction, transaction);
294
- }
295
- function serializeSignedTransaction(jsonTransaction, signature) {
296
- const signedTransaction = {
297
- transaction: mapTransaction(jsonTransaction),
298
- signature: {
299
- ed25519Signature: {
300
- data: (0, import_base58_js.base58_to_binary)(signature)
301
- }
302
- }
303
- };
304
- return (0, import_borsh.serialize)(SCHEMA.SignedTransaction, signedTransaction);
305
- }
306
- function mapAction(action) {
307
- switch (action.type) {
308
- case "CreateAccount": {
309
- return {
310
- createAccount: {}
311
- };
312
- }
313
- case "DeployContract": {
314
- return {
315
- deployContract: {
316
- code: fromBase64(action.codeBase64)
317
- }
318
- };
319
- }
320
- case "FunctionCall": {
321
- return {
322
- functionCall: {
323
- methodName: action.methodName,
324
- args: action.argsBase64 ? fromBase64(action.argsBase64) : new TextEncoder().encode(JSON.stringify(action.args)),
325
- gas: BigInt(action.gas),
326
- deposit: BigInt(action.deposit)
327
- }
328
- };
329
- }
330
- case "Transfer": {
331
- return {
332
- transfer: {
333
- deposit: BigInt(action.deposit)
334
- }
335
- };
336
- }
337
- case "Stake": {
338
- return {
339
- stake: {
340
- stake: BigInt(action.stake),
341
- publicKey: {
342
- ed25519Key: {
343
- data: keyFromString(action.publicKey)
344
- }
345
- }
346
- }
347
- };
348
- }
349
- case "AddKey": {
350
- return {
351
- addKey: {
352
- publicKey: {
353
- ed25519Key: {
354
- data: keyFromString(action.publicKey)
355
- }
356
- },
357
- accessKey: {
358
- nonce: BigInt(action.accessKey.nonce),
359
- permission: action.accessKey.permission === "FullAccess" ? { fullAccess: {} } : {
360
- functionCall: {
361
- allowance: action.accessKey.allowance ? BigInt(action.accessKey.allowance) : null,
362
- receiverId: action.accessKey.receiverId,
363
- methodNames: action.accessKey.methodNames
364
- }
365
- }
366
- }
367
- }
368
- };
369
- }
370
- case "DeleteKey": {
371
- return {
372
- deleteKey: {
373
- publicKey: {
374
- ed25519Key: {
375
- data: keyFromString(action.publicKey)
376
- }
377
- }
378
- }
379
- };
380
- }
381
- case "DeleteAccount": {
382
- return {
383
- deleteAccount: {
384
- beneficiaryId: action.beneficiaryId
385
- }
386
- };
387
- }
388
- case "SignedDelegate": {
389
- return {
390
- signedDelegate: {
391
- delegateAction: mapAction(action.delegateAction),
392
- signature: {
393
- ed25519Signature: (0, import_base58_js.base58_to_binary)(action.signature)
394
- }
395
- }
396
- };
397
- }
398
- default: {
399
- throw new Error("Not implemented action: " + action.type);
400
- }
401
- }
402
- }
403
- var SCHEMA = new class BorshSchema {
404
- Ed25519Signature = {
405
- struct: {
406
- data: { array: { type: "u8", len: 64 } }
407
- }
408
- };
409
- Secp256k1Signature = {
410
- struct: {
411
- data: { array: { type: "u8", len: 65 } }
412
- }
413
- };
414
- Signature = {
415
- enum: [
416
- { struct: { ed25519Signature: this.Ed25519Signature } },
417
- { struct: { secp256k1Signature: this.Secp256k1Signature } }
418
- ]
419
- };
420
- Ed25519Data = {
421
- struct: {
422
- data: { array: { type: "u8", len: 32 } }
423
- }
424
- };
425
- Secp256k1Data = {
426
- struct: {
427
- data: { array: { type: "u8", len: 64 } }
428
- }
429
- };
430
- PublicKey = {
431
- enum: [
432
- { struct: { ed25519Key: this.Ed25519Data } },
433
- { struct: { secp256k1Key: this.Secp256k1Data } }
434
- ]
435
- };
436
- FunctionCallPermission = {
437
- struct: {
438
- allowance: { option: "u128" },
439
- receiverId: "string",
440
- methodNames: { array: { type: "string" } }
441
- }
442
- };
443
- FullAccessPermission = {
444
- struct: {}
445
- };
446
- AccessKeyPermission = {
447
- enum: [
448
- { struct: { functionCall: this.FunctionCallPermission } },
449
- { struct: { fullAccess: this.FullAccessPermission } }
450
- ]
451
- };
452
- AccessKey = {
453
- struct: {
454
- nonce: "u64",
455
- permission: this.AccessKeyPermission
456
- }
457
- };
458
- CreateAccount = {
459
- struct: {}
460
- };
461
- DeployContract = {
462
- struct: {
463
- code: { array: { type: "u8" } }
464
- }
465
- };
466
- FunctionCall = {
467
- struct: {
468
- methodName: "string",
469
- args: { array: { type: "u8" } },
470
- gas: "u64",
471
- deposit: "u128"
472
- }
473
- };
474
- Transfer = {
475
- struct: {
476
- deposit: "u128"
477
- }
478
- };
479
- Stake = {
480
- struct: {
481
- stake: "u128",
482
- publicKey: this.PublicKey
483
- }
484
- };
485
- AddKey = {
486
- struct: {
487
- publicKey: this.PublicKey,
488
- accessKey: this.AccessKey
489
- }
490
- };
491
- DeleteKey = {
492
- struct: {
493
- publicKey: this.PublicKey
494
- }
495
- };
496
- DeleteAccount = {
497
- struct: {
498
- beneficiaryId: "string"
499
- }
500
- };
501
- ClassicAction = {
502
- enum: [
503
- { struct: { createAccount: this.CreateAccount } },
504
- { struct: { deployContract: this.DeployContract } },
505
- { struct: { functionCall: this.FunctionCall } },
506
- { struct: { transfer: this.Transfer } },
507
- { struct: { stake: this.Stake } },
508
- { struct: { addKey: this.AddKey } },
509
- { struct: { deleteKey: this.DeleteKey } },
510
- { struct: { deleteAccount: this.DeleteAccount } }
511
- ]
512
- };
513
- DelegateAction = {
514
- struct: {
515
- senderId: "string",
516
- receiverId: "string",
517
- actions: { array: { type: this.ClassicAction } },
518
- nonce: "u64",
519
- maxBlockHeight: "u64",
520
- publicKey: this.PublicKey
521
- }
522
- };
523
- SignedDelegate = {
524
- struct: {
525
- delegateAction: this.DelegateAction,
526
- signature: this.Signature
527
- }
528
- };
529
- Action = {
530
- enum: [
531
- { struct: { createAccount: this.CreateAccount } },
532
- { struct: { deployContract: this.DeployContract } },
533
- { struct: { functionCall: this.FunctionCall } },
534
- { struct: { transfer: this.Transfer } },
535
- { struct: { stake: this.Stake } },
536
- { struct: { addKey: this.AddKey } },
537
- { struct: { deleteKey: this.DeleteKey } },
538
- { struct: { deleteAccount: this.DeleteAccount } },
539
- { struct: { signedDelegate: this.SignedDelegate } }
540
- ]
541
- };
542
- Transaction = {
543
- struct: {
544
- signerId: "string",
545
- publicKey: this.PublicKey,
546
- nonce: "u64",
547
- receiverId: "string",
548
- blockHash: { array: { type: "u8", len: 32 } },
549
- actions: { array: { type: this.Action } }
550
- }
551
- };
552
- SignedTransaction = {
553
- struct: {
554
- transaction: this.Transaction,
555
- signature: this.Signature
556
- }
557
- };
558
- }();
559
-
560
- // src/near.ts
561
- import_big2.default.DP = 27;
562
- var MaxBlockDelayMs = 1e3 * 60 * 60 * 6;
563
- var WIDGET_URL = "http://localhost:3000/";
564
- var DEFAULT_NETWORK_ID = "mainnet";
565
- var NETWORKS = {
566
- testnet: {
567
- networkId: "testnet",
568
- nodeUrl: "https://rpc.testnet.fastnear.com/"
569
- },
570
- mainnet: {
571
- networkId: "mainnet",
572
- nodeUrl: "https://rpc.mainnet.fastnear.com/"
573
- }
574
- };
575
- var _config = lsGet("config") || { ...NETWORKS[DEFAULT_NETWORK_ID] };
576
- var _state = lsGet("state") || {};
577
- try {
578
- _state.publicKey = _state.privateKey ? publicKeyFromPrivate(_state.privateKey) : null;
579
- } catch (e) {
580
- console.error("Error parsing private key:", e);
581
- _state.privateKey = null;
582
- lsSet("nonce", null);
583
- }
584
- var _txHistory = lsGet("txHistory") || {};
585
- var _eventListeners = {
586
- account: /* @__PURE__ */ new Set(),
587
- tx: /* @__PURE__ */ new Set()
588
- };
589
- var _unbroadcastedEvents = {
590
- account: [],
591
- tx: []
592
- };
593
- function getWalletAdapterState() {
594
- return {
595
- publicKey: _state.publicKey,
596
- accountId: _state.accountId,
597
- lastWalletId: _state.lastWalletId,
598
- networkId: DEFAULT_NETWORK_ID
599
- };
600
- }
601
- var _adapter;
602
- function updateState(newState) {
603
- const oldState = _state;
604
- _state = { ..._state, ...newState };
605
- lsSet("state", {
606
- accountId: _state.accountId,
607
- privateKey: _state.privateKey,
608
- lastWalletId: _state.lastWalletId,
609
- accessKeyContractId: _state.accessKeyContractId
610
- });
611
- if (newState.hasOwnProperty("privateKey") && newState.privateKey !== oldState.privateKey) {
612
- _state.publicKey = newState.privateKey ? publicKeyFromPrivate(newState.privateKey) : null;
613
- lsSet("nonce", null);
614
- }
615
- if (newState.accountId !== oldState.accountId) {
616
- notifyAccountListeners(newState.accountId);
617
- }
618
- if (newState.hasOwnProperty("lastWalletId") && newState.lastWalletId !== oldState.lastWalletId || newState.hasOwnProperty("accountId") && newState.accountId !== oldState.accountId || newState.hasOwnProperty("privateKey") && newState.privateKey !== oldState.privateKey) {
619
- _adapter.setState(getWalletAdapterState());
620
- }
621
- }
622
- function updateTxHistory(txStatus) {
623
- const txId = txStatus.txId;
624
- _txHistory[txId] = {
625
- ..._txHistory[txId] ?? {},
626
- ...txStatus,
627
- updateTimestamp: Date.now()
628
- };
629
- lsSet("txHistory", _txHistory);
630
- notifyTxListeners(_txHistory[txId]);
631
- }
632
- function onAdapterStateUpdate(state) {
633
- console.log("Adapter state update:", state);
634
- const { accountId, lastWalletId, privateKey } = state;
635
- updateState({
636
- accountId,
637
- lastWalletId,
638
- ...privateKey && { privateKey }
639
- });
640
- }
641
- _adapter = new WalletAdapter({
642
- onStateUpdate: onAdapterStateUpdate,
643
- lastState: getWalletAdapterState(),
644
- widgetUrl: WIDGET_URL
645
- });
646
- function parseJsonFromBytes(bytes) {
647
- try {
648
- const decoder = new TextDecoder();
649
- return JSON.parse(decoder.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)));
650
- } catch (e) {
651
- try {
652
- return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
653
- } catch (e2) {
654
- return bytes;
655
- }
656
- }
657
- }
658
- function withBlockId(params, blockId) {
659
- return blockId === "final" || blockId === "optimistic" ? { ...params, finality: blockId } : blockId ? { ...params, block_id: blockId } : { ...params, finality: "optimistic" };
660
- }
661
- async function queryRpc(method, params) {
662
- const response = await fetch(_config.nodeUrl, {
663
- method: "POST",
664
- headers: { "Content-Type": "application/json" },
665
- body: JSON.stringify({
666
- jsonrpc: "2.0",
667
- id: `fastnear-${Date.now()}`,
668
- method,
669
- params
670
- })
671
- });
672
- const result = await response.json();
673
- if (result.error) {
674
- throw new Error(JSON.stringify(result.error));
675
- }
676
- return result.result;
677
- }
678
- function afterTxSent(txId) {
679
- queryRpc("tx", {
680
- tx_hash: _txHistory[txId].txHash,
681
- sender_account_id: _txHistory[txId].tx.signerId,
682
- wait_until: "EXECUTED_OPTIMISTIC"
683
- }).then((result) => {
684
- const successValue = result?.status?.SuccessValue;
685
- updateTxHistory({
686
- txId,
687
- status: "Executed",
688
- result,
689
- successValue: successValue ? tryParseJson(fromBase64(successValue)) : void 0,
690
- finalState: true
691
- });
692
- }).catch((error) => {
693
- updateTxHistory({
694
- txId,
695
- status: "ErrorAfterIncluded",
696
- error: tryParseJson(error.message),
697
- finalState: true
698
- });
699
- });
700
- }
701
- function sendTxToRpc(signedTxBase64, waitUntil, txId) {
702
- queryRpc("send_tx", {
703
- signed_tx_base64: signedTxBase64,
704
- wait_until: waitUntil ?? "INCLUDED"
705
- }).then((result) => {
706
- console.log("Transaction included:", result);
707
- updateTxHistory({
708
- txId,
709
- status: "Included",
710
- finalState: false
711
- });
712
- afterTxSent(txId);
713
- }).catch((error) => {
714
- updateTxHistory({
715
- txId,
716
- status: "Error",
717
- error: tryParseJson(error.message),
718
- finalState: false
719
- });
720
- });
721
- }
722
- function notifyAccountListeners(accountId) {
723
- if (_eventListeners.account.size === 0) {
724
- _unbroadcastedEvents.account.push(accountId);
725
- return;
726
- }
727
- _eventListeners.account.forEach((callback) => {
728
- try {
729
- callback(accountId);
730
- } catch (e) {
731
- console.error(e);
732
- }
733
- });
734
- }
735
- function notifyTxListeners(tx) {
736
- if (_eventListeners.tx.size === 0) {
737
- _unbroadcastedEvents.tx.push(tx);
738
- return;
739
- }
740
- _eventListeners.tx.forEach((callback) => {
741
- try {
742
- callback(tx);
743
- } catch (e) {
744
- console.error(e);
745
- }
746
- });
747
- }
748
- function convertUnit(s, ...args) {
749
- if (Array.isArray(s)) {
750
- s = s.reduce((acc, part, i) => {
751
- return acc + (args[i - 1] ?? "") + part;
752
- });
753
- }
754
- if (typeof s == "string") {
755
- const match = s.match(/([0-9.,_]+)\s*([a-zA-Z]+)?/);
756
- if (match) {
757
- const amount = match[1].replace(/[_,]/g, "");
758
- const unitPart = match[2];
759
- if (unitPart) {
760
- switch (unitPart.toLowerCase()) {
761
- case "near":
762
- return (0, import_big2.default)(amount).mul((0, import_big2.default)(10).pow(24)).toFixed(0);
763
- case "tgas":
764
- return (0, import_big2.default)(amount).mul((0, import_big2.default)(10).pow(12)).toFixed(0);
765
- case "ggas":
766
- return (0, import_big2.default)(amount).mul((0, import_big2.default)(10).pow(9)).toFixed(0);
767
- case "gas":
768
- case "yoctonear":
769
- return (0, import_big2.default)(amount).toFixed(0);
770
- default:
771
- throw new Error(`Unknown unit: ${unitPart}`);
772
- }
773
- } else {
774
- return (0, import_big2.default)(amount).toFixed(0);
775
- }
776
- }
777
- }
778
- return (0, import_big2.default)(s).toFixed(0);
779
- }
780
- var api = {
781
- // Context
782
- get accountId() {
783
- return _state.accountId;
784
- },
785
- get publicKey() {
786
- return _state.publicKey;
787
- },
788
- config(newConfig) {
789
- if (newConfig) {
790
- if (newConfig.networkId && _config.networkId !== newConfig.networkId) {
791
- _config = { ...NETWORKS[newConfig.networkId] };
792
- updateState({
793
- accountId: null,
794
- privateKey: null,
795
- lastWalletId: null
796
- });
797
- lsSet("block", null);
798
- _txHistory = {};
799
- lsSet("txHistory", _txHistory);
800
- }
801
- _config = { ..._config, ...newConfig };
802
- lsSet("config", _config);
803
- }
804
- return _config;
805
- },
806
- get authStatus() {
807
- if (!_state.accountId) {
808
- return "SignedOut";
809
- }
810
- const accessKey = _state.publicKey;
811
- const contractId = _state.accessKeyContractId;
812
- if (accessKey && contractId && _state.privateKey) {
813
- return {
814
- type: "SignedInWithLimitedAccessKey",
815
- accessKey,
816
- contractId
817
- };
818
- }
819
- return "SignedIn";
820
- },
821
- // Query Methods
822
- async view({
823
- contractId,
824
- methodName,
825
- args,
826
- argsBase64,
827
- blockId
828
- }) {
829
- const encodedArgs = argsBase64 || (args ? toBase64(JSON.stringify(args)) : "");
830
- const result = await queryRpc(
831
- "query",
832
- withBlockId(
833
- {
834
- request_type: "call_function",
835
- account_id: contractId,
836
- method_name: methodName,
837
- args_base64: encodedArgs
838
- },
839
- blockId
840
- )
841
- );
842
- return parseJsonFromBytes(result.result);
843
- },
844
- async account({
845
- accountId,
846
- blockId
847
- }) {
848
- return queryRpc(
849
- "query",
850
- withBlockId(
851
- {
852
- request_type: "view_account",
853
- account_id: accountId
854
- },
855
- blockId
856
- )
857
- );
858
- },
859
- async block({ blockId }) {
860
- return queryRpc("block", withBlockId({}, blockId));
861
- },
862
- async accessKey({
863
- accountId,
864
- publicKey,
865
- blockId
866
- }) {
867
- return queryRpc(
868
- "query",
869
- withBlockId(
870
- {
871
- request_type: "view_access_key",
872
- account_id: accountId,
873
- public_key: publicKey
874
- },
875
- blockId
876
- )
877
- );
878
- },
879
- async tx({ txHash, accountId }) {
880
- return queryRpc("tx", [txHash, accountId]);
881
- },
882
- localTxHistory() {
883
- return [..._txHistory];
884
- },
885
- // Transaction Methods
886
- async sendTx({
887
- receiverId,
888
- actions,
889
- waitUntil
890
- }) {
891
- const signerId = _state.accountId;
892
- if (!signerId) {
893
- throw new Error("Not signed in");
894
- }
895
- const publicKey = _state.publicKey;
896
- const privateKey = _state.privateKey;
897
- const txId = `tx-${Date.now()}-${Math.random()}`;
898
- if (!privateKey || receiverId !== _state.accessKeyContractId || !canSignWithLAK(actions)) {
899
- const jsonTransaction2 = {
900
- signerId,
901
- receiverId,
902
- actions
903
- };
904
- updateTxHistory({
905
- status: "Pending",
906
- txId,
907
- tx: jsonTransaction2,
908
- finalState: false
909
- });
910
- const url = new URL(typeof window !== "undefined" ? window.location.href : "");
911
- url.searchParams.set("txIds", txId);
912
- _adapter.sendTransactions({
913
- transactions: [jsonTransaction2],
914
- callbackUrl: url.toString()
915
- }).then((result) => {
916
- console.log("Transaction result:", result);
917
- if (result.url) {
918
- console.log("Redirecting to wallet:", result.url);
919
- if (typeof window !== "undefined") {
920
- setTimeout(() => {
921
- window.location.href = result.url;
922
- }, 100);
923
- }
924
- } else if (result.outcomes) {
925
- result.outcomes.forEach((r) => {
926
- updateTxHistory({
927
- txId,
928
- status: "Executed",
929
- result: r,
930
- txHash: r.transaction.hash,
931
- finalState: true
932
- });
933
- });
934
- } else if (result.rejected) {
935
- updateTxHistory({
936
- txId,
937
- status: "RejectedByUser",
938
- finalState: true
939
- });
940
- } else if (result.error) {
941
- updateTxHistory({
942
- txId,
943
- status: "Error",
944
- error: tryParseJson(result.error),
945
- finalState: true
946
- });
947
- }
948
- }).catch((error) => {
949
- updateTxHistory({
950
- txId,
951
- status: "Error",
952
- error: tryParseJson(error.message),
953
- finalState: true
954
- });
955
- });
956
- return txId;
957
- }
958
- let nonce = lsGet("nonce");
959
- let block = lsGet("block");
960
- const toDoPromises = {};
961
- if (nonce === null || nonce === void 0) {
962
- toDoPromises.nonce = api.accessKey({
963
- accountId: signerId,
964
- publicKey
965
- }).then((accessKey) => {
966
- if (accessKey.error) {
967
- throw new Error(`Access key error: ${accessKey.error}`);
968
- }
969
- lsSet("nonce", accessKey.nonce);
970
- return accessKey.nonce;
971
- });
972
- }
973
- if (!block || !block.header || parseFloat(block.header.timestamp_nanosec) / 1e6 + MaxBlockDelayMs < Date.now()) {
974
- toDoPromises.block = api.block({ blockId: "final" }).then((b) => {
975
- const newBlock = {
976
- header: {
977
- prev_hash: b.header.prev_hash,
978
- timestamp_nanosec: b.header.timestamp_nanosec
979
- }
980
- };
981
- lsSet("block", newBlock);
982
- return newBlock;
983
- });
984
- }
985
- if (Object.keys(toDoPromises).length > 0) {
986
- const results = await Promise.all(Object.values(toDoPromises));
987
- const keys = Object.keys(toDoPromises);
988
- results.forEach((res, i) => {
989
- if (keys[i] === "nonce") {
990
- nonce = res;
991
- } else if (keys[i] === "block") {
992
- block = res;
993
- }
994
- });
995
- }
996
- const newNonce = (nonce ?? 0) + 1;
997
- lsSet("nonce", newNonce);
998
- const blockHash = block.header.prev_hash;
999
- const jsonTransaction = {
1000
- signerId,
1001
- publicKey,
1002
- nonce: newNonce,
1003
- receiverId,
1004
- blockHash,
1005
- actions
1006
- };
1007
- console.log("Transaction:", jsonTransaction);
1008
- const transaction = serializeTransaction(jsonTransaction);
1009
- const txHash = (0, import_base58_js.binary_to_base58)(import_sha2.sha256(transaction));
1010
- const signature = signHash(txHash, privateKey);
1011
- const signedTransaction = serializeSignedTransaction(jsonTransaction, signature);
1012
- const signedTxBase64 = toBase64(signedTransaction);
1013
- updateTxHistory({
1014
- status: "Pending",
1015
- txId,
1016
- tx: jsonTransaction,
1017
- signature,
1018
- signedTxBase64,
1019
- txHash,
1020
- finalState: false
1021
- });
1022
- sendTxToRpc(signedTxBase64, waitUntil, txId);
1023
- return txId;
1024
- },
1025
- // Authentication Methods
1026
- async requestSignIn({ contractId }) {
1027
- const privateKey = privateKeyFromRandom();
1028
- updateState({
1029
- accessKeyContractId: contractId,
1030
- accountId: null,
1031
- privateKey
1032
- });
1033
- const publicKey = publicKeyFromPrivate(privateKey);
1034
- const result = await _adapter.signIn({
1035
- networkId: _config.networkId,
1036
- contractId,
1037
- publicKey
1038
- });
1039
- console.log("Sign in result:", result);
1040
- if (result.error) {
1041
- throw new Error(`Wallet error: ${result.error}`);
1042
- }
1043
- if (result.url) {
1044
- console.log("Redirecting to wallet:", result.url);
1045
- if (typeof window !== "undefined") {
1046
- setTimeout(() => {
1047
- window.location.href = result.url;
1048
- }, 100);
1049
- }
1050
- } else if (result.accountId) {
1051
- updateState({
1052
- accountId: result.accountId
1053
- });
1054
- }
1055
- },
1056
- signOut() {
1057
- updateState({
1058
- accountId: null,
1059
- privateKey: null,
1060
- contractId: null
1061
- });
1062
- },
1063
- // Event Handlers
1064
- onAccount(callback) {
1065
- _eventListeners.account.add(callback);
1066
- if (_unbroadcastedEvents.account.length > 0) {
1067
- const events = _unbroadcastedEvents.account;
1068
- _unbroadcastedEvents.account = [];
1069
- events.forEach(notifyAccountListeners);
1070
- }
1071
- },
1072
- onTx(callback) {
1073
- _eventListeners.tx.add(callback);
1074
- if (_unbroadcastedEvents.tx.length > 0) {
1075
- const events = _unbroadcastedEvents.tx;
1076
- _unbroadcastedEvents.tx = [];
1077
- events.forEach(notifyTxListeners);
1078
- }
1079
- },
1080
- // Action Helpers
1081
- actions: {
1082
- functionCall: ({
1083
- methodName,
1084
- gas,
1085
- deposit,
1086
- args,
1087
- argsBase64
1088
- }) => ({
1089
- type: "FunctionCall",
1090
- methodName,
1091
- args,
1092
- argsBase64,
1093
- gas,
1094
- deposit
1095
- }),
1096
- transfer: (yoctoAmount) => ({
1097
- type: "Transfer",
1098
- deposit: yoctoAmount
1099
- }),
1100
- stakeNEAR: ({ amount, publicKey }) => ({
1101
- type: "Stake",
1102
- stake: amount,
1103
- publicKey
1104
- }),
1105
- addFullAccessKey: ({ publicKey }) => ({
1106
- type: "AddKey",
1107
- publicKey,
1108
- accessKey: { permission: "FullAccess" }
1109
- }),
1110
- addLimitedAccessKey: ({
1111
- publicKey,
1112
- allowance,
1113
- accountId,
1114
- methodNames
1115
- }) => ({
1116
- type: "AddKey",
1117
- publicKey,
1118
- accessKey: {
1119
- permission: "FunctionCall",
1120
- allowance,
1121
- receiverId: accountId,
1122
- methodNames
1123
- }
1124
- }),
1125
- deleteKey: ({ publicKey }) => ({
1126
- type: "DeleteKey",
1127
- publicKey
1128
- }),
1129
- deleteAccount: ({ beneficiaryId }) => ({
1130
- type: "DeleteAccount",
1131
- beneficiaryId
1132
- }),
1133
- createAccount: () => ({
1134
- type: "CreateAccount"
1135
- }),
1136
- deployContract: ({ codeBase64 }) => ({
1137
- type: "DeployContract",
1138
- codeBase64
1139
- })
1140
- },
1141
- utils: {
1142
- toBase64,
1143
- fromBase64,
1144
- toBase58: import_base58_js.binary_to_base58,
1145
- fromBase58: import_base58_js.base58_to_binary
1146
- }
1147
- };
1148
- try {
1149
- if (typeof window !== "undefined") {
1150
- const url = new URL(window.location.href);
1151
- const accountId = url.searchParams.get("account_id");
1152
- const publicKey = url.searchParams.get("public_key");
1153
- const errorCode = url.searchParams.get("errorCode");
1154
- const errorMessage = url.searchParams.get("errorMessage");
1155
- const transactionHashes = url.searchParams.get("transactionHashes");
1156
- const txIds = url.searchParams.get("txIds");
1157
- if (errorCode || errorMessage) {
1158
- console.warn(new Error(`Wallet error: ${errorCode} ${errorMessage}`));
1159
- }
1160
- if (accountId && publicKey) {
1161
- if (publicKey === _state.publicKey) {
1162
- updateState({
1163
- accountId
1164
- });
1165
- } else {
1166
- console.error(
1167
- new Error("Public key mismatch from wallet redirect"),
1168
- publicKey,
1169
- _state.publicKey
1170
- );
1171
- }
1172
- }
1173
- if (transactionHashes || txIds) {
1174
- const txHashes = transactionHashes ? transactionHashes.split(",") : [];
1175
- const txIdsArray = txIds ? txIds.split(",") : [];
1176
- if (txIdsArray.length > txHashes.length) {
1177
- txIdsArray.forEach((txId, i) => {
1178
- updateTxHistory({
1179
- txId,
1180
- status: "RejectedByUser",
1181
- finalState: true
1182
- });
1183
- });
1184
- } else if (txIdsArray.length === txHashes.length) {
1185
- txIdsArray.forEach((txId, i) => {
1186
- updateTxHistory({
1187
- txId,
1188
- status: "PendingGotTxHash",
1189
- txHash: txHashes[i],
1190
- finalState: false
1191
- });
1192
- afterTxSent(txId);
1193
- });
1194
- } else {
1195
- console.error(
1196
- new Error("Transaction hash mismatch from wallet redirect"),
1197
- txIdsArray,
1198
- txHashes
1199
- );
1200
- }
1201
- }
1202
- url.searchParams.delete("account_id");
1203
- url.searchParams.delete("public_key");
1204
- url.searchParams.delete("errorCode");
1205
- url.searchParams.delete("errorMessage");
1206
- url.searchParams.delete("all_keys");
1207
- url.searchParams.delete("transactionHashes");
1208
- url.searchParams.delete("txIds");
1209
- window.history.replaceState({}, "", url.toString());
1210
- }
1211
- } catch (e) {
1212
- console.error("Error handling wallet redirect:", e);
1213
- }
1214
- // Annotate the CommonJS export names for ESM import in node:
1215
- 0 && (module.exports = {
1216
- $$,
1217
- near
1218
- });
1219
- //# sourceMappingURL=index.esm.js.map