@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
package/dist/cjs/near.js DELETED
@@ -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/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
- const match = s.match(/([0-9.,_]+)\s*([a-zA-Z]+)?/);
755
- if (match) {
756
- const amount = match[1].replace(/[_,]/g, "");
757
- const 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
- case "yoctonear":
768
- return (0, import_big2.default)(amount).toFixed(0);
769
- default:
770
- throw new Error(`Unknown unit: ${unitPart}`);
771
- }
772
- } else {
773
- return (0, import_big2.default)(amount).toFixed(0);
774
- }
775
- }
776
- }
777
- return (0, import_big2.default)(s).toFixed(0);
778
- }
779
- var api = {
780
- // Context
781
- get accountId() {
782
- return _state.accountId;
783
- },
784
- get publicKey() {
785
- return _state.publicKey;
786
- },
787
- config(newConfig) {
788
- if (newConfig) {
789
- if (newConfig.networkId && _config.networkId !== newConfig.networkId) {
790
- _config = { ...NETWORKS[newConfig.networkId] };
791
- updateState({
792
- accountId: null,
793
- privateKey: null,
794
- lastWalletId: null
795
- });
796
- lsSet("block", null);
797
- _txHistory = {};
798
- lsSet("txHistory", _txHistory);
799
- }
800
- _config = { ..._config, ...newConfig };
801
- lsSet("config", _config);
802
- }
803
- return _config;
804
- },
805
- get authStatus() {
806
- if (!_state.accountId) {
807
- return "SignedOut";
808
- }
809
- const accessKey = _state.publicKey;
810
- const contractId = _state.accessKeyContractId;
811
- if (accessKey && contractId && _state.privateKey) {
812
- return {
813
- type: "SignedInWithLimitedAccessKey",
814
- accessKey,
815
- contractId
816
- };
817
- }
818
- return "SignedIn";
819
- },
820
- // Query Methods
821
- async view({
822
- contractId,
823
- methodName,
824
- args,
825
- argsBase64,
826
- blockId
827
- }) {
828
- const encodedArgs = argsBase64 || (args ? toBase64(JSON.stringify(args)) : "");
829
- const result = await queryRpc(
830
- "query",
831
- withBlockId(
832
- {
833
- request_type: "call_function",
834
- account_id: contractId,
835
- method_name: methodName,
836
- args_base64: encodedArgs
837
- },
838
- blockId
839
- )
840
- );
841
- return parseJsonFromBytes(result.result);
842
- },
843
- async account({
844
- accountId,
845
- blockId
846
- }) {
847
- return queryRpc(
848
- "query",
849
- withBlockId(
850
- {
851
- request_type: "view_account",
852
- account_id: accountId
853
- },
854
- blockId
855
- )
856
- );
857
- },
858
- async block({ blockId }) {
859
- return queryRpc("block", withBlockId({}, blockId));
860
- },
861
- async accessKey({
862
- accountId,
863
- publicKey,
864
- blockId
865
- }) {
866
- return queryRpc(
867
- "query",
868
- withBlockId(
869
- {
870
- request_type: "view_access_key",
871
- account_id: accountId,
872
- public_key: publicKey
873
- },
874
- blockId
875
- )
876
- );
877
- },
878
- async tx({ txHash, accountId }) {
879
- return queryRpc("tx", [txHash, accountId]);
880
- },
881
- localTxHistory() {
882
- return [..._txHistory];
883
- },
884
- // Transaction Methods
885
- async sendTx({
886
- receiverId,
887
- actions,
888
- waitUntil
889
- }) {
890
- const signerId = _state.accountId;
891
- if (!signerId) {
892
- throw new Error("Not signed in");
893
- }
894
- const publicKey = _state.publicKey;
895
- const privateKey = _state.privateKey;
896
- const txId = `tx-${Date.now()}-${Math.random()}`;
897
- if (!privateKey || receiverId !== _state.accessKeyContractId || !canSignWithLAK(actions)) {
898
- const jsonTransaction2 = {
899
- signerId,
900
- receiverId,
901
- actions
902
- };
903
- updateTxHistory({
904
- status: "Pending",
905
- txId,
906
- tx: jsonTransaction2,
907
- finalState: false
908
- });
909
- const url = new URL(typeof window !== "undefined" ? window.location.href : "");
910
- url.searchParams.set("txIds", txId);
911
- _adapter.sendTransactions({
912
- transactions: [jsonTransaction2],
913
- callbackUrl: url.toString()
914
- }).then((result) => {
915
- console.log("Transaction result:", result);
916
- if (result.url) {
917
- console.log("Redirecting to wallet:", result.url);
918
- if (typeof window !== "undefined") {
919
- setTimeout(() => {
920
- window.location.href = result.url;
921
- }, 100);
922
- }
923
- } else if (result.outcomes) {
924
- result.outcomes.forEach((r) => {
925
- updateTxHistory({
926
- txId,
927
- status: "Executed",
928
- result: r,
929
- txHash: r.transaction.hash,
930
- finalState: true
931
- });
932
- });
933
- } else if (result.rejected) {
934
- updateTxHistory({
935
- txId,
936
- status: "RejectedByUser",
937
- finalState: true
938
- });
939
- } else if (result.error) {
940
- updateTxHistory({
941
- txId,
942
- status: "Error",
943
- error: tryParseJson(result.error),
944
- finalState: true
945
- });
946
- }
947
- }).catch((error) => {
948
- updateTxHistory({
949
- txId,
950
- status: "Error",
951
- error: tryParseJson(error.message),
952
- finalState: true
953
- });
954
- });
955
- return txId;
956
- }
957
- let nonce = lsGet("nonce");
958
- let block = lsGet("block");
959
- const toDoPromises = {};
960
- if (nonce === null || nonce === void 0) {
961
- toDoPromises.nonce = api.accessKey({
962
- accountId: signerId,
963
- publicKey
964
- }).then((accessKey) => {
965
- if (accessKey.error) {
966
- throw new Error(`Access key error: ${accessKey.error}`);
967
- }
968
- lsSet("nonce", accessKey.nonce);
969
- return accessKey.nonce;
970
- });
971
- }
972
- if (!block || !block.header || parseFloat(block.header.timestamp_nanosec) / 1e6 + MaxBlockDelayMs < Date.now()) {
973
- toDoPromises.block = api.block({ blockId: "final" }).then((b) => {
974
- const newBlock = {
975
- header: {
976
- prev_hash: b.header.prev_hash,
977
- timestamp_nanosec: b.header.timestamp_nanosec
978
- }
979
- };
980
- lsSet("block", newBlock);
981
- return newBlock;
982
- });
983
- }
984
- if (Object.keys(toDoPromises).length > 0) {
985
- const results = await Promise.all(Object.values(toDoPromises));
986
- const keys = Object.keys(toDoPromises);
987
- results.forEach((res, i) => {
988
- if (keys[i] === "nonce") {
989
- nonce = res;
990
- } else if (keys[i] === "block") {
991
- block = res;
992
- }
993
- });
994
- }
995
- const newNonce = (nonce ?? 0) + 1;
996
- lsSet("nonce", newNonce);
997
- const blockHash = block.header.prev_hash;
998
- const jsonTransaction = {
999
- signerId,
1000
- publicKey,
1001
- nonce: newNonce,
1002
- receiverId,
1003
- blockHash,
1004
- actions
1005
- };
1006
- console.log("Transaction:", jsonTransaction);
1007
- const transaction = serializeTransaction(jsonTransaction);
1008
- const txHash = (0, import_base58_js.binary_to_base58)(import_sha2.sha256(transaction));
1009
- const signature = signHash(txHash, privateKey);
1010
- const signedTransaction = serializeSignedTransaction(jsonTransaction, signature);
1011
- const signedTxBase64 = toBase64(signedTransaction);
1012
- updateTxHistory({
1013
- status: "Pending",
1014
- txId,
1015
- tx: jsonTransaction,
1016
- signature,
1017
- signedTxBase64,
1018
- txHash,
1019
- finalState: false
1020
- });
1021
- sendTxToRpc(signedTxBase64, waitUntil, txId);
1022
- return txId;
1023
- },
1024
- // Authentication Methods
1025
- async requestSignIn({ contractId }) {
1026
- const privateKey = privateKeyFromRandom();
1027
- updateState({
1028
- accessKeyContractId: contractId,
1029
- accountId: null,
1030
- privateKey
1031
- });
1032
- const publicKey = publicKeyFromPrivate(privateKey);
1033
- const result = await _adapter.signIn({
1034
- networkId: _config.networkId,
1035
- contractId,
1036
- publicKey
1037
- });
1038
- console.log("Sign in result:", result);
1039
- if (result.error) {
1040
- throw new Error(`Wallet error: ${result.error}`);
1041
- }
1042
- if (result.url) {
1043
- console.log("Redirecting to wallet:", result.url);
1044
- if (typeof window !== "undefined") {
1045
- setTimeout(() => {
1046
- window.location.href = result.url;
1047
- }, 100);
1048
- }
1049
- } else if (result.accountId) {
1050
- updateState({
1051
- accountId: result.accountId
1052
- });
1053
- }
1054
- },
1055
- signOut() {
1056
- updateState({
1057
- accountId: null,
1058
- privateKey: null,
1059
- contractId: null
1060
- });
1061
- },
1062
- // Event Handlers
1063
- onAccount(callback) {
1064
- _eventListeners.account.add(callback);
1065
- if (_unbroadcastedEvents.account.length > 0) {
1066
- const events = _unbroadcastedEvents.account;
1067
- _unbroadcastedEvents.account = [];
1068
- events.forEach(notifyAccountListeners);
1069
- }
1070
- },
1071
- onTx(callback) {
1072
- _eventListeners.tx.add(callback);
1073
- if (_unbroadcastedEvents.tx.length > 0) {
1074
- const events = _unbroadcastedEvents.tx;
1075
- _unbroadcastedEvents.tx = [];
1076
- events.forEach(notifyTxListeners);
1077
- }
1078
- },
1079
- // Action Helpers
1080
- actions: {
1081
- functionCall: ({
1082
- methodName,
1083
- gas,
1084
- deposit,
1085
- args,
1086
- argsBase64
1087
- }) => ({
1088
- type: "FunctionCall",
1089
- methodName,
1090
- args,
1091
- argsBase64,
1092
- gas,
1093
- deposit
1094
- }),
1095
- transfer: (yoctoAmount) => ({
1096
- type: "Transfer",
1097
- deposit: yoctoAmount
1098
- }),
1099
- stakeNEAR: ({ amount, publicKey }) => ({
1100
- type: "Stake",
1101
- stake: amount,
1102
- publicKey
1103
- }),
1104
- addFullAccessKey: ({ publicKey }) => ({
1105
- type: "AddKey",
1106
- publicKey,
1107
- accessKey: { permission: "FullAccess" }
1108
- }),
1109
- addLimitedAccessKey: ({
1110
- publicKey,
1111
- allowance,
1112
- accountId,
1113
- methodNames
1114
- }) => ({
1115
- type: "AddKey",
1116
- publicKey,
1117
- accessKey: {
1118
- permission: "FunctionCall",
1119
- allowance,
1120
- receiverId: accountId,
1121
- methodNames
1122
- }
1123
- }),
1124
- deleteKey: ({ publicKey }) => ({
1125
- type: "DeleteKey",
1126
- publicKey
1127
- }),
1128
- deleteAccount: ({ beneficiaryId }) => ({
1129
- type: "DeleteAccount",
1130
- beneficiaryId
1131
- }),
1132
- createAccount: () => ({
1133
- type: "CreateAccount"
1134
- }),
1135
- deployContract: ({ codeBase64 }) => ({
1136
- type: "DeployContract",
1137
- codeBase64
1138
- })
1139
- },
1140
- utils: {
1141
- toBase64,
1142
- fromBase64,
1143
- toBase58: import_base58_js.binary_to_base58,
1144
- fromBase58: import_base58_js.base58_to_binary
1145
- }
1146
- };
1147
- try {
1148
- if (typeof window !== "undefined") {
1149
- const url = new URL(window.location.href);
1150
- const accountId = url.searchParams.get("account_id");
1151
- const publicKey = url.searchParams.get("public_key");
1152
- const errorCode = url.searchParams.get("errorCode");
1153
- const errorMessage = url.searchParams.get("errorMessage");
1154
- const transactionHashes = url.searchParams.get("transactionHashes");
1155
- const txIds = url.searchParams.get("txIds");
1156
- if (errorCode || errorMessage) {
1157
- console.warn(new Error(`Wallet error: ${errorCode} ${errorMessage}`));
1158
- }
1159
- if (accountId && publicKey) {
1160
- if (publicKey === _state.publicKey) {
1161
- updateState({
1162
- accountId
1163
- });
1164
- } else {
1165
- console.error(
1166
- new Error("Public key mismatch from wallet redirect"),
1167
- publicKey,
1168
- _state.publicKey
1169
- );
1170
- }
1171
- }
1172
- if (transactionHashes || txIds) {
1173
- const txHashes = transactionHashes ? transactionHashes.split(",") : [];
1174
- const txIdsArray = txIds ? txIds.split(",") : [];
1175
- if (txIdsArray.length > txHashes.length) {
1176
- txIdsArray.forEach((txId, i) => {
1177
- updateTxHistory({
1178
- txId,
1179
- status: "RejectedByUser",
1180
- finalState: true
1181
- });
1182
- });
1183
- } else if (txIdsArray.length === txHashes.length) {
1184
- txIdsArray.forEach((txId, i) => {
1185
- updateTxHistory({
1186
- txId,
1187
- status: "PendingGotTxHash",
1188
- txHash: txHashes[i],
1189
- finalState: false
1190
- });
1191
- afterTxSent(txId);
1192
- });
1193
- } else {
1194
- console.error(
1195
- new Error("Transaction hash mismatch from wallet redirect"),
1196
- txIdsArray,
1197
- txHashes
1198
- );
1199
- }
1200
- }
1201
- url.searchParams.delete("account_id");
1202
- url.searchParams.delete("public_key");
1203
- url.searchParams.delete("errorCode");
1204
- url.searchParams.delete("errorMessage");
1205
- url.searchParams.delete("all_keys");
1206
- url.searchParams.delete("transactionHashes");
1207
- url.searchParams.delete("txIds");
1208
- window.history.replaceState({}, "", url.toString());
1209
- }
1210
- } catch (e) {
1211
- console.error("Error handling wallet redirect:", e);
1212
- }
1213
- // Annotate the CommonJS export names for ESM import in node:
1214
- 0 && (module.exports = {
1215
- api,
1216
- convertUnit,
1217
- parseJsonFromBytes
1218
- });
1219
- //# sourceMappingURL=near.js.map