@fastnear/api 0.7.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- /* ⋈ 🏃🏻💨 FastNEAR API - CJS (@fastnear/api version 0.7.0) */
2
- /* https://www.npmjs.com/package/@fastnear/api/v/0.7.0 */
1
+ /* ⋈ 🏃🏻💨 FastNEAR API - CJS (@fastnear/api version 0.8.0) */
2
+ /* https://www.npmjs.com/package/@fastnear/api/v/0.8.0 */
3
3
  "use strict";
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -17,11 +17,9 @@ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "defau
17
17
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
18
  var src_exports = {};
19
19
  module.exports = __toCommonJS(src_exports);
20
- __reExport(src_exports, require("./state.js"), module.exports);
21
20
  __reExport(src_exports, require("./near.js"), module.exports);
22
21
  // Annotate the CommonJS export names for ESM import in node:
23
22
  0 && (module.exports = {
24
- ...require("./state.js"),
25
23
  ...require("./near.js")
26
24
  });
27
25
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["// See tsup.config.ts for additional banner/footer js\nexport * from \"./state.js\"\nexport * from \"./near.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AAAA;AACA,wBAAc,uBADd;AAEA,wBAAc,sBAFd;","names":[]}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["// See tsup.config.ts for additional banner/footer js\nexport * from \"./near.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AAAA;AACA,wBAAc,sBADd;","names":[]}
@@ -1,18 +1,5 @@
1
- import { WalletAdapter } from '@fastnear/wallet-adapter';
2
1
  import * as borsh from 'borsh';
3
2
 
