@fastnear/api 0.9.7 → 0.9.8

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.
@@ -1,4 +1,5 @@
1
1
  import * as borsh from 'borsh';
2
+ import { NEP413Message } from '@fastnear/utils';
2
3
 
3
4
  interface NetworkConfig {
4
5
  networkId: string;
@@ -14,6 +15,35 @@ interface TxStatus {
14
15
  [key: string]: any;
15
16
  }
16
17
  type TxHistory = Record<string, TxStatus>;
18
+ interface WalletProvider {
19
+ connect(options?: {
20
+ contractId?: string;
21
+ network?: string;
22
+ excludedWallets?: string[];
23
+ features?: Record<string, boolean>;
24
+ }): Promise<{
25
+ accountId: string;
26
+ } | null>;
27
+ restore?(options?: {
28
+ contractId?: string;
29
+ network?: string;
30
+ }): Promise<{
31
+ accountId: string;
32
+ } | null>;
33
+ disconnect(): Promise<void>;
34
+ sendTransaction(params: {
35
+ receiverId: string;
36
+ actions: any[];
37
+ signerId?: string;
38
+ }): Promise<any>;
39
+ signMessage?(params: {
40
+ message: string;
41
+ recipient: string;
42
+ nonce: Uint8Array;
43
+ }): Promise<any>;
44
+ accountId(): string | null;
45
+ isConnected(): boolean;
46
+ }
17
47
 
18
48
  declare const MaxBlockDelayMs: number;
19
49
  interface AccessKeyWithError {
@@ -23,16 +53,6 @@ interface AccessKeyWithError {
23
53
  error?: string;
24
54
  };
25
55
  }
26
- interface WalletTxResult {
27
- url?: string;
28
- outcomes?: Array<{
29
- transaction: {
30
- hash: string;
31
- };
32
- }>;
33
- rejected?: boolean;
34
- error?: string;
35
- }
36
56
  interface BlockView {
37
57
  result: {
38
58
  header: {
@@ -61,15 +81,6 @@ interface AccessKeyView {
61
81
  }
62
82
  /**
63
83
  * Generates a mock transaction ID.
64
- *
65
- * This function creates a pseudo-unique transaction ID for testing or
66
- * non-production use. It combines the current timestamp with a
67
- * random component for uniqueness.
68
- *
69
- * **Note:** This is not cryptographically secure and should not be used
70
- * for actual transaction processing.
71
- *
72
- * @returns {string} A mock transaction ID in the format `tx-{timestamp}-{random}`
73
84
  */
74
85
  declare function generateTxId(): string;
75
86
  declare const accountId: () => string | null | undefined;
@@ -87,8 +98,10 @@ declare const selected: () => {
87
98
  contract: string | null | undefined;
88
99
  publicKey: string | null | undefined;
89
100
  };
90
- declare const requestSignIn: ({ contractId }: {
91
- contractId: string;
101
+ declare const requestSignIn: ({ contractId, excludedWallets, features, }?: {
102
+ contractId?: string;
103
+ excludedWallets?: string[];
104
+ features?: Record<string, boolean>;
92
105
  }) => Promise<void>;
93
106
  declare const view: ({ contractId, methodName, args, argsBase64, blockId, }: {
94
107
  contractId: string;
@@ -114,12 +127,21 @@ declare const queryTx: ({ txHash, accountId }: {
114
127
  accountId: string;
115
128
  }) => Promise<any>;
116
129
  declare const localTxHistory: () => TxHistory;
117
- declare const signOut: () => void;
130
+ declare const signOut: () => Promise<void>;
118
131
  declare const sendTx: ({ receiverId, actions, waitUntil, }: {
119
132
  receiverId: string;
120
133
  actions: any[];
121
134
  waitUntil?: string;
122
135
  }) => Promise<any>;
136
+ /**
137
+ * Signs a NEP-413 message using the connected wallet.
138
+ */
139
+ declare const signMessage: (message: NEP413Message) => Promise<any>;
140
+ /**
141
+ * Set the wallet provider used by the API for signing and sending transactions.
142
+ * Automatically called in IIFE builds when globalThis.nearWallet is present.
143
+ */
144
+ declare const useWallet: (provider: WalletProvider) => void;
123
145
  declare const exp: {
124
146
  utils: {};
125
147
  borsh: {
@@ -230,4 +252,4 @@ declare const actions: {
230
252
  };
231
253
  };
232
254
 
233
- export { type AccessKeyView, type AccessKeyWithError, type BlockView, type LastKnownBlock, MaxBlockDelayMs, type WalletTxResult, accountId, actions, afterTxSent, authStatus, config, event, exp, generateTxId, getPublicKeyForContract, localTxHistory, publicKey, queryAccessKey, queryAccount, queryBlock, queryTx, requestSignIn, selected, sendRpc, sendTx, sendTxToRpc, signOut, state, utils, view, withBlockId };
255
+ export { type AccessKeyView, type AccessKeyWithError, type BlockView, type LastKnownBlock, MaxBlockDelayMs, accountId, actions, afterTxSent, authStatus, config, event, exp, generateTxId, getPublicKeyForContract, localTxHistory, publicKey, queryAccessKey, queryAccount, queryBlock, queryTx, requestSignIn, selected, sendRpc, sendTx, sendTxToRpc, signMessage, signOut, state, useWallet, utils, view, withBlockId };
package/dist/cjs/near.cjs CHANGED
@@ -52,8 +52,10 @@ __export(near_exports, {
52
52
  sendRpc: () => sendRpc,
53
53
  sendTx: () => sendTx,
54
54
  sendTxToRpc: () => sendTxToRpc,
55
+ signMessage: () => signMessage,
55
56
  signOut: () => signOut,
56
57
  state: () => state,
58
+ useWallet: () => useWallet,
57
59
  utils: () => utils,
58
60
  view: () => view,
59
61
  withBlockId: () => withBlockId
@@ -193,27 +195,28 @@ const selected = /* @__PURE__ */ __name(() => {
193
195
  publicKey: publicKey2
194
196
  };
195
197
  }, "selected");
196
- const requestSignIn = /* @__PURE__ */ __name(async ({ contractId }) => {
197
- const privateKey = (0, import_utils.privateKeyFromRandom)();
198
- (0, import_state.update)({ accessKeyContractId: contractId, accountId: null, privateKey });
199
- const pubKey = (0, import_utils.publicKeyFromPrivate)(privateKey);
200
- const result = await import_state._adapter.signIn({
201
- networkId: (0, import_state2.getConfig)().networkId,
198
+ const requestSignIn = /* @__PURE__ */ __name(async ({
199
+ contractId,
200
+ excludedWallets,
201
+ features
202
+ } = {}) => {
203
+ const provider = (0, import_state.getWalletProvider)();
204
+ if (!provider) {
205
+ throw new Error("No wallet provider set. Call useWallet() first or load the @fastnear/wallet IIFE bundle.");
206
+ }
207
+ if (provider.isConnected()) {
208
+ await provider.disconnect();
209
+ }
210
+ const result = await provider.connect({
202
211
  contractId,
203
- publicKey: pubKey
212
+ network: (0, import_state2.getConfig)().networkId,
213
+ excludedWallets,
214
+ features
204
215
  });
205
- if (result.error) {
206
- throw new Error(`Wallet error: ${result.error}`);
207
- }
208
- if (result.url) {
209
- if (typeof window !== "undefined") {
210
- setTimeout(() => {
211
- window.location.href = result.url;
212
- }, 100);
213
- }
214
- } else if (result.accountId) {
215
- (0, import_state.update)({ accountId: result.accountId });
216
+ if (!result) {
217
+ return;
216
218
  }
219
+ (0, import_state.update)({ accountId: result.accountId });
217
220
  }, "requestSignIn");
218
221
  const view = /* @__PURE__ */ __name(async ({
219
222
  contractId,
@@ -268,7 +271,11 @@ const queryTx = /* @__PURE__ */ __name(async ({ txHash, accountId: accountId2 })
268
271
  const localTxHistory = /* @__PURE__ */ __name(() => {
269
272
  return (0, import_state.getTxHistory)();
270
273
  }, "localTxHistory");
271
- const signOut = /* @__PURE__ */ __name(() => {
274
+ const signOut = /* @__PURE__ */ __name(async () => {
275
+ const provider = (0, import_state.getWalletProvider)();
276
+ if (provider?.isConnected()) {
277
+ await provider.disconnect();
278
+ }
272
279
  (0, import_state.update)({ accountId: null, privateKey: null, contractId: null });
273
280
  (0, import_state2.setConfig)(import_state.NETWORKS[import_state.DEFAULT_NETWORK_ID]);
274
281
  }, "signOut");
@@ -279,56 +286,36 @@ const sendTx = /* @__PURE__ */ __name(async ({
279
286
  }) => {
280
287
  const signerId = import_state._state.accountId;
281
288
  if (!signerId) throw new Error("Must sign in");
282
- const publicKey2 = import_state._state.publicKey ?? "";
289
+ const pubKey = import_state._state.publicKey ?? "";
283
290
  const privKey = import_state._state.privateKey;
284
291
  const txId = generateTxId();
285
292
  if (!privKey || receiverId !== import_state._state.accessKeyContractId || !(0, import_utils.canSignWithLAK)(actions2)) {
286
293
  const jsonTx = { signerId, receiverId, actions: actions2 };
287
294
  (0, import_state.updateTxHistory)({ status: "Pending", txId, tx: jsonTx, finalState: false });
288
- const url = new URL(typeof window !== "undefined" ? window.location.href : "");
289
- url.searchParams.set("txIds", txId);
290
- const existingParams = new URLSearchParams(window.location.search);
291
- existingParams.forEach((value, key) => {
292
- if (!url.searchParams.has(key)) {
293
- url.searchParams.set(key, value);
294
- }
295
- });
296
- url.searchParams.delete("errorCode");
297
- url.searchParams.delete("errorMessage");
298
295
  try {
299
- const result = await import_state._adapter.sendTransactions({
300
- transactions: [jsonTx],
301
- callbackUrl: url.toString()
302
- });
303
- if (result.url) {
304
- if (typeof window !== "undefined") {
305
- setTimeout(() => {
306
- window.location.href = result.url;
307
- }, 100);
308
- }
309
- } else if (result.outcomes?.length) {
296
+ const provider = (0, import_state.getWalletProvider)();
297
+ if (!provider?.isConnected()) {
298
+ throw new Error("Must sign in");
299
+ }
300
+ const result = await provider.sendTransaction(jsonTx);
301
+ if (!result) {
302
+ (0, import_state.updateTxHistory)({ txId, status: "RejectedByUser", finalState: true });
303
+ return { rejected: true };
304
+ }
305
+ if (result.outcomes?.length) {
310
306
  result.outcomes.forEach(
311
307
  (r) => (0, import_state.updateTxHistory)({
312
308
  txId,
313
309
  status: "Executed",
314
310
  result: r,
315
- txHash: r.transaction.hash,
311
+ txHash: r.transaction?.hash,
316
312
  finalState: true
317
313
  })
318
314
  );
319
- } else if (result.rejected) {
320
- (0, import_state.updateTxHistory)({ txId, status: "RejectedByUser", finalState: true });
321
- } else if (result.error) {
322
- (0, import_state.updateTxHistory)({
323
- txId,
324
- status: "Error",
325
- error: (0, import_utils.tryParseJson)(result.error),
326
- finalState: true
327
- });
328
315
  }
329
316
  return result;
330
317
  } catch (err) {
331
- console.error("fastnear: error sending tx using adapter:", err);
318
+ console.error("fastnear: error sending tx using wallet provider:", err);
332
319
  (0, import_state.updateTxHistory)({
333
320
  txId,
334
321
  status: "Error",
@@ -340,9 +327,9 @@ const sendTx = /* @__PURE__ */ __name(async ({
340
327
  }
341
328
  let nonce = (0, import_utils.lsGet)("nonce");
342
329
  if (nonce == null) {
343
- const accessKey = await queryAccessKey({ accountId: signerId, publicKey: publicKey2 });
330
+ const accessKey = await queryAccessKey({ accountId: signerId, publicKey: pubKey });
344
331
  if (accessKey.result.error) {
345
- throw new Error(`Access key error: ${accessKey.result.error} when attempting to get nonce for ${signerId} for public key ${publicKey2}`);
332
+ throw new Error(`Access key error: ${accessKey.result.error} when attempting to get nonce for ${signerId} for public key ${pubKey}`);
346
333
  }
347
334
  nonce = accessKey.result.nonce;
348
335
  (0, import_utils.lsSet)("nonce", nonce);
@@ -363,7 +350,7 @@ const sendTx = /* @__PURE__ */ __name(async ({
363
350
  const blockHash = lastKnownBlock.header.hash;
364
351
  const plainTransactionObj = {
365
352
  signerId,
366
- publicKey: publicKey2,
353
+ publicKey: pubKey,
367
354
  nonce,
368
355
  receiverId,
369
356
  blockHash,
@@ -390,6 +377,19 @@ const sendTx = /* @__PURE__ */ __name(async ({
390
377
  console.error("Error Sending Transaction:", error, plainTransactionObj, signedTxBase64);
391
378
  }
392
379
  }, "sendTx");
380
+ const signMessage = /* @__PURE__ */ __name(async (message) => {
381
+ const provider = (0, import_state.getWalletProvider)();
382
+ if (!provider?.isConnected()) {
383
+ throw new Error("Must sign in");
384
+ }
385
+ if (!provider.signMessage) {
386
+ throw new Error("Connected wallet does not support signMessage");
387
+ }
388
+ return provider.signMessage(message);
389
+ }, "signMessage");
390
+ const useWallet = /* @__PURE__ */ __name((provider) => {
391
+ (0, import_state.setWalletProvider)(provider);
392
+ }, "useWallet");
393
393
  const exp = {
394
394
  utils: {},
395
395
  // we will map this in a moment, giving keys, for IDE hints
@@ -406,61 +406,6 @@ for (const key in stateExports) {
406
406
  }
407
407
  const event = state["events"];
408
408
  delete state["events"];
409
- try {
410
- if (typeof window !== "undefined") {
411
- const url = new URL(window.location.href);
412
- const accId = url.searchParams.get("account_id");
413
- const pubKey = url.searchParams.get("public_key");
414
- const errCode = url.searchParams.get("errorCode");
415
- const errMsg = url.searchParams.get("errorMessage");
416
- const decodedErrMsg = errMsg ? decodeURIComponent(errMsg) : null;
417
- const txHashes = url.searchParams.get("transactionHashes");
418
- const txIds = url.searchParams.get("txIds");
419
- if (errCode || errMsg) {
420
- console.warn(new Error(`Wallet raises:
421
- code: ${errCode}
422
- message: ${decodedErrMsg}`));
423
- }
424
- if (accId && pubKey) {
425
- if (pubKey === import_state._state.publicKey) {
426
- (0, import_state.update)({ accountId: accId });
427
- } else {
428
- if (authStatus() === "SignedIn") {
429
- console.warn("Public key mismatch from wallet redirect", pubKey, import_state._state.publicKey);
430
- }
431
- url.searchParams.delete("public_key");
432
- }
433
- }
434
- if (txHashes || txIds) {
435
- const hashArr = txHashes ? txHashes.split(",") : [];
436
- const idArr = txIds ? txIds.split(",") : [];
437
- if (idArr.length > hashArr.length) {
438
- idArr.forEach((id) => {
439
- (0, import_state.updateTxHistory)({ txId: id, status: "RejectedByUser", finalState: true });
440
- });
441
- } else if (idArr.length === hashArr.length) {
442
- idArr.forEach((id, i) => {
443
- (0, import_state.updateTxHistory)({
444
- txId: id,
445
- status: "PendingGotTxHash",
446
- txHash: hashArr[i],
447
- finalState: false
448
- });
449
- afterTxSent(id);
450
- });
451
- } else {
452
- console.error(new Error("Transaction hash mismatch from wallet redirect"), idArr, hashArr);
453
- }
454
- }
455
- url.searchParams.delete("txIds");
456
- if (authStatus() === "SignedOut") {
457
- url.searchParams.delete("errorCode");
458
- url.searchParams.delete("errorMessage");
459
- }
460
- }
461
- } catch (e) {
462
- console.error("Error handling wallet redirect:", e);
463
- }
464
409
  const actions = {
465
410
  functionCall: /* @__PURE__ */ __name(({
466
411
  methodName,
@@ -544,8 +489,10 @@ const actions = {
544
489
  sendRpc,
545
490
  sendTx,
546
491
  sendTxToRpc,
492
+ signMessage,
547
493
  signOut,
548
494
  state,
495
+ useWallet,
549
496
  utils,
550
497
  view,
551
498
  withBlockId
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/near.ts"],"sourcesContent":["import Big from \"big.js\";\nimport {\n lsSet,\n lsGet,\n tryParseJson,\n fromBase64,\n toBase64,\n canSignWithLAK,\n toBase58,\n parseJsonFromBytes,\n signHash,\n publicKeyFromPrivate,\n privateKeyFromRandom,\n serializeTransaction,\n serializeSignedTransaction, bytesToBase64, PlainTransaction,\n} from \"@fastnear/utils\";\n\nimport {\n _adapter,\n _state,\n DEFAULT_NETWORK_ID,\n NETWORKS,\n getTxHistory,\n update,\n updateTxHistory,\n} from \"./state.js\";\n\nimport {\n getConfig,\n setConfig,\n resetTxHistory,\n} from \"./state.js\";\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport * as reExportAllUtils from \"@fastnear/utils\";\nimport * as stateExports from \"./state.js\";\n\nBig.DP = 27;\nexport const MaxBlockDelayMs = 1000 * 60 * 60 * 6; // 6 hours\n\nexport interface AccessKeyWithError {\n result: {\n nonce: number;\n permission?: any;\n error?: string;\n }\n}\n\nexport interface WalletTxResult {\n url?: string;\n outcomes?: Array<{ transaction: { hash: string } }>;\n rejected?: boolean;\n error?: string;\n}\n\nexport interface BlockView {\n result: {\n header: {\n hash: string;\n timestamp_nanosec: string;\n }\n }\n}\n\n// The structure it's saved to in storage\nexport interface LastKnownBlock {\n header: {\n hash: string;\n timestamp_nanosec: string;\n }\n}\n\nexport function withBlockId(params: Record<string, any>, blockId?: string) {\n if (blockId === \"final\" || blockId === \"optimistic\") {\n return { ...params, finality: blockId };\n }\n return blockId ? { ...params, block_id: blockId } : { ...params, finality: \"optimistic\" };\n}\n\nexport async function sendRpc(method: string, params: Record<string, any> | any[]) {\n const config = getConfig();\n if (!config?.nodeUrl) {\n throw new Error(\"fastnear: getConfig() returned invalid config: missing nodeUrl.\");\n }\n const response = await fetch(config.nodeUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: `fastnear-${Date.now()}`,\n method,\n params,\n }),\n });\n const result = await response.json();\n if (result.error) {\n throw new Error(JSON.stringify(result.error));\n }\n return result;\n}\n\nexport function afterTxSent(txId: string) {\n const txHistory = getTxHistory();\n sendRpc(\"tx\", {\n tx_hash: txHistory[txId]?.txHash,\n sender_account_id: txHistory[txId]?.tx?.signerId,\n wait_until: \"EXECUTED_OPTIMISTIC\",\n })\n .then( result => {\n const successValue = result?.result?.status?.SuccessValue;\n updateTxHistory({\n txId,\n status: \"Executed\",\n result,\n successValue: successValue ? tryParseJson(fromBase64(successValue)) : undefined,\n finalState: true,\n });\n })\n .catch((error) => {\n updateTxHistory({\n txId,\n status: \"ErrorAfterIncluded\",\n error: tryParseJson(error.message) ?? error.message,\n finalState: true,\n });\n });\n}\n\nexport async function sendTxToRpc(signedTxBase64: string, waitUntil: string | undefined, txId: string) {\n // default to \"INCLUDED\"\n // see options: https://docs.near.org/api/rpc/transactions#tx-status-result\n waitUntil = waitUntil || \"INCLUDED\";\n\n try {\n const sendTxRes = await sendRpc(\"send_tx\", {\n signed_tx_base64: signedTxBase64,\n wait_until: waitUntil,\n });\n\n updateTxHistory({ txId, status: \"Included\", finalState: false });\n afterTxSent(txId);\n\n return sendTxRes;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n updateTxHistory({\n txId,\n status: \"Error\",\n error: tryParseJson(errorMessage) ?? errorMessage,\n finalState: false,\n });\n throw new Error(errorMessage);\n }\n}\n\nexport interface AccessKeyView {\n nonce: number;\n permission: any;\n}\n\n/**\n * Generates a mock transaction ID.\n *\n * This function creates a pseudo-unique transaction ID for testing or\n * non-production use. It combines the current timestamp with a\n * random component for uniqueness.\n *\n * **Note:** This is not cryptographically secure and should not be used\n * for actual transaction processing.\n *\n * @returns {string} A mock transaction ID in the format `tx-{timestamp}-{random}`\n */\nexport function generateTxId(): string {\n const randomPart = crypto.getRandomValues(new Uint32Array(2)).join(\"\");\n return `tx-${Date.now()}-${parseInt(randomPart, 10).toString(36)}`;\n}\n\nexport const accountId = () => _state.accountId;\nexport const publicKey = () => _state.publicKey;\n\nexport const config = (newConfig?: Record<string, any>) => {\n const current = getConfig();\n if (newConfig) {\n if (newConfig.networkId && current.networkId !== newConfig.networkId) {\n setConfig(newConfig.networkId);\n update({ accountId: null, privateKey: null, lastWalletId: null });\n lsSet(\"block\", null);\n resetTxHistory();\n }\n setConfig({ ...getConfig(), ...newConfig });\n }\n return getConfig();\n};\n\nexport const authStatus = (): string | Record<string, any> => {\n if (!_state.accountId) {\n return \"SignedOut\";\n }\n return \"SignedIn\";\n};\n\n// this is an intentional stub\n// and it's probably partially done, to help ease future features\n// for now we'll assume each web end user has one keypair in storage\n// for every contract they wish to interact with\n// later, it may be prudent to hold multiple, but until then this function\n// just returns the access key as if it were among others in the array.\n// we're pretending like we really thought about which access key we're returning\n// based on the opts argument. this allows us to fill this logic in later.\nexport const getPublicKeyForContract = (opts?: any) => {\n return publicKey();\n}\n\n// returns details on the selected:\n// network, wallet, and explorer details as well as\n// sending account, contract, and selected public key\nexport const selected = () => {\n const network = getConfig().networkId;\n const nodeUrl = getConfig().nodeUrl;\n const walletUrl = getConfig().walletUrl;\n const helperUrl = getConfig().helperUrl;\n const explorerUrl = getConfig().explorerUrl;\n\n const account = accountId();\n const contract = _state.accessKeyContractId;\n const publicKey = getPublicKeyForContract();\n\n return {\n network,\n nodeUrl,\n walletUrl,\n helperUrl,\n explorerUrl,\n account,\n contract,\n publicKey\n }\n}\n\nexport const requestSignIn = async ({ contractId }: { contractId: string }) => {\n const privateKey = privateKeyFromRandom();\n update({ accessKeyContractId: contractId, accountId: null, privateKey });\n const pubKey = publicKeyFromPrivate(privateKey);\n\n const result = await _adapter.signIn({\n networkId: getConfig().networkId,\n contractId,\n publicKey: pubKey,\n });\n\n if (result.error) {\n throw new Error(`Wallet error: ${result.error}`);\n }\n if (result.url) {\n if (typeof window !== \"undefined\") {\n setTimeout(() => {\n window.location.href = result.url;\n }, 100);\n }\n } else if (result.accountId) {\n update({ accountId: result.accountId });\n }\n};\n\nexport const view = async ({\n contractId,\n methodName,\n args,\n argsBase64,\n blockId,\n }: {\n contractId: string;\n methodName: string;\n args?: any;\n argsBase64?: string;\n blockId?: string;\n}) => {\n const encodedArgs = argsBase64 || (args ? toBase64(JSON.stringify(args)) : \"\");\n const queryResult = await sendRpc(\n \"query\",\n withBlockId(\n {\n request_type: \"call_function\",\n account_id: contractId,\n method_name: methodName,\n args_base64: encodedArgs,\n },\n blockId\n )\n );\n\n return parseJsonFromBytes(queryResult.result.result);\n};\n\nexport const queryAccount = async ({\n accountId,\n blockId,\n }: {\n accountId: string;\n blockId?: string;\n}) => {\n return sendRpc(\n \"query\",\n withBlockId({ request_type: \"view_account\", account_id: accountId }, blockId)\n );\n};\n\nexport const queryBlock = async ({ blockId }: { blockId?: string }): Promise<BlockView> => {\n return sendRpc(\"block\", withBlockId({}, blockId));\n};\n\nexport const queryAccessKey = async ({\n accountId,\n publicKey,\n blockId,\n }: {\n accountId: string;\n publicKey: string;\n blockId?: string;\n}): Promise<AccessKeyWithError> => {\n return sendRpc(\n \"query\",\n withBlockId(\n { request_type: \"view_access_key\", account_id: accountId, public_key: publicKey },\n blockId\n )\n );\n};\n\nexport const queryTx = async ({ txHash, accountId }: { txHash: string; accountId: string }) => {\n return sendRpc(\"tx\", [txHash, accountId]);\n};\n\nexport const localTxHistory = () => {\n return getTxHistory();\n};\n\nexport const signOut = () => {\n update({ accountId: null, privateKey: null, contractId: null });\n setConfig(NETWORKS[DEFAULT_NETWORK_ID]);\n};\n\nexport const sendTx = async ({\n receiverId,\n actions,\n waitUntil,\n }: {\n receiverId: string;\n actions: any[];\n waitUntil?: string;\n}) => {\n const signerId = _state.accountId;\n if (!signerId) throw new Error(\"Must sign in\");\n\n const publicKey = _state.publicKey ?? \"\";\n const privKey = _state.privateKey;\n // this generates a mock transaction ID so we can keep track of each tx\n const txId = generateTxId();\n\n if (!privKey || receiverId !== _state.accessKeyContractId || !canSignWithLAK(actions)) {\n const jsonTx = { signerId, receiverId, actions };\n updateTxHistory({ status: \"Pending\", txId, tx: jsonTx, finalState: false });\n\n const url = new URL(typeof window !== \"undefined\" ? window.location.href : \"\");\n url.searchParams.set(\"txIds\", txId);\n\n // preserve existing url params\n const existingParams = new URLSearchParams(window.location.search);\n existingParams.forEach((value, key) => {\n if (!url.searchParams.has(key)) {\n url.searchParams.set(key, value);\n }\n });\n\n // we're wanting to preserve URL params that we send in\n // but make sure we're not feeding back error params\n // from a previous failure\n\n url.searchParams.delete(\"errorCode\");\n url.searchParams.delete(\"errorMessage\");\n\n try {\n const result: WalletTxResult = await _adapter.sendTransactions({\n transactions: [jsonTx],\n callbackUrl: url.toString(),\n });\n\n if (result.url) {\n if (typeof window !== \"undefined\") {\n setTimeout(() => {\n window.location.href = result.url!;\n }, 100);\n }\n } else if (result.outcomes?.length) {\n result.outcomes.forEach((r) =>\n updateTxHistory({\n txId,\n status: \"Executed\",\n result: r,\n txHash: r.transaction.hash,\n finalState: true,\n })\n );\n } else if (result.rejected) {\n updateTxHistory({ txId, status: \"RejectedByUser\", finalState: true });\n } else if (result.error) {\n updateTxHistory({\n txId,\n status: \"Error\",\n error: tryParseJson(result.error),\n finalState: true,\n });\n }\n\n return result;\n } catch (err) {\n console.error('fastnear: error sending tx using adapter:', err)\n updateTxHistory({\n txId,\n status: \"Error\",\n error: tryParseJson((err as Error).message),\n finalState: true,\n });\n\n return Promise.reject(err);\n }\n }\n\n let nonce = lsGet(\"nonce\") as number | null;\n if (nonce == null) {\n const accessKey = await queryAccessKey({ accountId: signerId, publicKey: publicKey });\n if (accessKey.result.error) {\n throw new Error(`Access key error: ${accessKey.result.error} when attempting to get nonce for ${signerId} for public key ${publicKey}`);\n }\n nonce = accessKey.result.nonce;\n lsSet(\"nonce\", nonce);\n }\n\n let lastKnownBlock = lsGet(\"block\") as LastKnownBlock | null;\n if (\n !lastKnownBlock ||\n parseFloat(lastKnownBlock.header.timestamp_nanosec) / 1e6 + MaxBlockDelayMs < Date.now()\n ) {\n const latestBlock = await queryBlock({ blockId: \"final\" });\n lastKnownBlock = {\n header: {\n hash: latestBlock.result.header.hash,\n timestamp_nanosec: latestBlock.result.header.timestamp_nanosec,\n },\n };\n lsSet(\"block\", lastKnownBlock);\n }\n\n nonce += 1;\n lsSet(\"nonce\", nonce);\n\n const blockHash = lastKnownBlock.header.hash;\n\n const plainTransactionObj: PlainTransaction = {\n signerId,\n publicKey,\n nonce,\n receiverId,\n blockHash,\n actions,\n };\n\n const txBytes = serializeTransaction(plainTransactionObj);\n const txHashBytes = sha256(txBytes);\n const txHash58 = toBase58(txHashBytes);\n\n const signatureBase58 = signHash(txHashBytes, privKey, { returnBase58: true });\n const signedTransactionBytes = serializeSignedTransaction(plainTransactionObj, signatureBase58);\n const signedTxBase64 = bytesToBase64(signedTransactionBytes);\n\n updateTxHistory({\n status: \"Pending\",\n txId,\n tx: plainTransactionObj,\n signature: signatureBase58,\n signedTxBase64,\n txHash: txHash58,\n finalState: false,\n });\n\n try {\n return await sendTxToRpc(signedTxBase64, waitUntil, txId);\n } catch (error) {\n console.error(\"Error Sending Transaction:\", error, plainTransactionObj, signedTxBase64);\n }\n};\n\n// exports\nexport const exp = {\n utils: {}, // we will map this in a moment, giving keys, for IDE hints\n borsh: reExportAllUtils.exp.borsh,\n borshSchema: reExportAllUtils.exp.borshSchema.getBorshSchema(),\n};\n\nfor (const key in reExportAllUtils) {\n exp.utils[key] = reExportAllUtils[key];\n}\n\n// devx\nexport const utils = exp.utils;\n\nexport const state = {}\n\nfor (const key in stateExports) {\n state[key] = stateExports[key];\n}\n\n// devx\n\nexport const event = state['events'];\ndelete state['events'];\n\n// Wallet redirect handling\ntry {\n if (typeof window !== \"undefined\") {\n const url = new URL(window.location.href);\n const accId = url.searchParams.get(\"account_id\");\n const pubKey = url.searchParams.get(\"public_key\");\n const errCode = url.searchParams.get(\"errorCode\");\n const errMsg = url.searchParams.get(\"errorMessage\");\n const decodedErrMsg = errMsg ? decodeURIComponent(errMsg) : null;\n\n const txHashes = url.searchParams.get(\"transactionHashes\");\n const txIds = url.searchParams.get(\"txIds\");\n\n if (errCode || errMsg) {\n console.warn(new Error(`Wallet raises:\\ncode: ${errCode}\\nmessage: ${decodedErrMsg}`));\n }\n\n if (accId && pubKey) {\n if (pubKey === _state.publicKey) {\n update({ accountId: accId });\n } else {\n // it's possible the end user has a URL param that's old. we'll remove the public_key param\n // if logged out, no need to throw warning\n if (authStatus() === \"SignedIn\") {\n console.warn(\"Public key mismatch from wallet redirect\", pubKey, _state.publicKey);\n }\n url.searchParams.delete(\"public_key\");\n }\n }\n\n if (txHashes || txIds) {\n const hashArr = txHashes ? txHashes.split(\",\") : [];\n const idArr = txIds ? txIds.split(\",\") : [];\n if (idArr.length > hashArr.length) {\n idArr.forEach((id) => {\n updateTxHistory({ txId: id, status: \"RejectedByUser\", finalState: true });\n });\n } else if (idArr.length === hashArr.length) {\n idArr.forEach((id, i) => {\n updateTxHistory({\n txId: id,\n status: \"PendingGotTxHash\",\n txHash: hashArr[i],\n finalState: false,\n });\n afterTxSent(id);\n });\n } else {\n console.error(new Error(\"Transaction hash mismatch from wallet redirect\"), idArr, hashArr);\n }\n }\n\n // we can consider removing these, but want to be careful because\n // it can be helpful for a dev to have a URL they can debug with\n // we won't want to remove information\n\n // pretty sure txIds can go, especially if you can tell it's been more than 5 minutes or something\n // public_key sometimes confuses it, so this might only be needed when adding a new access key\n // and perhaps once we've confirmed that the transaction hashes are getting saved to storage\n // (not sure about that section of code) then we can get rid of the transactionHashes, too\n\n url.searchParams.delete(\"txIds\");\n if (authStatus() === \"SignedOut\") {\n url.searchParams.delete(\"errorCode\");\n url.searchParams.delete(\"errorMessage\");\n }\n // ^ we've decided these ones make sense to keep\n\n // I'd like to keep this for posterity. for a bit.\n // url.searchParams.delete(\"account_id\");\n // url.searchParams.delete(\"public_key\");\n\n // url.searchParams.delete(\"all_keys\");\n // url.searchParams.delete(\"transactionHashes\");\n // window.history.replaceState({}, \"\", url.toString());\n }\n} catch (e) {\n console.error(\"Error handling wallet redirect:\", e);\n}\n\n// action helpers\nexport const actions = {\n functionCall: ({\n methodName,\n gas,\n deposit,\n args,\n argsBase64,\n }: {\n methodName: string;\n gas?: string;\n deposit?: string;\n args?: Record<string, any>;\n argsBase64?: string;\n }) => ({\n type: \"FunctionCall\",\n methodName,\n args,\n argsBase64,\n gas,\n deposit,\n }),\n\n transfer: (yoctoAmount: string) => ({\n type: \"Transfer\",\n deposit: yoctoAmount,\n }),\n\n stakeNEAR: ({amount, publicKey}: { amount: string; publicKey: string }) => ({\n type: \"Stake\",\n stake: amount,\n publicKey,\n }),\n\n addFullAccessKey: ({publicKey}: { publicKey: string }) => ({\n type: \"AddKey\",\n publicKey: publicKey,\n accessKey: {permission: \"FullAccess\"},\n }),\n\n addLimitedAccessKey: ({\n publicKey,\n allowance,\n accountId,\n methodNames,\n }: {\n publicKey: string;\n allowance: string;\n accountId: string;\n methodNames: string[];\n }) => ({\n type: \"AddKey\",\n publicKey: publicKey,\n accessKey: {\n permission: \"FunctionCall\",\n allowance,\n receiverId: accountId,\n methodNames,\n },\n }),\n\n deleteKey: ({publicKey}: { publicKey: string }) => ({\n type: \"DeleteKey\",\n publicKey,\n }),\n\n deleteAccount: ({beneficiaryId}: { beneficiaryId: string }) => ({\n type: \"DeleteAccount\",\n beneficiaryId,\n }),\n\n createAccount: () => ({\n type: \"CreateAccount\",\n }),\n\n deployContract: ({codeBase64}: { codeBase64: string }) => ({\n type: \"DeployContract\",\n codeBase64,\n }),\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAgB;AAChB,mBAcO;AAEP,mBAQO;AAEP,IAAAA,gBAIO;AAEP,kBAAuB;AACvB,uBAAkC;AAClC,mBAA8B;AAE9B,WAAAC,QAAI,KAAK;AACF,MAAM,kBAAkB,MAAO,KAAK,KAAK;AAkCzC,SAAS,YAAY,QAA6B,SAAkB;AACzE,MAAI,YAAY,WAAW,YAAY,cAAc;AACnD,WAAO,EAAE,GAAG,QAAQ,UAAU,QAAQ;AAAA,EACxC;AACA,SAAO,UAAU,EAAE,GAAG,QAAQ,UAAU,QAAQ,IAAI,EAAE,GAAG,QAAQ,UAAU,aAAa;AAC1F;AALgB;AAOhB,eAAsB,QAAQ,QAAgB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A;AAAA,IACA;AAAA,EACF,OAMR;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAnBc;AAAA,EAqBd,UAAU,wBAAC,iBAAyB;AAAA,IAClC,MAAM;AAAA,IACN,SAAS;AAAA,EACX,IAHU;AAAA,EAKV,WAAW,wBAAC,EAAC,QAAQ,WAAAF,WAAS,OAA8C;AAAA,IAC1E,MAAM;AAAA,IACN,OAAO;AAAA,IACP,WAAAA;AAAA,EACF,IAJW;AAAA,EAMX,kBAAkB,wBAAC,EAAC,WAAAA,WAAS,OAA8B;AAAA,IACzD,MAAM;AAAA,IACN,WAAWA;AAAA,IACX,WAAW,EAAC,YAAY,aAAY;AAAA,EACtC,IAJkB;AAAA,EAMlB,qBAAqB,wBAAC;AAAA,IACE,WAAAA;AAAA,IACA;AAAA,IACA,WAAAC;AAAA,IACA;AAAA,EACF,OAKf;AAAA,IACL,MAAM;AAAA,IACN,WAAWD;AAAA,IACX,WAAW;AAAA,MACT,YAAY;AAAA,MACZ;AAAA,MACA,YAAYC;AAAA,MACZ;AAAA,IACF;AAAA,EACF,IAnBqB;AAAA,EAqBrB,WAAW,wBAAC,EAAC,WAAAD,WAAS,OAA8B;AAAA,IAClD,MAAM;AAAA,IACN,WAAAA;AAAA,EACF,IAHW;AAAA,EAKX,eAAe,wBAAC,EAAC,cAAa,OAAkC;AAAA,IAC9D,MAAM;AAAA,IACN;AAAA,EACF,IAHe;AAAA,EAKf,eAAe,8BAAO;AAAA,IACpB,MAAM;AAAA,EACR,IAFe;AAAA,EAIf,gBAAgB,wBAAC,EAAC,WAAU,OAA+B;AAAA,IACzD,MAAM;AAAA,IACN;AAAA,EACF,IAHgB;AAIlB;","names":["import_state","Big","config","publicKey","accountId","actions"]}
1
+ {"version":3,"sources":["../../src/near.ts"],"sourcesContent":["import Big from \"big.js\";\nimport {\n lsSet,\n lsGet,\n tryParseJson,\n fromBase64,\n toBase64,\n canSignWithLAK,\n toBase58,\n parseJsonFromBytes,\n signHash,\n publicKeyFromPrivate,\n serializeTransaction,\n serializeSignedTransaction, bytesToBase64, PlainTransaction,\n} from \"@fastnear/utils\";\n\nimport type { NEP413Message } from \"@fastnear/utils\";\n\nimport {\n _state,\n DEFAULT_NETWORK_ID,\n NETWORKS,\n getWalletProvider,\n setWalletProvider,\n getTxHistory,\n update,\n updateTxHistory,\n} from \"./state.js\";\n\nimport type { WalletProvider } from \"./state.js\";\n\nimport {\n getConfig,\n setConfig,\n resetTxHistory,\n} from \"./state.js\";\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport * as reExportAllUtils from \"@fastnear/utils\";\nimport * as stateExports from \"./state.js\";\n\nBig.DP = 27;\nexport const MaxBlockDelayMs = 1000 * 60 * 60 * 6; // 6 hours\n\nexport interface AccessKeyWithError {\n result: {\n nonce: number;\n permission?: any;\n error?: string;\n }\n}\n\nexport interface BlockView {\n result: {\n header: {\n hash: string;\n timestamp_nanosec: string;\n }\n }\n}\n\n// The structure it's saved to in storage\nexport interface LastKnownBlock {\n header: {\n hash: string;\n timestamp_nanosec: string;\n }\n}\n\nexport function withBlockId(params: Record<string, any>, blockId?: string) {\n if (blockId === \"final\" || blockId === \"optimistic\") {\n return { ...params, finality: blockId };\n }\n return blockId ? { ...params, block_id: blockId } : { ...params, finality: \"optimistic\" };\n}\n\nexport async function sendRpc(method: string, params: Record<string, any> | any[]) {\n const config = getConfig();\n if (!config?.nodeUrl) {\n throw new Error(\"fastnear: getConfig() returned invalid config: missing nodeUrl.\");\n }\n const response = await fetch(config.nodeUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: `fastnear-${Date.now()}`,\n method,\n params,\n }),\n });\n const result = await response.json();\n if (result.error) {\n throw new Error(JSON.stringify(result.error));\n }\n return result;\n}\n\nexport function afterTxSent(txId: string) {\n const txHistory = getTxHistory();\n sendRpc(\"tx\", {\n tx_hash: txHistory[txId]?.txHash,\n sender_account_id: txHistory[txId]?.tx?.signerId,\n wait_until: \"EXECUTED_OPTIMISTIC\",\n })\n .then( result => {\n const successValue = result?.result?.status?.SuccessValue;\n updateTxHistory({\n txId,\n status: \"Executed\",\n result,\n successValue: successValue ? tryParseJson(fromBase64(successValue)) : undefined,\n finalState: true,\n });\n })\n .catch((error) => {\n updateTxHistory({\n txId,\n status: \"ErrorAfterIncluded\",\n error: tryParseJson(error.message) ?? error.message,\n finalState: true,\n });\n });\n}\n\nexport async function sendTxToRpc(signedTxBase64: string, waitUntil: string | undefined, txId: string) {\n // default to \"INCLUDED\"\n // see options: https://docs.near.org/api/rpc/transactions#tx-status-result\n waitUntil = waitUntil || \"INCLUDED\";\n\n try {\n const sendTxRes = await sendRpc(\"send_tx\", {\n signed_tx_base64: signedTxBase64,\n wait_until: waitUntil,\n });\n\n updateTxHistory({ txId, status: \"Included\", finalState: false });\n afterTxSent(txId);\n\n return sendTxRes;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n updateTxHistory({\n txId,\n status: \"Error\",\n error: tryParseJson(errorMessage) ?? errorMessage,\n finalState: false,\n });\n throw new Error(errorMessage);\n }\n}\n\nexport interface AccessKeyView {\n nonce: number;\n permission: any;\n}\n\n/**\n * Generates a mock transaction ID.\n */\nexport function generateTxId(): string {\n const randomPart = crypto.getRandomValues(new Uint32Array(2)).join(\"\");\n return `tx-${Date.now()}-${parseInt(randomPart, 10).toString(36)}`;\n}\n\nexport const accountId = () => _state.accountId;\nexport const publicKey = () => _state.publicKey;\n\nexport const config = (newConfig?: Record<string, any>) => {\n const current = getConfig();\n if (newConfig) {\n if (newConfig.networkId && current.networkId !== newConfig.networkId) {\n setConfig(newConfig.networkId);\n update({ accountId: null, privateKey: null, lastWalletId: null });\n lsSet(\"block\", null);\n resetTxHistory();\n }\n setConfig({ ...getConfig(), ...newConfig });\n }\n return getConfig();\n};\n\nexport const authStatus = (): string | Record<string, any> => {\n if (!_state.accountId) {\n return \"SignedOut\";\n }\n return \"SignedIn\";\n};\n\nexport const getPublicKeyForContract = (opts?: any) => {\n return publicKey();\n}\n\nexport const selected = () => {\n const network = getConfig().networkId;\n const nodeUrl = getConfig().nodeUrl;\n const walletUrl = getConfig().walletUrl;\n const helperUrl = getConfig().helperUrl;\n const explorerUrl = getConfig().explorerUrl;\n\n const account = accountId();\n const contract = _state.accessKeyContractId;\n const publicKey = getPublicKeyForContract();\n\n return {\n network,\n nodeUrl,\n walletUrl,\n helperUrl,\n explorerUrl,\n account,\n contract,\n publicKey\n }\n}\n\nexport const requestSignIn = async ({\n contractId,\n excludedWallets,\n features,\n}: {\n contractId?: string;\n excludedWallets?: string[];\n features?: Record<string, boolean>;\n} = {}) => {\n const provider = getWalletProvider();\n if (!provider) {\n throw new Error(\"No wallet provider set. Call useWallet() first or load the @fastnear/wallet IIFE bundle.\");\n }\n\n // Disconnect if already connected\n if (provider.isConnected()) {\n await provider.disconnect();\n }\n\n const result = await provider.connect({\n contractId,\n network: getConfig().networkId,\n excludedWallets,\n features,\n });\n\n if (!result) {\n // User rejected\n return;\n }\n\n update({ accountId: result.accountId });\n};\n\nexport const view = async ({\n contractId,\n methodName,\n args,\n argsBase64,\n blockId,\n }: {\n contractId: string;\n methodName: string;\n args?: any;\n argsBase64?: string;\n blockId?: string;\n}) => {\n const encodedArgs = argsBase64 || (args ? toBase64(JSON.stringify(args)) : \"\");\n const queryResult = await sendRpc(\n \"query\",\n withBlockId(\n {\n request_type: \"call_function\",\n account_id: contractId,\n method_name: methodName,\n args_base64: encodedArgs,\n },\n blockId\n )\n );\n\n return parseJsonFromBytes(queryResult.result.result);\n};\n\nexport const queryAccount = async ({\n accountId,\n blockId,\n }: {\n accountId: string;\n blockId?: string;\n}) => {\n return sendRpc(\n \"query\",\n withBlockId({ request_type: \"view_account\", account_id: accountId }, blockId)\n );\n};\n\nexport const queryBlock = async ({ blockId }: { blockId?: string }): Promise<BlockView> => {\n return sendRpc(\"block\", withBlockId({}, blockId));\n};\n\nexport const queryAccessKey = async ({\n accountId,\n publicKey,\n blockId,\n }: {\n accountId: string;\n publicKey: string;\n blockId?: string;\n}): Promise<AccessKeyWithError> => {\n return sendRpc(\n \"query\",\n withBlockId(\n { request_type: \"view_access_key\", account_id: accountId, public_key: publicKey },\n blockId\n )\n );\n};\n\nexport const queryTx = async ({ txHash, accountId }: { txHash: string; accountId: string }) => {\n return sendRpc(\"tx\", [txHash, accountId]);\n};\n\nexport const localTxHistory = () => {\n return getTxHistory();\n};\n\nexport const signOut = async () => {\n const provider = getWalletProvider();\n if (provider?.isConnected()) {\n await provider.disconnect();\n }\n update({ accountId: null, privateKey: null, contractId: null });\n setConfig(NETWORKS[DEFAULT_NETWORK_ID]);\n};\n\nexport const sendTx = async ({\n receiverId,\n actions,\n waitUntil,\n }: {\n receiverId: string;\n actions: any[];\n waitUntil?: string;\n}) => {\n const signerId = _state.accountId;\n if (!signerId) throw new Error(\"Must sign in\");\n\n const pubKey = _state.publicKey ?? \"\";\n const privKey = _state.privateKey;\n const txId = generateTxId();\n\n // If no local private key, or the receiver doesn't match the access key contract,\n // or the actions aren't signable with a limited access key, delegate to the wallet\n if (!privKey || receiverId !== _state.accessKeyContractId || !canSignWithLAK(actions)) {\n const jsonTx = { signerId, receiverId, actions };\n updateTxHistory({ status: \"Pending\", txId, tx: jsonTx, finalState: false });\n\n try {\n const provider = getWalletProvider();\n if (!provider?.isConnected()) {\n throw new Error(\"Must sign in\");\n }\n\n const result = await provider.sendTransaction(jsonTx);\n\n if (!result) {\n // User rejected\n updateTxHistory({ txId, status: \"RejectedByUser\", finalState: true });\n return { rejected: true };\n }\n\n if (result.outcomes?.length) {\n result.outcomes.forEach((r: any) =>\n updateTxHistory({\n txId,\n status: \"Executed\",\n result: r,\n txHash: r.transaction?.hash,\n finalState: true,\n })\n );\n }\n\n return result;\n } catch (err) {\n console.error('fastnear: error sending tx using wallet provider:', err)\n updateTxHistory({\n txId,\n status: \"Error\",\n error: tryParseJson((err as Error).message),\n finalState: true,\n });\n\n return Promise.reject(err);\n }\n }\n\n // Local signing path (limited access key)\n let nonce = lsGet(\"nonce\") as number | null;\n if (nonce == null) {\n const accessKey = await queryAccessKey({ accountId: signerId, publicKey: pubKey });\n if (accessKey.result.error) {\n throw new Error(`Access key error: ${accessKey.result.error} when attempting to get nonce for ${signerId} for public key ${pubKey}`);\n }\n nonce = accessKey.result.nonce;\n lsSet(\"nonce\", nonce);\n }\n\n let lastKnownBlock = lsGet(\"block\") as LastKnownBlock | null;\n if (\n !lastKnownBlock ||\n parseFloat(lastKnownBlock.header.timestamp_nanosec) / 1e6 + MaxBlockDelayMs < Date.now()\n ) {\n const latestBlock = await queryBlock({ blockId: \"final\" });\n lastKnownBlock = {\n header: {\n hash: latestBlock.result.header.hash,\n timestamp_nanosec: latestBlock.result.header.timestamp_nanosec,\n },\n };\n lsSet(\"block\", lastKnownBlock);\n }\n\n nonce += 1;\n lsSet(\"nonce\", nonce);\n\n const blockHash = lastKnownBlock.header.hash;\n\n const plainTransactionObj: PlainTransaction = {\n signerId,\n publicKey: pubKey,\n nonce,\n receiverId,\n blockHash,\n actions,\n };\n\n const txBytes = serializeTransaction(plainTransactionObj);\n const txHashBytes = sha256(txBytes);\n const txHash58 = toBase58(txHashBytes);\n\n const signatureBase58 = signHash(txHashBytes, privKey, { returnBase58: true });\n const signedTransactionBytes = serializeSignedTransaction(plainTransactionObj, signatureBase58);\n const signedTxBase64 = bytesToBase64(signedTransactionBytes);\n\n updateTxHistory({\n status: \"Pending\",\n txId,\n tx: plainTransactionObj,\n signature: signatureBase58,\n signedTxBase64,\n txHash: txHash58,\n finalState: false,\n });\n\n try {\n return await sendTxToRpc(signedTxBase64, waitUntil, txId);\n } catch (error) {\n console.error(\"Error Sending Transaction:\", error, plainTransactionObj, signedTxBase64);\n }\n};\n\n/**\n * Signs a NEP-413 message using the connected wallet.\n */\nexport const signMessage = async (message: NEP413Message) => {\n const provider = getWalletProvider();\n if (!provider?.isConnected()) {\n throw new Error(\"Must sign in\");\n }\n if (!provider.signMessage) {\n throw new Error(\"Connected wallet does not support signMessage\");\n }\n return provider.signMessage(message);\n};\n\n/**\n * Set the wallet provider used by the API for signing and sending transactions.\n * Automatically called in IIFE builds when globalThis.nearWallet is present.\n */\nexport const useWallet = (provider: WalletProvider): void => {\n setWalletProvider(provider);\n};\n\n// exports\nexport const exp = {\n utils: {}, // we will map this in a moment, giving keys, for IDE hints\n borsh: reExportAllUtils.exp.borsh,\n borshSchema: reExportAllUtils.exp.borshSchema.getBorshSchema(),\n};\n\nfor (const key in reExportAllUtils) {\n exp.utils[key] = reExportAllUtils[key];\n}\n\n// devx\nexport const utils = exp.utils;\n\nexport const state = {}\n\nfor (const key in stateExports) {\n state[key] = stateExports[key];\n}\n\n// devx\n\nexport const event = state['events'];\ndelete state['events'];\n\n// action helpers\nexport const actions = {\n functionCall: ({\n methodName,\n gas,\n deposit,\n args,\n argsBase64,\n }: {\n methodName: string;\n gas?: string;\n deposit?: string;\n args?: Record<string, any>;\n argsBase64?: string;\n }) => ({\n type: \"FunctionCall\",\n methodName,\n args,\n argsBase64,\n gas,\n deposit,\n }),\n\n transfer: (yoctoAmount: string) => ({\n type: \"Transfer\",\n deposit: yoctoAmount,\n }),\n\n stakeNEAR: ({amount, publicKey}: { amount: string; publicKey: string }) => ({\n type: \"Stake\",\n stake: amount,\n publicKey,\n }),\n\n addFullAccessKey: ({publicKey}: { publicKey: string }) => ({\n type: \"AddKey\",\n publicKey: publicKey,\n accessKey: {permission: \"FullAccess\"},\n }),\n\n addLimitedAccessKey: ({\n publicKey,\n allowance,\n accountId,\n methodNames,\n }: {\n publicKey: string;\n allowance: string;\n accountId: string;\n methodNames: string[];\n }) => ({\n type: \"AddKey\",\n publicKey: publicKey,\n accessKey: {\n permission: \"FunctionCall\",\n allowance,\n receiverId: accountId,\n methodNames,\n },\n }),\n\n deleteKey: ({publicKey}: { publicKey: string }) => ({\n type: \"DeleteKey\",\n publicKey,\n }),\n\n deleteAccount: ({beneficiaryId}: { beneficiaryId: string }) => ({\n type: \"DeleteAccount\",\n beneficiaryId,\n }),\n\n createAccount: () => ({\n type: \"CreateAccount\",\n }),\n\n deployContract: ({codeBase64}: { codeBase64: string }) => ({\n type: \"DeployContract\",\n codeBase64,\n }),\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAgB;AAChB,mBAaO;AAIP,mBASO;AAIP,IAAAA,gBAIO;AAEP,kBAAuB;AACvB,uBAAkC;AAClC,mBAA8B;AAE9B,WAAAC,QAAI,KAAK;AACF,MAAM,kBAAkB,MAAO,KAAK,KAAK;AA2BzC,SAAS,YAAY,QAA6B,SAAkB;AACzE,MAAI,YAAY,WAAW,YAAY,cAAc;AACnD,WAAO,EAAE,GAAG,QAAQ,UAAU,QAAQ;AAAA,EACxC;AACA,SAAO,UAAU,EAAE,GAAG,QAAQ,UAAU,QAAQ,IAAI,EAAE,GAAG,QAAQ,UAAU,aAAa;AAC1F;AALgB;AAOhB,eAAsB,QAAQ,QAAgB,QAAqC;AACjF,QAAMC,cAAS,yBAAU;AACzB,MAAI,CAACA,SAAQ,SAAS;AACpB,UAAM,IAAI,MAAM,iEAAiE;AAAA,EACnF;AACA,QAAM,WAAW,MAAM,MAAMA,QAAO,SAAS;AAAA,IAC3C,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAC9C,MAAM,KAAK,UAAU;AAAA,MACnB,SAAS;AAAA,MACT,IAAI,YAAY,KAAK,IAAI,CAAC;AAAA,MAC1B;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACD,QAAM,SAAS,MAAM,SA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gB;AAIlB;","names":["import_state","Big","config","publicKey","accountId","actions"]}
@@ -23,8 +23,6 @@ var state_exports = {};
23
23
  __export(state_exports, {
24
24
  DEFAULT_NETWORK_ID: () => DEFAULT_NETWORK_ID,
25
25
  NETWORKS: () => NETWORKS,
26
- WIDGET_URL: () => WIDGET_URL,
27
- _adapter: () => _adapter,
28
26
  _config: () => _config,
29
27
  _state: () => _state,
30
28
  _txHistory: () => _txHistory,
@@ -32,17 +30,15 @@ __export(state_exports, {
32
30
  events: () => events,
33
31
  getConfig: () => getConfig,
34
32
  getTxHistory: () => getTxHistory,
35
- getWalletAdapterState: () => getWalletAdapterState,
36
- onAdapterStateUpdate: () => onAdapterStateUpdate,
33
+ getWalletProvider: () => getWalletProvider,
37
34
  resetTxHistory: () => resetTxHistory,
38
35
  setConfig: () => setConfig,
36
+ setWalletProvider: () => setWalletProvider,
39
37
  update: () => update,
40
38
  updateTxHistory: () => updateTxHistory
41
39
  });
42
40
  module.exports = __toCommonJS(state_exports);
43
41
  var import_utils = require("@fastnear/utils");
44
- var import_wallet_adapter = require("@fastnear/wallet-adapter");
45
- const WIDGET_URL = "https://js.cdn.fastnear.com";
46
42
  const DEFAULT_NETWORK_ID = "mainnet";
47
43
  const NETWORKS = {
48
44
  testnet: {
@@ -58,28 +54,13 @@ let _config = (0, import_utils.lsGet)("config") || {
58
54
  ...NETWORKS[DEFAULT_NETWORK_ID]
59
55
  };
60
56
  let _state = (0, import_utils.lsGet)("state") || {};
61
- const onAdapterStateUpdate = /* @__PURE__ */ __name((state) => {
62
- console.log("Adapter state update:", state);
63
- const { accountId, lastWalletId, privateKey } = state;
64
- update({
65
- accountId: accountId || void 0,
66
- lastWalletId: lastWalletId || void 0,
67
- ...privateKey ? { privateKey } : {}
68
- });
69
- }, "onAdapterStateUpdate");
70
- const getWalletAdapterState = /* @__PURE__ */ __name(() => {
71
- return {
72
- publicKey: _state.publicKey,
73
- accountId: _state.accountId,
74
- lastWalletId: _state.lastWalletId,
75
- networkId: _config.networkId
76
- };
77
- }, "getWalletAdapterState");
78
- let _adapter = new import_wallet_adapter.WalletAdapter({
79
- onStateUpdate: onAdapterStateUpdate,
80
- lastState: getWalletAdapterState(),
81
- widgetUrl: WIDGET_URL
82
- });
57
+ let _walletProvider = null;
58
+ const setWalletProvider = /* @__PURE__ */ __name((provider) => {
59
+ _walletProvider = provider;
60
+ }, "setWalletProvider");
61
+ const getWalletProvider = /* @__PURE__ */ __name(() => {
62
+ return _walletProvider;
63
+ }, "getWalletProvider");
83
64
  try {
84
65
  _state.publicKey = _state.privateKey ? (0, import_utils.publicKeyFromPrivate)(_state.privateKey) : null;
85
66
  } catch (e) {
@@ -156,9 +137,6 @@ const update = /* @__PURE__ */ __name((newState) => {
156
137
  if (newState.accountId !== oldState.accountId) {
157
138
  events.notifyAccountListeners(newState.accountId);
158
139
  }
159
- if (newState.hasOwnProperty("lastWalletId") && newState.lastWalletId !== oldState.lastWalletId || newState.hasOwnProperty("accountId") && newState.accountId !== oldState.accountId || newState.hasOwnProperty("privateKey") && newState.privateKey !== oldState.privateKey) {
160
- _adapter.setState(getWalletAdapterState());
161
- }
162
140
  }, "update");
163
141
  const updateTxHistory = /* @__PURE__ */ __name((txStatus) => {
164
142
  const txId = txStatus.txId;
@@ -188,8 +166,6 @@ const resetTxHistory = /* @__PURE__ */ __name(() => {
188
166
  0 && (module.exports = {
189
167
  DEFAULT_NETWORK_ID,
190
168
  NETWORKS,
191
- WIDGET_URL,
192
- _adapter,
193
169
  _config,
194
170
  _state,
195
171
  _txHistory,
@@ -197,10 +173,10 @@ const resetTxHistory = /* @__PURE__ */ __name(() => {
197
173
  events,
198
174
  getConfig,
199
175
  getTxHistory,
200
- getWalletAdapterState,
201
- onAdapterStateUpdate,
176
+ getWalletProvider,
202
177
  resetTxHistory,
203
178
  setConfig,
179
+ setWalletProvider,
204
180
  update,
205
181
  updateTxHistory
206
182
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/state.ts"],"sourcesContent":["import {\n lsSet,\n lsGet,\n publicKeyFromPrivate,\n} from \"@fastnear/utils\";\nimport {WalletAdapter} from \"@fastnear/wallet-adapter\";\n\nexport const WIDGET_URL = \"https://js.cdn.fastnear.com\";\n\nexport const DEFAULT_NETWORK_ID = \"mainnet\";\nexport const NETWORKS = {\n testnet: {\n networkId: \"testnet\",\n nodeUrl: \"https://rpc.testnet.fastnear.com/\",\n },\n mainnet: {\n networkId: \"mainnet\",\n nodeUrl: \"https://rpc.mainnet.fastnear.com/\",\n },\n};\n\nexport interface NetworkConfig {\n networkId: string;\n nodeUrl?: string;\n walletUrl?: string;\n helperUrl?: string;\n explorerUrl?: string;\n\n [key: string]: any;\n}\n\nexport interface AppState {\n accountId?: string | null;\n privateKey?: string | null;\n lastWalletId?: string | null;\n publicKey?: string | null;\n accessKeyContractId?: string | null;\n\n [key: string]: any;\n}\n\nexport interface TxStatus {\n txId: string;\n updateTimestamp?: number;\n\n [key: string]: any;\n}\n\nexport type TxHistory = Record<string, TxStatus>;\n\nexport interface EventListeners {\n account: Set<(accountId: string) => void>;\n tx: Set<(tx: TxStatus) => void>;\n}\n\nexport interface UnbroadcastedEvents {\n account: string[];\n tx: TxStatus[];\n}\n\nexport interface WalletAdapterState {\n publicKey?: string | null;\n privateKey?: string | null;\n accountId?: string | null;\n lastWalletId?: string | null;\n networkId: string;\n}\n\n\n// Load config from localStorage or default to the network's config\nexport let _config: NetworkConfig = lsGet(\"config\") || {\n ...NETWORKS[DEFAULT_NETWORK_ID]\n};\n\n// Load application state from localStorage\nexport let _state: AppState = lsGet(\"state\") || {};\n\n// Triggered by the wallet adapter\nexport const onAdapterStateUpdate = (state: WalletAdapterState) => {\n console.log(\"Adapter state update:\", state);\n const { accountId, lastWalletId, privateKey } = state;\n update({\n accountId: accountId || undefined,\n lastWalletId: lastWalletId || undefined,\n ...(privateKey ? { privateKey } : {}),\n });\n}\n\nexport const getWalletAdapterState = (): WalletAdapterState => {\n return {\n publicKey: _state.publicKey,\n accountId: _state.accountId,\n lastWalletId: _state.lastWalletId,\n networkId: _config.networkId,\n };\n}\n\n// We can create an adapter instance here\nexport let _adapter = new WalletAdapter({\n onStateUpdate: onAdapterStateUpdate,\n lastState: getWalletAdapterState(),\n widgetUrl: WIDGET_URL,\n});\n\n// Attempt to set publicKey if we have a privateKey\ntry {\n _state.publicKey = _state.privateKey\n ? publicKeyFromPrivate(_state.privateKey)\n : null;\n} catch (e) {\n console.error(\"Error parsing private key:\", e);\n _state.privateKey = null;\n lsSet(\"nonce\", null);\n}\n\n// Transaction history\nexport let _txHistory: TxHistory = lsGet(\"txHistory\") || {};\n\n\nexport const _unbroadcastedEvents: UnbroadcastedEvents = {\n account: [],\n tx: [],\n};\n\n// events / listeners\nexport const events = {\n _eventListeners: {\n account: new Set(),\n tx: new Set(),\n },\n\n notifyAccountListeners: (accountId: string) => {\n if (events._eventListeners.account.size === 0) {\n _unbroadcastedEvents.account.push(accountId);\n return;\n }\n events._eventListeners.account.forEach((callback: any) => {\n try {\n callback(accountId);\n } catch (e) {\n console.error(e);\n }\n });\n },\n\n notifyTxListeners: (tx: TxStatus) => {\n if (events._eventListeners.tx.size === 0) {\n _unbroadcastedEvents.tx.push(tx);\n return;\n }\n events._eventListeners.tx.forEach((callback: any) => {\n try {\n callback(tx);\n } catch (e) {\n console.error(e);\n }\n });\n },\n\n onAccount: (callback: (accountId: string) => void) => {\n events._eventListeners.account.add(callback);\n if (_unbroadcastedEvents.account.length > 0) {\n const accountEvent = _unbroadcastedEvents.account;\n _unbroadcastedEvents.account = [];\n accountEvent.forEach(events.notifyAccountListeners);\n }\n },\n\n onTx: (callback: (tx: TxStatus) => void): void => {\n events._eventListeners.tx.add(callback);\n if (_unbroadcastedEvents.tx.length > 0) {\n const txEvent = _unbroadcastedEvents.tx;\n _unbroadcastedEvents.tx = [];\n txEvent.forEach(events.notifyTxListeners);\n }\n }\n}\n\n// Mutators\n// @todo: in favor of limiting when out of alpha\n// but haven't given it enough thought ~ mike\nexport const update = (newState: Partial<AppState>) => {\n const oldState = _state;\n _state = {..._state, ...newState};\n\n lsSet(\"state\", {\n accountId: _state.accountId,\n privateKey: _state.privateKey,\n lastWalletId: _state.lastWalletId,\n accessKeyContractId: _state.accessKeyContractId,\n });\n\n if (\n newState.hasOwnProperty(\"privateKey\") &&\n newState.privateKey !== oldState.privateKey\n ) {\n _state.publicKey = newState.privateKey\n ? publicKeyFromPrivate(newState.privateKey as string)\n : null;\n lsSet(\"nonce\", null);\n }\n\n if (newState.accountId !== oldState.accountId) {\n events.notifyAccountListeners(newState.accountId as string);\n }\n\n if (\n (newState.hasOwnProperty(\"lastWalletId\") &&\n newState.lastWalletId !== oldState.lastWalletId) ||\n (newState.hasOwnProperty(\"accountId\") &&\n newState.accountId !== oldState.accountId) ||\n (newState.hasOwnProperty(\"privateKey\") &&\n newState.privateKey !== oldState.privateKey)\n ) {\n _adapter.setState(getWalletAdapterState());\n }\n}\n\nexport const updateTxHistory = (txStatus: TxStatus) => {\n const txId = txStatus.txId;\n _txHistory[txId] = {\n ...(_txHistory[txId] || {}),\n ...txStatus,\n updateTimestamp: Date.now(),\n };\n lsSet(\"txHistory\", _txHistory);\n events.notifyTxListeners(_txHistory[txId]);\n}\n\nexport const getConfig = (): NetworkConfig => {\n return _config;\n}\n\nexport const getTxHistory = (): TxHistory => {\n return _txHistory;\n}\n\n// Exposed \"write\" functions\nexport const setConfig = (newConf: NetworkConfig): void => {\n _config = { ...NETWORKS[newConf.networkId], ...newConf };\n lsSet(\"config\", _config);\n}\n\nexport const resetTxHistory = (): void => {\n _txHistory = {};\n lsSet(\"txHistory\", _txHistory);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAIO;AACP,4BAA4B;AAErB,MAAM,aAAa;AAEnB,MAAM,qBAAqB;AAC3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qBAAqB,OAAO;AAAA,EAC9B,CAAC;AAED,MACE,SAAS,eAAe,YAAY,KACpC,SAAS,eAAe,SAAS,YACjC;AACA,WAAO,YAAY,SAAS,iBACxB,mCAAqB,SAAS,UAAoB,IAClD;AACJ,4BAAM,SAAS,IAAI;AAAA,EACrB;AAEA,MAAI,SAAS,cAAc,SAAS,WAAW;AAC7C,WAAO,uBAAuB,SAAS,SAAmB;AAAA,EAC5D;AAEA,MACG,SAAS,eAAe,cAAc,KACrC,SAAS,iBAAiB,SAAS,gBACpC,SAAS,eAAe,WAAW,KAClC,SAAS,cAAc,SAAS,aACjC,SAAS,eAAe,YAAY,KACnC,SAAS,eAAe,SAAS,YACnC;AACA,aAAS,SAAS,sBAAsB,CAAC;AAAA,EAC3C;AACF,GAnCsB;AAqCf,MAAM,kBAAkB,wBAAC,aAAuB;AACrD,QAAM,OAAO,SAAS;AACtB,aAAW,IAAI,IAAI;AAAA,IACjB,GAAI,WAAW,IAAI,KAAK,CAAC;AAAA,IACzB,GAAG;AAAA,IACH,iBAAiB,KAAK,IAAI;AAAA,EAC5B;AACA,0BAAM,aAAa,UAAU;AAC7B,SAAO,kBAAkB,WAAW,IAAI,CAAC;AAC3C,GAT+B;AAWxB,MAAM,YAAY,6BAAqB;AAC5C,SAAO;AACT,GAFyB;AAIlB,MAAM,eAAe,6BAAiB;AAC3C,SAAO;AACT,GAF4B;AAKrB,MAAM,YAAY,wBAAC,YAAiC;AACzD,YAAU,EAAE,GAAG,SAAS,QAAQ,SAAS,GAAG,GAAG,QAAQ;AACvD,0BAAM,UAAU,OAAO;AACzB,GAHyB;AAKlB,MAAM,iBAAiB,6BAAY;AACxC,eAAa,CAAC;AACd,0BAAM,aAAa,UAAU;AAC/B,GAH8B;","names":[]}
1
+ {"version":3,"sources":["../../src/state.ts"],"sourcesContent":["import {\n lsSet,\n lsGet,\n publicKeyFromPrivate,\n} from \"@fastnear/utils\";\n\nexport const DEFAULT_NETWORK_ID = \"mainnet\";\nexport const NETWORKS = {\n testnet: {\n networkId: \"testnet\",\n nodeUrl: \"https://rpc.testnet.fastnear.com/\",\n },\n mainnet: {\n networkId: \"mainnet\",\n nodeUrl: \"https://rpc.mainnet.fastnear.com/\",\n },\n};\n\nexport interface NetworkConfig {\n networkId: string;\n nodeUrl?: string;\n walletUrl?: string;\n helperUrl?: string;\n explorerUrl?: string;\n\n [key: string]: any;\n}\n\nexport interface AppState {\n accountId?: string | null;\n privateKey?: string | null;\n lastWalletId?: string | null;\n publicKey?: string | null;\n accessKeyContractId?: string | null;\n\n [key: string]: any;\n}\n\nexport interface TxStatus {\n txId: string;\n updateTimestamp?: number;\n\n [key: string]: any;\n}\n\nexport type TxHistory = Record<string, TxStatus>;\n\nexport interface EventListeners {\n account: Set<(accountId: string) => void>;\n tx: Set<(tx: TxStatus) => void>;\n}\n\nexport interface UnbroadcastedEvents {\n account: string[];\n tx: TxStatus[];\n}\n\n// Load config from localStorage or default to the network's config\nexport let _config: NetworkConfig = lsGet(\"config\") || {\n ...NETWORKS[DEFAULT_NETWORK_ID]\n};\n\n// Load application state from localStorage\nexport let _state: AppState = lsGet(\"state\") || {};\n\nexport interface WalletProvider {\n connect(options?: { contractId?: string; network?: string; excludedWallets?: string[]; features?: Record<string, boolean> }): Promise<{ accountId: string } | null>;\n restore?(options?: { contractId?: string; network?: string }): Promise<{ accountId: string } | null>;\n disconnect(): Promise<void>;\n sendTransaction(params: { receiverId: string; actions: any[]; signerId?: string }): Promise<any>;\n signMessage?(params: { message: string; recipient: string; nonce: Uint8Array }): Promise<any>;\n accountId(): string | null;\n isConnected(): boolean;\n}\n\nlet _walletProvider: WalletProvider | null = null;\n\nexport const setWalletProvider = (provider: WalletProvider): void => {\n _walletProvider = provider;\n};\n\nexport const getWalletProvider = (): WalletProvider | null => {\n return _walletProvider;\n};\n\n// Attempt to set publicKey if we have a privateKey\ntry {\n _state.publicKey = _state.privateKey\n ? publicKeyFromPrivate(_state.privateKey)\n : null;\n} catch (e) {\n console.error(\"Error parsing private key:\", e);\n _state.privateKey = null;\n lsSet(\"nonce\", null);\n}\n\n// Transaction history\nexport let _txHistory: TxHistory = lsGet(\"txHistory\") || {};\n\n\nexport const _unbroadcastedEvents: UnbroadcastedEvents = {\n account: [],\n tx: [],\n};\n\n// events / listeners\nexport const events = {\n _eventListeners: {\n account: new Set(),\n tx: new Set(),\n },\n\n notifyAccountListeners: (accountId: string) => {\n if (events._eventListeners.account.size === 0) {\n _unbroadcastedEvents.account.push(accountId);\n return;\n }\n events._eventListeners.account.forEach((callback: any) => {\n try {\n callback(accountId);\n } catch (e) {\n console.error(e);\n }\n });\n },\n\n notifyTxListeners: (tx: TxStatus) => {\n if (events._eventListeners.tx.size === 0) {\n _unbroadcastedEvents.tx.push(tx);\n return;\n }\n events._eventListeners.tx.forEach((callback: any) => {\n try {\n callback(tx);\n } catch (e) {\n console.error(e);\n }\n });\n },\n\n onAccount: (callback: (accountId: string) => void) => {\n events._eventListeners.account.add(callback);\n if (_unbroadcastedEvents.account.length > 0) {\n const accountEvent = _unbroadcastedEvents.account;\n _unbroadcastedEvents.account = [];\n accountEvent.forEach(events.notifyAccountListeners);\n }\n },\n\n onTx: (callback: (tx: TxStatus) => void): void => {\n events._eventListeners.tx.add(callback);\n if (_unbroadcastedEvents.tx.length > 0) {\n const txEvent = _unbroadcastedEvents.tx;\n _unbroadcastedEvents.tx = [];\n txEvent.forEach(events.notifyTxListeners);\n }\n }\n}\n\n// Mutators\nexport const update = (newState: Partial<AppState>) => {\n const oldState = _state;\n _state = {..._state, ...newState};\n\n lsSet(\"state\", {\n accountId: _state.accountId,\n privateKey: _state.privateKey,\n lastWalletId: _state.lastWalletId,\n accessKeyContractId: _state.accessKeyContractId,\n });\n\n if (\n newState.hasOwnProperty(\"privateKey\") &&\n newState.privateKey !== oldState.privateKey\n ) {\n _state.publicKey = newState.privateKey\n ? publicKeyFromPrivate(newState.privateKey as string)\n : null;\n lsSet(\"nonce\", null);\n }\n\n if (newState.accountId !== oldState.accountId) {\n events.notifyAccountListeners(newState.accountId as string);\n }\n}\n\nexport const updateTxHistory = (txStatus: TxStatus) => {\n const txId = txStatus.txId;\n _txHistory[txId] = {\n ...(_txHistory[txId] || {}),\n ...txStatus,\n updateTimestamp: Date.now(),\n };\n lsSet(\"txHistory\", _txHistory);\n events.notifyTxListeners(_txHistory[txId]);\n}\n\nexport const getConfig = (): NetworkConfig => {\n return _config;\n}\n\nexport const getTxHistory = (): TxHistory => {\n return _txHistory;\n}\n\n// Exposed \"write\" functions\nexport const setConfig = (newConf: NetworkConfig): void => {\n _config = { ...NETWORKS[newConf.networkId], ...newConf };\n lsSet(\"config\", _config);\n}\n\nexport const resetTxHistory = (): void => {\n _txHistory = {};\n lsSet(\"txHistory\", _txHistory);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAIO;AAEA,MAAM,qBAAqB;AAC3B,MAAM,WAAW;AAAA,EACtB,SAAS;AAAA,IACP,WAAW;AAAA,IACX,SAAS;AAAA,EACX;AAAA,EACA,SAAS;AAAA,IACP,WAAW;AAAA,IACX,SAAS;AAAA,EACX;AACF;AA0CO,IAAI,cAAyB,oBAAM,QAAQ,KAAK;AAAA,EACrD,GAAG,SAAS,kBAAkB;AAChC;AAGO,IAAI,aAAmB,oBAAM,OAAO,KAAK,CAAC;AAYjD,IAAI,kBAAyC;AAEtC,MAAM,oBAAoB,wBAAC,aAAmC;AACnE,oBAAkB;AACpB,GAFiC;AAI1B,MAAM,oBAAoB,6BAA6B;AAC5D,SAAO;AACT,GAFiC;AAKjC,IAAI;AACF,SAAO,YAAY,OAAO,iBACtB,mCAAqB,OAAO,UAAU,IACtC;AACN,SAAS,GAAG;AACV,UAAQ,MAAM,8BAA8B,CAAC;AAC7C,SAAO,aAAa;AACpB,0BAAM,SAAS,IAAI;AACrB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