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