4
- declare const WIDGET_URL = "https://wallet-adapter.fastnear.com";
5
- declare const DEFAULT_NETWORK_ID = "mainnet";
6
- declare const NETWORKS: {
7
- testnet: {
8
- networkId: string;
9
- nodeUrl: string;
10
- };
11
- mainnet: {
12
- networkId: string;
13
- nodeUrl: string;
14
- };
15
- };
16
3
  interface NetworkConfig {
17
4
  networkId: string;
18
5
  nodeUrl?: string;
@@ -21,63 +8,42 @@ interface NetworkConfig {
21
8
  explorerUrl?: string;
22
9
  [key: string]: any;
23
10
  }
24
- interface AppState {
25
- accountId?: string | null;
26
- privateKey?: string | null;
27
- lastWalletId?: string | null;
28
- publicKey?: string | null;
29
- accessKeyContractId?: string | null;
30
- [key: string]: any;
31
- }
32
11
  interface TxStatus {
33
12
  txId: string;
34
13
  updateTimestamp?: number;
35
14
  [key: string]: any;
36
15
  }
37
16
  type TxHistory = Record<string, TxStatus>;
38
- interface EventListeners {
39
- account: Set<(accountId: string) => void>;
40
- tx: Set<(tx: TxStatus) => void>;
41
- }
42
- interface UnbroadcastedEvents {
43
- account: string[];
44
- tx: TxStatus[];
45
- }
46
- interface WalletAdapterState {
47
- publicKey?: string | null;
48
- privateKey?: string | null;
49
- accountId?: string | null;
50
- lastWalletId?: string | null;
51
- networkId: string;
52
- }
53
- declare let _config: NetworkConfig;
54
- declare let _state: AppState;
55
- declare const onAdapterStateUpdate: (state: WalletAdapterState) => void;
56
- declare const getWalletAdapterState: () => WalletAdapterState;
57
- declare let _adapter: WalletAdapter;
58
- declare let _txHistory: TxHistory;
59
- declare const _eventListeners: EventListeners;
60
- declare const _unbroadcastedEvents: UnbroadcastedEvents;
61
- declare const updateState: (newState: Partial<AppState>) => void;
62
- declare const updateTxHistory: (txStatus: TxStatus) => void;
63
- declare const notifyAccountListeners: (accountId: string) => void;
64
- declare const notifyTxListeners: (tx: TxStatus) => void;
65
- declare const onAccount: (callback: (accountId: string) => void) => void;
66
- declare const onTx: (callback: (tx: TxStatus) => void) => void;
67
- declare const getConfig: () => NetworkConfig;
68
- declare const getTxHistory: () => TxHistory;
69
- declare const setConfig: (newConf: NetworkConfig) => void;
70
- declare const resetTxHistory: () => void;
71
17
 
72
18
  declare const MaxBlockDelayMs: number;
73
19
  interface AccessKeyWithError {
74
- nonce: number;
75
- permission?: any;
20
+ result: {
21
+ nonce: number;
22
+ permission?: any;
23
+ error?: string;
24
+ };
25
+ }
26
+ interface WalletTxResult {
27
+ url?: string;
28
+ outcomes?: Array<{
29
+ transaction: {
30
+ hash: string;
31
+ };
32
+ }>;
33
+ rejected?: boolean;
76
34
  error?: string;
77
35
  }
78
36
  interface BlockView {
37
+ result: {
38
+ header: {
39
+ hash: string;
40
+ timestamp_nanosec: string;
41
+ };
42
+ };
43
+ }
44
+ interface LastKnownBlock {
79
45
  header: {
80
- prev_hash: string;
46
+ hash: string;
81
47
  timestamp_nanosec: string;
82
48
  };
83
49
  }
@@ -86,7 +52,7 @@ declare function withBlockId(params: Record<string, any>, blockId?: string): {
86
52
  } | {
87
53
  block_id: string;
88
54
  };
89
- declare function queryRpc(method: string, params: Record<string, any> | any[]): Promise<any>;
55
+ declare function sendRpc(method: string, params: Record<string, any> | any[]): Promise<any>;
90
56
  declare function afterTxSent(txId: string): void;
91
57
  declare function sendTxToRpc(signedTxBase64: string, waitUntil: string | undefined, txId: string): Promise<any>;
92
58
  interface AccessKeyView {
@@ -110,6 +76,17 @@ declare const accountId: () => string | null | undefined;
110
76
  declare const publicKey: () => string | null | undefined;
111
77
  declare const config: (newConfig?: Record<string, any>) => NetworkConfig;
112
78
  declare const authStatus: () => string | Record<string, any>;
79
+ declare const getPublicKeyForContract: (opts?: any) => string | null | undefined;
80
+ declare const selected: () => {
81
+ network: string;
82
+ nodeUrl: string | undefined;
83
+ walletUrl: string | undefined;
84
+ helperUrl: string | undefined;
85
+ explorerUrl: string | undefined;
86
+ account: string | null | undefined;
87
+ contract: string | null | undefined;
88
+ publicKey: string | null | undefined;
89
+ };
113
90
  declare const requestSignIn: ({ contractId }: {
114
91
  contractId: string;
115
92
  }) => Promise<void>;
@@ -177,6 +154,8 @@ declare const exp: {
177
154
  };
178
155
  };
179
156
  declare const utils: {};
157
+ declare const state: {};
158
+ declare const event: any;
180
159
  declare const actions: {
181
160
  functionCall: ({ methodName, gas, deposit, args, argsBase64, }: {
182
161
  methodName: string;
@@ -251,4 +230,4 @@ declare const actions: {
251
230
  };
252
231
  };
253
232
 
254
- export { type AccessKeyView, type AppState, DEFAULT_NETWORK_ID, type EventListeners, MaxBlockDelayMs, NETWORKS, type NetworkConfig, type TxHistory, type TxStatus, type UnbroadcastedEvents, WIDGET_URL, type WalletAdapterState, _adapter, _config, _eventListeners, _state, _txHistory, _unbroadcastedEvents, accountId, actions, afterTxSent, authStatus, config, exp, generateTxId, getConfig, getTxHistory, getWalletAdapterState, localTxHistory, notifyAccountListeners, notifyTxListeners, onAccount, onAdapterStateUpdate, onTx, publicKey, queryAccessKey, queryAccount, queryBlock, queryRpc, queryTx, requestSignIn, resetTxHistory, sendTx, sendTxToRpc, setConfig, signOut, updateState, updateTxHistory, utils, view, withBlockId };
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 };
package/dist/cjs/near.cjs CHANGED
@@ -1,5 +1,5 @@
1
- /* ⋈ 🏃🏻💨 FastNEAR API - CJS (@fastnear/api version 0.7.0) */
2
- /* https://www.npmjs.com/package/@fastnear/api/v/0.7.0 */
1
+ /* ⋈ 🏃🏻💨 FastNEAR API - CJS (@fastnear/api version 0.8.0) */
2
+ /* https://www.npmjs.com/package/@fastnear/api/v/0.8.0 */
3
3
  "use strict";
4
4
  var __create = Object.create;
5
5
  var __defProp = Object.defineProperty;
@@ -37,19 +37,23 @@ __export(near_exports, {
37
37
  afterTxSent: () => afterTxSent,
38
38
  authStatus: () => authStatus,
39
39
  config: () => config,
40
+ event: () => event,
40
41
  exp: () => exp,
41
42
  generateTxId: () => generateTxId,
43
+ getPublicKeyForContract: () => getPublicKeyForContract,
42
44
  localTxHistory: () => localTxHistory,
43
45
  publicKey: () => publicKey,
44
46
  queryAccessKey: () => queryAccessKey,
45
47
  queryAccount: () => queryAccount,
46
48
  queryBlock: () => queryBlock,
47
- queryRpc: () => queryRpc,
48
49
  queryTx: () => queryTx,
49
50
  requestSignIn: () => requestSignIn,
51
+ selected: () => selected,
52
+ sendRpc: () => sendRpc,
50
53
  sendTx: () => sendTx,
51
54
  sendTxToRpc: () => sendTxToRpc,
52
55
  signOut: () => signOut,
56
+ state: () => state,
53
57
  utils: () => utils,
54
58
  view: () => view,
55
59
  withBlockId: () => withBlockId
@@ -61,6 +65,7 @@ var import_state = require("./state.js");
61
65
  var import_state2 = require("./state.js");
62
66
  var import_sha2 = require("@noble/hashes/sha2");
63
67
  var reExportAllUtils = __toESM(require("@fastnear/utils"), 1);
68
+ var stateExports = __toESM(require("./state.js"), 1);
64
69
  import_big.default.DP = 27;
65
70
  const MaxBlockDelayMs = 1e3 * 60 * 60 * 6;
66
71
  function withBlockId(params, blockId) {
@@ -70,7 +75,7 @@ function withBlockId(params, blockId) {
70
75
  return blockId ? { ...params, block_id: blockId } : { ...params, finality: "optimistic" };
71
76
  }
72
77
  __name(withBlockId, "withBlockId");
73
- async function queryRpc(method, params) {
78
+ async function sendRpc(method, params) {
74
79
  const config2 = (0, import_state2.getConfig)();
75
80
  if (!config2?.nodeUrl) {
76
81
  throw new Error("fastnear: getConfig() returned invalid config: missing nodeUrl.");
@@ -89,17 +94,17 @@ async function queryRpc(method, params) {
89
94
  if (result.error) {
90
95
  throw new Error(JSON.stringify(result.error));
91
96
  }
92
- return result.result;
97
+ return result;
93
98
  }
94
- __name(queryRpc, "queryRpc");
99
+ __name(sendRpc, "sendRpc");
95
100
  function afterTxSent(txId) {
96
101
  const txHistory = (0, import_state.getTxHistory)();
97
- queryRpc("tx", {
102
+ sendRpc("tx", {
98
103
  tx_hash: txHistory[txId]?.txHash,
99
104
  sender_account_id: txHistory[txId]?.tx?.signerId,
100
105
  wait_until: "EXECUTED_OPTIMISTIC"
101
106
  }).then((result) => {
102
- const successValue = result?.status?.SuccessValue;
107
+ const successValue = result?.result?.status?.SuccessValue;
103
108
  (0, import_state.updateTxHistory)({
104
109
  txId,
105
110
  status: "Executed",
@@ -120,7 +125,7 @@ __name(afterTxSent, "afterTxSent");
120
125
  async function sendTxToRpc(signedTxBase64, waitUntil, txId) {
121
126
  waitUntil = waitUntil || "INCLUDED";
122
127
  try {
123
- const sendTxRes = await queryRpc("send_tx", {
128
+ const sendTxRes = await sendRpc("send_tx", {
124
129
  signed_tx_base64: signedTxBase64,
125
130
  wait_until: waitUntil
126
131
  });
@@ -151,7 +156,7 @@ const config = /* @__PURE__ */ __name((newConfig) => {
151
156
  if (newConfig) {
152
157
  if (newConfig.networkId && current.networkId !== newConfig.networkId) {
153
158
  (0, import_state2.setConfig)(newConfig.networkId);
154
- (0, import_state.updateState)({ accountId: null, privateKey: null, lastWalletId: null });
159
+ (0, import_state.update)({ accountId: null, privateKey: null, lastWalletId: null });
155
160
  (0, import_utils.lsSet)("block", null);
156
161
  (0, import_state2.resetTxHistory)();
157
162
  }
@@ -165,9 +170,32 @@ const authStatus = /* @__PURE__ */ __name(() => {
165
170
  }
166
171
  return "SignedIn";
167
172
  }, "authStatus");
173
+ const getPublicKeyForContract = /* @__PURE__ */ __name((opts) => {
174
+ return publicKey();
175
+ }, "getPublicKeyForContract");
176
+ const selected = /* @__PURE__ */ __name(() => {
177
+ const network = (0, import_state2.getConfig)().networkId;
178
+ const nodeUrl = (0, import_state2.getConfig)().nodeUrl;
179
+ const walletUrl = (0, import_state2.getConfig)().walletUrl;
180
+ const helperUrl = (0, import_state2.getConfig)().helperUrl;
181
+ const explorerUrl = (0, import_state2.getConfig)().explorerUrl;
182
+ const account = accountId();
183
+ const contract = import_state._state.accessKeyContractId;
184
+ const publicKey2 = getPublicKeyForContract();
185
+ return {
186
+ network,
187
+ nodeUrl,
188
+ walletUrl,
189
+ helperUrl,
190
+ explorerUrl,
191
+ account,
192
+ contract,
193
+ publicKey: publicKey2
194
+ };
195
+ }, "selected");
168
196
  const requestSignIn = /* @__PURE__ */ __name(async ({ contractId }) => {
169
197
  const privateKey = (0, import_utils.privateKeyFromRandom)();
170
- (0, import_state.updateState)({ accessKeyContractId: contractId, accountId: null, privateKey });
198
+ (0, import_state.update)({ accessKeyContractId: contractId, accountId: null, privateKey });
171
199
  const pubKey = (0, import_utils.publicKeyFromPrivate)(privateKey);
172
200
  const result = await import_state._adapter.signIn({
173
201
  networkId: (0, import_state2.getConfig)().networkId,
@@ -184,7 +212,7 @@ const requestSignIn = /* @__PURE__ */ __name(async ({ contractId }) => {
184
212
  }, 100);
185
213
  }
186
214
  } else if (result.accountId) {
187
- (0, import_state.updateState)({ accountId: result.accountId });
215
+ (0, import_state.update)({ accountId: result.accountId });
188
216
  }
189
217
  }, "requestSignIn");
190
218
  const view = /* @__PURE__ */ __name(async ({
@@ -195,7 +223,7 @@ const view = /* @__PURE__ */ __name(async ({
195
223
  blockId
196
224
  }) => {
197
225
  const encodedArgs = argsBase64 || (args ? (0, import_utils.toBase64)(JSON.stringify(args)) : "");
198
- const result = await queryRpc(
226
+ const queryResult = await sendRpc(
199
227
  "query",
200
228
  withBlockId(
201
229
  {
@@ -207,26 +235,26 @@ const view = /* @__PURE__ */ __name(async ({
207
235
  blockId
208
236
  )
209
237
  );
210
- return (0, import_utils.parseJsonFromBytes)(result.result);
238
+ return (0, import_utils.parseJsonFromBytes)(queryResult.result.result);
211
239
  }, "view");
212
240
  const queryAccount = /* @__PURE__ */ __name(async ({
213
241
  accountId: accountId2,
214
242
  blockId
215
243
  }) => {
216
- return queryRpc(
244
+ return sendRpc(
217
245
  "query",
218
246
  withBlockId({ request_type: "view_account", account_id: accountId2 }, blockId)
219
247
  );
220
248
  }, "queryAccount");
221
249
  const queryBlock = /* @__PURE__ */ __name(async ({ blockId }) => {
222
- return queryRpc("block", withBlockId({}, blockId));
250
+ return sendRpc("block", withBlockId({}, blockId));
223
251
  }, "queryBlock");
224
252
  const queryAccessKey = /* @__PURE__ */ __name(async ({
225
253
  accountId: accountId2,
226
254
  publicKey: publicKey2,
227
255
  blockId
228
256
  }) => {
229
- return queryRpc(
257
+ return sendRpc(
230
258
  "query",
231
259
  withBlockId(
232
260
  { request_type: "view_access_key", account_id: accountId2, public_key: publicKey2 },
@@ -235,13 +263,13 @@ const queryAccessKey = /* @__PURE__ */ __name(async ({
235
263
  );
236
264
  }, "queryAccessKey");
237
265
  const queryTx = /* @__PURE__ */ __name(async ({ txHash, accountId: accountId2 }) => {
238
- return queryRpc("tx", [txHash, accountId2]);
266
+ return sendRpc("tx", [txHash, accountId2]);
239
267
  }, "queryTx");
240
268
  const localTxHistory = /* @__PURE__ */ __name(() => {
241
269
  return (0, import_state.getTxHistory)();
242
270
  }, "localTxHistory");
243
271
  const signOut = /* @__PURE__ */ __name(() => {
244
- (0, import_state.updateState)({ accountId: null, privateKey: null, contractId: null });
272
+ (0, import_state.update)({ accountId: null, privateKey: null, contractId: null });
245
273
  (0, import_state2.setConfig)(import_state.NETWORKS[import_state.DEFAULT_NETWORK_ID]);
246
274
  }, "signOut");
247
275
  const sendTx = /* @__PURE__ */ __name(async ({
@@ -259,6 +287,14 @@ const sendTx = /* @__PURE__ */ __name(async ({
259
287
  (0, import_state.updateTxHistory)({ status: "Pending", txId, tx: jsonTx, finalState: false });
260
288
  const url = new URL(typeof window !== "undefined" ? window.location.href : "");
261
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");
262
298
  try {
263
299
  const result = await import_state._adapter.sendTransactions({
264
300
  transactions: [jsonTx],
@@ -305,10 +341,10 @@ const sendTx = /* @__PURE__ */ __name(async ({
305
341
  let nonce = (0, import_utils.lsGet)("nonce");
306
342
  if (nonce == null) {
307
343
  const accessKey = await queryAccessKey({ accountId: signerId, publicKey: publicKey2 });
308
- if (accessKey.error) {
309
- throw new Error(`Access key error: ${accessKey.error} when attempting to get nonce for ${signerId} for public key ${publicKey2}`);
344
+ 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}`);
310
346
  }
311
- nonce = accessKey.nonce;
347
+ nonce = accessKey.result.nonce;
312
348
  (0, import_utils.lsSet)("nonce", nonce);
313
349
  }
314
350
  let lastKnownBlock = (0, import_utils.lsGet)("block");
@@ -316,15 +352,15 @@ const sendTx = /* @__PURE__ */ __name(async ({
316
352
  const latestBlock = await queryBlock({ blockId: "final" });
317
353
  lastKnownBlock = {
318
354
  header: {
319
- prev_hash: latestBlock.header.prev_hash,
320
- timestamp_nanosec: latestBlock.header.timestamp_nanosec
355
+ hash: latestBlock.result.header.hash,
356
+ timestamp_nanosec: latestBlock.result.header.timestamp_nanosec
321
357
  }
322
358
  };
323
359
  (0, import_utils.lsSet)("block", lastKnownBlock);
324
360
  }
325
361
  nonce += 1;
326
362
  (0, import_utils.lsSet)("nonce", nonce);
327
- const blockHash = lastKnownBlock.header.prev_hash;
363
+ const blockHash = lastKnownBlock.header.hash;
328
364
  const plainTransactionObj = {
329
365
  signerId,
330
366
  publicKey: publicKey2,
@@ -364,6 +400,12 @@ for (const key in reExportAllUtils) {
364
400
  exp.utils[key] = reExportAllUtils[key];
365
401
  }
366
402
  const utils = exp.utils;
403
+ const state = {};
404
+ for (const key in stateExports) {
405
+ state[key] = stateExports[key];
406
+ }
407
+ const event = state["events"];
408
+ delete state["events"];
367
409
  try {
368
410
  if (typeof window !== "undefined") {
369
411
  const url = new URL(window.location.href);
@@ -371,16 +413,22 @@ try {
371
413
  const pubKey = url.searchParams.get("public_key");
372
414
  const errCode = url.searchParams.get("errorCode");
373
415
  const errMsg = url.searchParams.get("errorMessage");
416
+ const decodedErrMsg = errMsg ? decodeURIComponent(errMsg) : null;
374
417
  const txHashes = url.searchParams.get("transactionHashes");
375
418
  const txIds = url.searchParams.get("txIds");
376
419
  if (errCode || errMsg) {
377
- console.warn(new Error(`Wallet error: ${errCode} ${errMsg}`));
420
+ console.warn(new Error(`Wallet raises:
421
+ code: ${errCode}
422
+ message: ${decodedErrMsg}`));
378
423
  }
379
424
  if (accId && pubKey) {
380
425
  if (pubKey === import_state._state.publicKey) {
381
- (0, import_state.updateState)({ accountId: accId });
426
+ (0, import_state.update)({ accountId: accId });
382
427
  } else {
383
- console.error(new Error("Public key mismatch from wallet redirect"), pubKey, import_state._state.publicKey);
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");
384
432
  }
385
433
  }
386
434
  if (txHashes || txIds) {
@@ -404,14 +452,6 @@ try {
404
452
  console.error(new Error("Transaction hash mismatch from wallet redirect"), idArr, hashArr);
405
453
  }
406
454
  }
407
- url.searchParams.delete("account_id");
408
- url.searchParams.delete("public_key");
409
- url.searchParams.delete("errorCode");
410
- url.searchParams.delete("errorMessage");
411
- url.searchParams.delete("all_keys");
412
- url.searchParams.delete("transactionHashes");
413
- url.searchParams.delete("txIds");
414
- window.history.replaceState({}, "", url.toString());
415
455
  }
416
456
  } catch (e) {
417
457
  console.error("Error handling wallet redirect:", e);
@@ -484,19 +524,23 @@ const actions = {
484
524
  afterTxSent,
485
525
  authStatus,
486
526
  config,
527
+ event,
487
528
  exp,
488
529
  generateTxId,
530
+ getPublicKeyForContract,
489
531
  localTxHistory,
490
532
  publicKey,
491
533
  queryAccessKey,
492
534
  queryAccount,
493
535
  queryBlock,
494
- queryRpc,
495
536
  queryTx,
496
537
  requestSignIn,
538
+ selected,
539
+ sendRpc,
497
540
  sendTx,
498
541
  sendTxToRpc,
499
542
  signOut,
543
+ state,
500
544
  utils,
501
545
  view,
502
546
  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 updateState,\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\";\n\nBig.DP = 27;\nexport const MaxBlockDelayMs = 1000 * 60 * 60 * 6; // 6 hours\n\ninterface AccessKeyWithError {\n nonce: number;\n permission?: any;\n error?: string;\n}\n\ninterface WalletTxResult {\n url?: string;\n outcomes?: Array<{ transaction: { hash: string } }>;\n rejected?: boolean;\n error?: string;\n}\n\ninterface BlockView {\n header: {\n prev_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 queryRpc(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.result;\n}\n\nexport function afterTxSent(txId: string) {\n const txHistory = getTxHistory();\n queryRpc(\"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?.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 queryRpc(\"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 updateState({ 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 requestSignIn = async ({ contractId }: { contractId: string }) => {\n const privateKey = privateKeyFromRandom();\n updateState({ 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 updateState({ 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 result = await queryRpc(\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 return parseJsonFromBytes(result.result);\n};\n\nexport const queryAccount = async ({\n accountId,\n blockId,\n }: {\n accountId: string;\n blockId?: string;\n}) => {\n return queryRpc(\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 queryRpc(\"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 queryRpc(\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 queryRpc(\"tx\", [txHash, accountId]);\n};\n\nexport const localTxHistory = () => {\n return getTxHistory();\n};\n\nexport const signOut = () => {\n updateState({ 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 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 //\n let nonce = lsGet(\"nonce\") as number | null;\n if (nonce == null) {\n const accessKey = await queryAccessKey({ accountId: signerId, publicKey: publicKey });\n if (accessKey.error) {\n throw new Error(`Access key error: ${accessKey.error} when attempting to get nonce for ${signerId} for public key ${publicKey}`);\n }\n nonce = accessKey.nonce;\n lsSet(\"nonce\", nonce);\n }\n\n let lastKnownBlock = lsGet(\"block\") as BlockView | 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 prev_hash: latestBlock.header.prev_hash,\n timestamp_nanosec: latestBlock.header.timestamp_nanosec,\n },\n };\n lsSet(\"block\", lastKnownBlock);\n }\n\n nonce += 1;\n lsSet(\"nonce\", nonce);\n\n const blockHash = lastKnownBlock.header.prev_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\nexport const utils = exp.utils;\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 txHashes = url.searchParams.get(\"transactionHashes\");\n const txIds = url.searchParams.get(\"txIds\");\n\n if (errCode || errMsg) {\n console.warn(new Error(`Wallet error: ${errCode} ${errMsg}`));\n }\n\n if (accId && pubKey) {\n if (pubKey === _state.publicKey) {\n updateState({ accountId: accId });\n } else {\n console.error(new Error(\"Public key mismatch from wallet redirect\"), pubKey, _state.publicKey);\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 url.searchParams.delete(\"account_id\");\n url.searchParams.delete(\"public_key\");\n url.searchParams.delete(\"errorCode\");\n url.searchParams.delete(\"errorMessage\");\n url.searchParams.delete(\"all_keys\");\n url.searchParams.delete(\"transactionHashes\");\n url.searchParams.delete(\"txIds\");\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,iBAAgB;AAChB,mBAcO;AAEP,mBAQO;AAEP,IAAAA,gBAIO;AAEP,kBAAuB;AACvB,uBAAkC;AAElC,WAAAC,QAAI,KAAK;AACF,MAAM,kBAAkB,MAAO,KAAK,KAAK;AAsBzC,SAAS,YAAY,QAA6B,SAAkB;AACzE,MAAI,YAAY,WAAW,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IACF;AAAA,EACF,IAnBqB;AAAA,EAqBrB,WAAW,wBAAC,EAAC,WAAAC,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","accountId","publicKey","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 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 // I'd like to keep this for posterity. for a bit.\n\n // url.searchParams.delete(\"account_id\");\n // url.searchParams.delete(\"public_key\");\n // url.searchParams.delete(\"txIds\");\n // url.searchParams.delete(\"errorCode\");\n // url.searchParams.delete(\"errorMessage\");\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: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