@fastnear/api 0.1.0 → 0.3.0

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