@fastnear/api 0.3.0 → 0.4.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.
@@ -656,7 +656,7 @@ function parseJsonFromBytes(bytes) {
656
656
  }
657
657
  }
658
658
  function withBlockId(params, blockId) {
659
- return blockId === "final" || blockId === "optimistic" ? { ...params, finality: blockId } : !!blockId ? { ...params, block_id: blockId } : { ...params, finality: "optimistic" };
659
+ return blockId === "final" || blockId === "optimistic" ? { ...params, finality: blockId } : blockId ? { ...params, block_id: blockId } : { ...params, finality: "optimistic" };
660
660
  }
661
661
  async function queryRpc(method, params) {
662
662
  const response = await fetch(_config.nodeUrl, {
@@ -752,10 +752,10 @@ function convertUnit(s, ...args) {
752
752
  });
753
753
  }
754
754
  if (typeof s == "string") {
755
- let match = s.match(/([0-9.,_]+)\s*([a-zA-Z]+)?/);
755
+ const match = s.match(/([0-9.,_]+)\s*([a-zA-Z]+)?/);
756
756
  if (match) {
757
- let amount = match[1].replace(/[_,]/g, "");
758
- let unitPart = match[2];
757
+ const amount = match[1].replace(/[_,]/g, "");
758
+ const unitPart = match[2];
759
759
  if (unitPart) {
760
760
  switch (unitPart.toLowerCase()) {
761
761
  case "near":
@@ -765,9 +765,10 @@ function convertUnit(s, ...args) {
765
765
  case "ggas":
766
766
  return (0, import_big2.default)(amount).mul((0, import_big2.default)(10).pow(9)).toFixed(0);
767
767
  case "gas":
768
+ case "yoctonear":
768
769
  return (0, import_big2.default)(amount).toFixed(0);
769
770
  default:
770
- throw new Error(`Unknown unit: ${unit}`);
771
+ throw new Error(`Unknown unit: ${unitPart}`);
771
772
  }
772
773
  } else {
773
774
  return (0, import_big2.default)(amount).toFixed(0);
@@ -818,7 +819,13 @@ var api = {
818
819
  return "SignedIn";
819
820
  },
820
821
  // Query Methods
821
- async view({ contractId, methodName, args, argsBase64, blockId }) {
822
+ async view({
823
+ contractId,
824
+ methodName,
825
+ args,
826
+ argsBase64,
827
+ blockId
828
+ }) {
822
829
  const encodedArgs = argsBase64 || (args ? toBase64(JSON.stringify(args)) : "");
823
830
  const result = await queryRpc(
824
831
  "query",
@@ -834,7 +841,10 @@ var api = {
834
841
  );
835
842
  return parseJsonFromBytes(result.result);
836
843
  },
837
- async account({ accountId, blockId }) {
844
+ async account({
845
+ accountId,
846
+ blockId
847
+ }) {
838
848
  return queryRpc(
839
849
  "query",
840
850
  withBlockId(
@@ -849,7 +859,11 @@ var api = {
849
859
  async block({ blockId }) {
850
860
  return queryRpc("block", withBlockId({}, blockId));
851
861
  },
852
- async accessKey({ accountId, publicKey, blockId }) {
862
+ async accessKey({
863
+ accountId,
864
+ publicKey,
865
+ blockId
866
+ }) {
853
867
  return queryRpc(
854
868
  "query",
855
869
  withBlockId(
@@ -869,7 +883,11 @@ var api = {
869
883
  return [..._txHistory];
870
884
  },
871
885
  // Transaction Methods
872
- async sendTx({ receiverId, actions, waitUntil }) {
886
+ async sendTx({
887
+ receiverId,
888
+ actions,
889
+ waitUntil
890
+ }) {
873
891
  const signerId = _state.accountId;
874
892
  if (!signerId) {
875
893
  throw new Error("Not signed in");
@@ -889,7 +907,7 @@ var api = {
889
907
  tx: jsonTransaction2,
890
908
  finalState: false
891
909
  });
892
- const url = new URL(window.location.href);
910
+ const url = new URL(typeof window !== "undefined" ? window.location.href : "");
893
911
  url.searchParams.set("txIds", txId);
894
912
  _adapter.sendTransactions({
895
913
  transactions: [jsonTransaction2],
@@ -898,16 +916,18 @@ var api = {
898
916
  console.log("Transaction result:", result);
899
917
  if (result.url) {
900
918
  console.log("Redirecting to wallet:", result.url);
901
- setTimeout(() => {
902
- window.location.href = result.url;
903
- }, 100);
919
+ if (typeof window !== "undefined") {
920
+ setTimeout(() => {
921
+ window.location.href = result.url;
922
+ }, 100);
923
+ }
904
924
  } else if (result.outcomes) {
905
- result.outcomes.forEach((result2) => {
925
+ result.outcomes.forEach((r) => {
906
926
  updateTxHistory({
907
927
  txId,
908
928
  status: "Executed",
909
- result: result2,
910
- txHash: result2.transaction.hash,
929
+ result: r,
930
+ txHash: r.transaction.hash,
911
931
  finalState: true
912
932
  });
913
933
  });
@@ -935,10 +955,11 @@ var api = {
935
955
  });
936
956
  return txId;
937
957
  }
938
- const toDoPromises = {};
939
958
  let nonce = lsGet("nonce");
959
+ let block = lsGet("block");
960
+ const toDoPromises = {};
940
961
  if (nonce === null || nonce === void 0) {
941
- toDoPromises.nonce = this.accessKey({
962
+ toDoPromises.nonce = api.accessKey({
942
963
  accountId: signerId,
943
964
  publicKey
944
965
  }).then((accessKey) => {
@@ -949,30 +970,30 @@ var api = {
949
970
  return accessKey.nonce;
950
971
  });
951
972
  }
952
- let block = lsGet("block");
953
- if (!block || parseFloat(block.header.timestamp_nanosec) / 1e6 + MaxBlockDelayMs < Date.now()) {
954
- toDoPromises.block = this.block({ blockId: "final" }).then((block2) => {
955
- block2 = {
973
+ if (!block || !block.header || parseFloat(block.header.timestamp_nanosec) / 1e6 + MaxBlockDelayMs < Date.now()) {
974
+ toDoPromises.block = api.block({ blockId: "final" }).then((b) => {
975
+ const newBlock = {
956
976
  header: {
957
- prev_hash: block2.header.prev_hash,
958
- timestamp_nanosec: block2.header.timestamp_nanosec
977
+ prev_hash: b.header.prev_hash,
978
+ timestamp_nanosec: b.header.timestamp_nanosec
959
979
  }
960
980
  };
961
- lsSet("block", block2);
962
- return block2;
981
+ lsSet("block", newBlock);
982
+ return newBlock;
963
983
  });
964
984
  }
965
985
  if (Object.keys(toDoPromises).length > 0) {
966
- let results = await Promise.all(Object.values(toDoPromises));
967
- for (let i = 0; i < results.length; i++) {
968
- if (Object.keys(toDoPromises)[i] === "nonce") {
969
- nonce = results[i];
970
- } else if (Object.keys(toDoPromises)[i] === "block") {
971
- block = results[i];
986
+ const results = await Promise.all(Object.values(toDoPromises));
987
+ const keys = Object.keys(toDoPromises);
988
+ results.forEach((res, i) => {
989
+ if (keys[i] === "nonce") {
990
+ nonce = res;
991
+ } else if (keys[i] === "block") {
992
+ block = res;
972
993
  }
973
- }
994
+ });
974
995
  }
975
- const newNonce = nonce + 1;
996
+ const newNonce = (nonce ?? 0) + 1;
976
997
  lsSet("nonce", newNonce);
977
998
  const blockHash = block.header.prev_hash;
978
999
  const jsonTransaction = {
@@ -987,11 +1008,8 @@ var api = {
987
1008
  const transaction = serializeTransaction(jsonTransaction);
988
1009
  const txHash = (0, import_base58_js.binary_to_base58)(import_sha2.sha256(transaction));
989
1010
  const signature = signHash(txHash, privateKey);
990
- const singedTransaction = serializeSignedTransaction(
991
- jsonTransaction,
992
- signature
993
- );
994
- const signedTxBase64 = toBase64(singedTransaction);
1011
+ const signedTransaction = serializeSignedTransaction(jsonTransaction, signature);
1012
+ const signedTxBase64 = toBase64(signedTransaction);
995
1013
  updateTxHistory({
996
1014
  status: "Pending",
997
1015
  txId,
@@ -1024,9 +1042,11 @@ var api = {
1024
1042
  }
1025
1043
  if (result.url) {
1026
1044
  console.log("Redirecting to wallet:", result.url);
1027
- setTimeout(() => {
1028
- window.location.href = result.url;
1029
- }, 100);
1045
+ if (typeof window !== "undefined") {
1046
+ setTimeout(() => {
1047
+ window.location.href = result.url;
1048
+ }, 100);
1049
+ }
1030
1050
  } else if (result.accountId) {
1031
1051
  updateState({
1032
1052
  accountId: result.accountId
@@ -1059,7 +1079,13 @@ var api = {
1059
1079
  },
1060
1080
  // Action Helpers
1061
1081
  actions: {
1062
- functionCall: ({ methodName, gas, deposit, args, argsBase64 }) => ({
1082
+ functionCall: ({
1083
+ methodName,
1084
+ gas,
1085
+ deposit,
1086
+ args,
1087
+ argsBase64
1088
+ }) => ({
1063
1089
  type: "FunctionCall",
1064
1090
  methodName,
1065
1091
  args,
@@ -1120,66 +1146,68 @@ var api = {
1120
1146
  }
1121
1147
  };
1122
1148
  try {
1123
- const url = new URL(window.location.href);
1124
- const accountId = url.searchParams.get("account_id");
1125
- const publicKey = url.searchParams.get("public_key");
1126
- const errorCode = url.searchParams.get("errorCode");
1127
- const errorMessage = url.searchParams.get("errorMessage");
1128
- const transactionHashes = url.searchParams.get("transactionHashes");
1129
- const txIds = url.searchParams.get("txIds");
1130
- if (errorCode || errorMessage) {
1131
- console.warn(new Error(`Wallet error: ${errorCode} ${errorMessage}`));
1132
- }
1133
- if (accountId && publicKey) {
1134
- if (publicKey === _state.publicKey) {
1135
- updateState({
1136
- accountId
1137
- });
1138
- } else {
1139
- console.error(
1140
- new Error("Public key mismatch from wallet redirect"),
1141
- publicKey,
1142
- _state.publicKey
1143
- );
1149
+ if (typeof window !== "undefined") {
1150
+ const url = new URL(window.location.href);
1151
+ const accountId = url.searchParams.get("account_id");
1152
+ const publicKey = url.searchParams.get("public_key");
1153
+ const errorCode = url.searchParams.get("errorCode");
1154
+ const errorMessage = url.searchParams.get("errorMessage");
1155
+ const transactionHashes = url.searchParams.get("transactionHashes");
1156
+ const txIds = url.searchParams.get("txIds");
1157
+ if (errorCode || errorMessage) {
1158
+ console.warn(new Error(`Wallet error: ${errorCode} ${errorMessage}`));
1144
1159
  }
1145
- }
1146
- if (transactionHashes || txIds) {
1147
- const txHashes = transactionHashes ? transactionHashes.split(",") : [];
1148
- const txIdsArray = txIds ? txIds.split(",") : [];
1149
- if (txIdsArray.length > txHashes.length) {
1150
- txIdsArray.forEach((txId, i) => {
1151
- updateTxHistory({
1152
- txId,
1153
- status: "RejectedByUser",
1154
- finalState: true
1160
+ if (accountId && publicKey) {
1161
+ if (publicKey === _state.publicKey) {
1162
+ updateState({
1163
+ accountId
1155
1164
  });
1156
- });
1157
- } else if (txIdsArray.length === txHashes.length) {
1158
- txIdsArray.forEach((txId, i) => {
1159
- updateTxHistory({
1160
- txId,
1161
- status: "PendingGotTxHash",
1162
- txHash: txHashes[i],
1163
- finalState: false
1165
+ } else {
1166
+ console.error(
1167
+ new Error("Public key mismatch from wallet redirect"),
1168
+ publicKey,
1169
+ _state.publicKey
1170
+ );
1171
+ }
1172
+ }
1173
+ if (transactionHashes || txIds) {
1174
+ const txHashes = transactionHashes ? transactionHashes.split(",") : [];
1175
+ const txIdsArray = txIds ? txIds.split(",") : [];
1176
+ if (txIdsArray.length > txHashes.length) {
1177
+ txIdsArray.forEach((txId, i) => {
1178
+ updateTxHistory({
1179
+ txId,
1180
+ status: "RejectedByUser",
1181
+ finalState: true
1182
+ });
1164
1183
  });
1165
- afterTxSent(txId);
1166
- });
1167
- } else {
1168
- console.error(
1169
- new Error("Transaction hash mismatch from wallet redirect"),
1170
- txIdsArray,
1171
- txHashes
1172
- );
1184
+ } else if (txIdsArray.length === txHashes.length) {
1185
+ txIdsArray.forEach((txId, i) => {
1186
+ updateTxHistory({
1187
+ txId,
1188
+ status: "PendingGotTxHash",
1189
+ txHash: txHashes[i],
1190
+ finalState: false
1191
+ });
1192
+ afterTxSent(txId);
1193
+ });
1194
+ } else {
1195
+ console.error(
1196
+ new Error("Transaction hash mismatch from wallet redirect"),
1197
+ txIdsArray,
1198
+ txHashes
1199
+ );
1200
+ }
1173
1201
  }
1202
+ url.searchParams.delete("account_id");
1203
+ url.searchParams.delete("public_key");
1204
+ url.searchParams.delete("errorCode");
1205
+ url.searchParams.delete("errorMessage");
1206
+ url.searchParams.delete("all_keys");
1207
+ url.searchParams.delete("transactionHashes");
1208
+ url.searchParams.delete("txIds");
1209
+ window.history.replaceState({}, "", url.toString());
1174
1210
  }
1175
- url.searchParams.delete("account_id");
1176
- url.searchParams.delete("public_key");
1177
- url.searchParams.delete("errorCode");
1178
- url.searchParams.delete("errorMessage");
1179
- url.searchParams.delete("all_keys");
1180
- url.searchParams.delete("transactionHashes");
1181
- url.searchParams.delete("txIds");
1182
- window.history.replaceState({}, "", url.toString());
1183
1211
  } catch (e) {
1184
1212
  console.error("Error handling wallet redirect:", e);
1185
1213
  }