near-api-ts 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +31 -8
  2. package/dist/index.d.cts +3 -1
  3. package/dist/index.d.ts +3 -1
  4. package/package.json +3 -4
  5. package/src/_common/configs/constants.ts +5 -12
  6. package/src/_common/natError.ts +50 -0
  7. package/src/_common/schemas/borsh/index.ts +0 -1
  8. package/src/_common/schemas/borsh/transaction.ts +8 -0
  9. package/src/_common/schemas/zod/client.ts +34 -0
  10. package/src/_common/schemas/zod/common/accountId.ts +11 -0
  11. package/src/_common/schemas/zod/common/common.ts +16 -0
  12. package/src/_common/schemas/zod/common/cryptoHash.ts +25 -0
  13. package/src/_common/schemas/zod/common/curveString.ts +22 -0
  14. package/src/_common/schemas/zod/common/nearGas.ts +33 -0
  15. package/src/_common/schemas/zod/common/nearToken.ts +54 -0
  16. package/src/_common/schemas/zod/common/privateKey.ts +26 -0
  17. package/src/_common/schemas/zod/common/publicKey.ts +26 -0
  18. package/src/_common/schemas/zod/common/signature.ts +26 -0
  19. package/src/_common/schemas/zod/rpc.ts +58 -5
  20. package/src/_common/schemas/zod/transaction/actions/addKey.ts +29 -0
  21. package/src/_common/schemas/zod/transaction/actions/createAccount.ts +5 -0
  22. package/src/_common/schemas/zod/transaction/actions/deleteAccount.ts +11 -0
  23. package/src/_common/schemas/zod/transaction/actions/deleteKey.ts +9 -0
  24. package/src/_common/schemas/zod/transaction/actions/deployContract.ts +10 -0
  25. package/src/_common/schemas/zod/transaction/actions/functionCall.ts +14 -0
  26. package/src/_common/schemas/zod/transaction/actions/transfer.ts +9 -0
  27. package/src/_common/schemas/zod/transaction/transaction.ts +80 -0
  28. package/src/_common/transformers/toBorshBytes/transaction.ts +25 -9
  29. package/src/_common/transformers/{curveString.ts → toCurveString.ts} +1 -16
  30. package/src/_common/transformers/toNative/actions/addKey.ts +10 -12
  31. package/src/_common/transformers/toNative/actions/deleteAccount.ts +4 -6
  32. package/src/_common/transformers/toNative/actions/deleteKey.ts +4 -6
  33. package/src/_common/transformers/toNative/actions/deployContract.ts +6 -15
  34. package/src/_common/transformers/toNative/actions/functionCall.ts +12 -14
  35. package/src/_common/transformers/toNative/actions/transfer.ts +5 -7
  36. package/src/_common/transformers/toNative/blockReference.ts +1 -1
  37. package/src/_common/transformers/toNative/publicKey.ts +9 -7
  38. package/src/_common/transformers/toNative/signature.ts +9 -7
  39. package/src/_common/transformers/toNative/transaction.ts +23 -29
  40. package/src/_common/utils/asThrowable.ts +43 -0
  41. package/src/{helpers/crypto → _common/utils}/getTransactionHash.ts +5 -5
  42. package/src/_common/utils/repackError.ts +35 -0
  43. package/src/_common/utils/result.ts +6 -0
  44. package/src/_common/utils/sleep.ts +5 -18
  45. package/src/_common/utils/snakeToCamelCase.ts +1 -1
  46. package/src/_common/utils/wrapInternalError.ts +56 -0
  47. package/src/client/createClient.ts +81 -32
  48. package/src/client/methods/account/{helpers/transformKey.ts → _common/transformAccessKey.ts} +5 -5
  49. package/src/client/methods/account/getAccountAccessKey/getAccountAccessKey.ts +62 -0
  50. package/src/client/methods/account/getAccountAccessKey/handleError.ts +88 -0
  51. package/src/client/methods/account/getAccountAccessKey/handleResult.ts +84 -0
  52. package/src/client/methods/account/getAccountAccessKeys/getAccountAccessKeys.ts +59 -0
  53. package/src/client/methods/account/getAccountAccessKeys/handleError.ts +88 -0
  54. package/src/client/methods/account/getAccountAccessKeys/handleResult.ts +51 -0
  55. package/src/client/methods/account/getAccountInfo/getAccountInfo.ts +61 -0
  56. package/src/client/methods/account/getAccountInfo/handleError.ts +100 -0
  57. package/src/client/methods/account/getAccountInfo/handleResult.ts +83 -0
  58. package/src/client/methods/block/getBlock/getBlock.ts +53 -0
  59. package/src/client/methods/block/getBlock/handleError.ts +57 -0
  60. package/src/client/methods/block/getBlock/handleResult.ts +27 -0
  61. package/src/client/methods/contract/callContractReadFunction/callContractReadFunction.ts +80 -0
  62. package/src/client/methods/contract/callContractReadFunction/handleError.ts +86 -0
  63. package/src/client/methods/contract/callContractReadFunction/handleResult/deserializeCallResult.ts +31 -0
  64. package/src/client/methods/contract/callContractReadFunction/handleResult/handleResult.ts +80 -0
  65. package/src/client/methods/contract/callContractReadFunction/serializeFunctionArgs.ts +60 -0
  66. package/src/client/methods/protocol/getGasPrice.ts +10 -10
  67. package/src/client/methods/transaction/sendSignedTransaction/handleError/handleError.ts +52 -0
  68. package/src/client/methods/transaction/sendSignedTransaction/handleError/handleInvalidTransaction.ts +106 -0
  69. package/src/client/methods/transaction/sendSignedTransaction/handleResult/handleActionError.ts +69 -0
  70. package/src/client/methods/transaction/sendSignedTransaction/handleResult/handleResult.ts +46 -0
  71. package/src/client/methods/transaction/sendSignedTransaction/sendSignedTransaction.ts +57 -0
  72. package/src/client/presets/mainnet.ts +4 -3
  73. package/src/client/presets/testnet.ts +4 -4
  74. package/src/client/transport/createTransport.ts +38 -58
  75. package/src/client/transport/rpcEndpoints.ts +38 -0
  76. package/src/client/transport/sendRequest/1-createSendRequest/_common/getAvailableRpcs.ts +29 -22
  77. package/src/client/transport/sendRequest/1-createSendRequest/createExternalAbortSignal.ts +4 -5
  78. package/src/client/transport/sendRequest/1-createSendRequest/createRequestTimeout.ts +5 -7
  79. package/src/client/transport/sendRequest/1-createSendRequest/createSendRequest.ts +42 -36
  80. package/src/client/transport/sendRequest/1-createSendRequest/handleMaybeUnknownBlock.ts +14 -17
  81. package/src/client/transport/sendRequest/2-tryMultipleRounds/tryMultipleRounds.ts +28 -34
  82. package/src/client/transport/sendRequest/3-tryOneRound/tryOneRound.ts +28 -35
  83. package/src/client/transport/sendRequest/4-sendWithRetry/sendWithRetry.ts +26 -34
  84. package/src/client/transport/sendRequest/5-sendOnce/extractRpcErrors.ts +62 -0
  85. package/src/client/transport/sendRequest/5-sendOnce/fetchData/createAttemptTimeout.ts +6 -10
  86. package/src/client/transport/sendRequest/5-sendOnce/fetchData/fetchData.ts +27 -22
  87. package/src/client/transport/sendRequest/5-sendOnce/parseJsonResponse.ts +18 -11
  88. package/src/client/transport/sendRequest/5-sendOnce/sendOnce.ts +45 -66
  89. package/src/client/transport/transportPolicy.ts +46 -8
  90. package/src/helpers/actionCreators/addFullAccessKey.ts +32 -10
  91. package/src/helpers/actionCreators/addFunctionCallKey.ts +43 -16
  92. package/src/helpers/actionCreators/deleteAccount.ts +31 -7
  93. package/src/helpers/actionCreators/deleteKey.ts +33 -5
  94. package/src/helpers/actionCreators/deployContract.ts +41 -8
  95. package/src/helpers/actionCreators/functionCall.ts +107 -8
  96. package/src/helpers/actionCreators/transfer.ts +33 -5
  97. package/src/helpers/keyPair/_common/signByEd25519Key.ts +16 -0
  98. package/src/helpers/keyPair/_common/signBySecp256k1Key.ts +21 -0
  99. package/src/helpers/keyPair/keyPair.ts +61 -0
  100. package/src/helpers/keyPair/randomEd25519KeyPair.ts +36 -0
  101. package/src/helpers/keyPair/randomSecp256k1KeyPair.ts +44 -0
  102. package/src/helpers/nearGas.ts +219 -0
  103. package/src/helpers/tokens/nearToken.ts +237 -0
  104. package/src/helpers/tokens/tokenConverter/convertTokensToUnits.ts +31 -0
  105. package/src/{_common/utils → helpers/tokens}/tokenConverter/convertUnitsToTokens.ts +4 -17
  106. package/src/{_common/utils → helpers/tokens}/tokenConverter/helpers.ts +0 -7
  107. package/src/index.ts +94 -14
  108. package/src/keyServices/memoryKeyService/createFindKeyPair.ts +38 -0
  109. package/src/keyServices/memoryKeyService/createMemoryKeyService.ts +70 -21
  110. package/src/keyServices/memoryKeyService/createSignTransaction.ts +61 -24
  111. package/src/keyServices/memoryKeyService/getKeyPairs.ts +19 -0
  112. package/src/signers/memorySigner/createExecuteTransaction.ts +81 -0
  113. package/src/signers/memorySigner/createMemorySigner.ts +122 -31
  114. package/src/signers/memorySigner/createSignTransaction.ts +52 -0
  115. package/src/signers/memorySigner/executors/executeTransaction.ts +67 -58
  116. package/src/signers/memorySigner/executors/signTransaction.ts +38 -20
  117. package/src/signers/memorySigner/keyPool/createFindKeyForTask.ts +22 -14
  118. package/src/signers/memorySigner/keyPool/createIsKeyForTaskExist.ts +18 -7
  119. package/src/signers/memorySigner/keyPool/createKeyPool.ts +45 -16
  120. package/src/signers/memorySigner/keyPool/getFullAccessKeyList.ts +19 -22
  121. package/src/signers/memorySigner/keyPool/getFunctionCallKeyList.ts +20 -22
  122. package/src/signers/memorySigner/keyPool/helpers/keyUtils.ts +5 -7
  123. package/src/signers/memorySigner/matcher/createMatcher.ts +27 -12
  124. package/src/signers/memorySigner/resolver/createResolver.ts +20 -9
  125. package/src/signers/memorySigner/state/createState.ts +30 -11
  126. package/src/signers/memorySigner/taskQueue/addTask/_future/createExecuteMultipleTransactions.ts +38 -0
  127. package/src/signers/memorySigner/taskQueue/addTask/_future/createSignMultipleTransactions.ts +38 -0
  128. package/src/signers/memorySigner/taskQueue/addTask/createAddExecuteTransactionTask.ts +23 -0
  129. package/src/signers/memorySigner/taskQueue/addTask/createAddSignTransactionTask.ts +23 -0
  130. package/src/signers/memorySigner/taskQueue/addTask/helpers/{getSigningKeyPriority.ts → getAccessTypePriority.ts} +10 -12
  131. package/src/signers/memorySigner/taskQueue/createFindTaskForKey.ts +27 -11
  132. package/src/signers/memorySigner/taskQueue/createTaskQueue.ts +34 -19
  133. package/types/{accountKey.ts → _common/accountAccessKey.ts} +4 -4
  134. package/types/{common.ts → _common/common.ts} +15 -34
  135. package/types/{crypto.ts → _common/crypto.ts} +11 -11
  136. package/types/_common/curveString.ts +9 -0
  137. package/types/_common/keyPair/keyPair.ts +54 -0
  138. package/types/_common/keyPair/randomEd25519KeyPair.ts +54 -0
  139. package/types/_common/keyPair/randomSecp256k1KeyPair.ts +54 -0
  140. package/types/_common/nearGas.ts +93 -0
  141. package/types/_common/nearToken.ts +103 -0
  142. package/types/_common/sharedTransactionErrors.ts +35 -0
  143. package/types/actions/addKey.ts +73 -9
  144. package/types/actions/deleteAccount.ts +33 -3
  145. package/types/actions/deleteKey.ts +34 -3
  146. package/types/actions/deployContract.ts +33 -3
  147. package/types/actions/functionCall.ts +86 -12
  148. package/types/actions/transfer.ts +35 -5
  149. package/types/client/client.ts +78 -33
  150. package/types/client/createClient.ts +34 -0
  151. package/types/client/methods/_common/common.ts +26 -0
  152. package/types/client/methods/_common/query.ts +25 -0
  153. package/types/client/methods/account/getAccountAccessKey.ts +75 -0
  154. package/types/client/methods/account/getAccountAccessKeys.ts +63 -0
  155. package/types/client/methods/account/getAccountInfo.ts +81 -0
  156. package/types/client/methods/block/getBlock.ts +33 -5
  157. package/types/client/methods/contract/callContractReadFunction.ts +98 -17
  158. package/types/client/methods/contract/getContractState.ts +2 -2
  159. package/types/client/methods/protocol/getGasPrice.ts +3 -2
  160. package/types/client/methods/protocol/getProtocolConfig.ts +2 -2
  161. package/types/client/methods/transaction/sendSignedTransaction.ts +75 -9
  162. package/types/client/transport/sendRequest.ts +130 -0
  163. package/types/client/{transport.ts → transport/transport.ts} +19 -26
  164. package/types/keyServices/memoryKeyService/createFindKeyPair.ts +17 -0
  165. package/types/keyServices/memoryKeyService/createMemoryKeyService.ts +22 -0
  166. package/types/keyServices/memoryKeyService/createSignTransaction.ts +20 -0
  167. package/types/keyServices/memoryKeyService/memoryKeyService.ts +68 -0
  168. package/types/natError.ts +106 -0
  169. package/types/signers/memorySigner/createExecuteTransaction.ts +72 -0
  170. package/types/signers/memorySigner/createMemorySigner.ts +76 -0
  171. package/types/signers/memorySigner/createSignTransaction.ts +59 -0
  172. package/types/signers/memorySigner/keyPool.ts +55 -0
  173. package/types/signers/memorySigner/matcher.ts +27 -0
  174. package/types/signers/memorySigner/memorySigner.ts +75 -0
  175. package/types/signers/memorySigner/resolver.ts +20 -0
  176. package/types/signers/memorySigner/state.ts +21 -0
  177. package/types/signers/memorySigner/taskQueue.ts +135 -0
  178. package/types/transaction.ts +30 -38
  179. package/src/_common/schemas/borsh/signedTransaction.ts +0 -10
  180. package/src/_common/schemas/valibot/common.ts +0 -12
  181. package/src/_common/schemas/valibot/cryptoHash.ts +0 -12
  182. package/src/_common/schemas/valibot/curveString.ts +0 -23
  183. package/src/_common/schemas/valibot/privateKey.ts +0 -38
  184. package/src/_common/schemas/valibot/publicKey.ts +0 -33
  185. package/src/_common/schemas/valibot/transaction.ts +0 -42
  186. package/src/_common/schemas/zod/common.ts +0 -29
  187. package/src/_common/transformers/contract.ts +0 -11
  188. package/src/_common/transformers/toBorshBytes/signedTransaction.ts +0 -20
  189. package/src/_common/transformers/toNative/signedTransaction.ts +0 -13
  190. package/src/_common/utils/tokenConverter/convertTokensToUnits.ts +0 -65
  191. package/src/client/methods/account/getAccountKey.ts +0 -69
  192. package/src/client/methods/account/getAccountKeys.ts +0 -46
  193. package/src/client/methods/account/getAccountState.ts +0 -80
  194. package/src/client/methods/block/getBlock.ts +0 -23
  195. package/src/client/methods/contract/callContractReadFunction.ts +0 -78
  196. package/src/client/methods/transaction/sendSignedTransaction.ts +0 -32
  197. package/src/client/rpcError.ts +0 -118
  198. package/src/client/transport/transportError.ts +0 -51
  199. package/src/helpers/crypto/getPublicKey.ts +0 -59
  200. package/src/helpers/crypto/getRandomPrivateKey.ts +0 -19
  201. package/src/helpers/crypto/sign.ts +0 -69
  202. package/src/helpers/gas.ts +0 -25
  203. package/src/helpers/near.ts +0 -118
  204. package/src/keyServices/memoryKeyService/createFindPrivateKey.ts +0 -11
  205. package/src/keyServices/memoryKeyService/parseKeySources.ts +0 -49
  206. package/src/signers/memorySigner/executors/helpers/getSignedTransaction.ts +0 -33
  207. package/src/signers/memorySigner/taskQueue/addTask/executeMultipleTransactions.ts +0 -29
  208. package/src/signers/memorySigner/taskQueue/addTask/executeTransaction.ts +0 -28
  209. package/src/signers/memorySigner/taskQueue/addTask/signMultipleTransactions.ts +0 -26
  210. package/src/signers/memorySigner/taskQueue/addTask/signTransaction.ts +0 -23
  211. package/types/client/methods/account/getAccountKey.ts +0 -37
  212. package/types/client/methods/account/getAccountKeys.ts +0 -35
  213. package/types/client/methods/account/getAccountState.ts +0 -45
  214. package/types/contract.ts +0 -13
  215. package/types/delegateAction.ts +0 -0
  216. package/types/keyServices/memoryKeyService.ts +0 -26
  217. package/types/signedTransaction.ts +0 -14
  218. package/types/signers/memorySigner.ts +0 -60
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  ## NEAR API TS
2
- Typescript library for interactions with Near Protocol in the browser or Node.js
2
+ TypeScript library for interactions with Near Protocol in the browser or Node.js
3
3
 
4
4
  [GitHub Repository](https://github.com/eclipseeer/near-api-ts/tree/main)
5
5
 
@@ -15,19 +15,20 @@ import {
15
15
  createTestnetClient,
16
16
  createMemoryKeyService,
17
17
  createMemorySigner,
18
- testnet,
19
18
  transfer,
19
+ near,
20
+ isNatError,
20
21
  } from 'near-api-ts';
21
22
 
22
- // Create a near testnet client
23
+ // Read some data from the chain
23
24
  const client = await createTestnetClient();
24
25
 
25
-
26
- // Read some data from the chain
27
- await client.getAccountState({
26
+ const { accountInfo } = await client.getAccountInfo({
28
27
  accountId: 'testnet',
29
28
  atMomentOf: 'LatestFinalBlock',
30
29
  })
30
+ console.log(accountInfo.balance.total.near)
31
+ console.log(accountInfo.balance.total.yoctoNear)
31
32
 
32
33
  // Send some transaction
33
34
  const keyService = await createMemoryKeyService({
@@ -41,9 +42,31 @@ const signer = await createMemorySigner({
41
42
  });
42
43
 
43
44
  await signer.executeTransaction({
44
- action: transfer({ amount: { yoctoNear: '1' } }),
45
- receiverAccountId: 'some-receiver.testnet',
45
+ intent: {
46
+ action: transfer({ amount: { yoctoNear: '1' } }),
47
+ receiverAccountId: 'some-receiver.testnet',
48
+ }
49
+ });
50
+
51
+ // Handle transaction errors
52
+ try {
53
+ const txResult = await signer.executeTransaction({
54
+ intent: {
55
+ action: transfer({ amount: near('10000000000') }),
56
+ receiverAccountId: 'some-receiver.testnet',
57
+ },
58
+ });
59
+ } catch (e) {
60
+ if (isNatError(e, 'MemorySigner.ExecuteTransaction.Rpc.Transaction.Signer.Balance.TooLow')) {
61
+ console.log(e.context.transactionCost)
62
+ }
63
+ }
64
+
65
+ // Use library functions in 'safe' mode
66
+ const maybeBlock = await client.safeGetBlock({
67
+ blockReference: { blockHeight: 10000000000000 },
46
68
  });
69
+ console.log(maybeBlock); // { ok: false, error: NatError: <{ kind: 'Client.GetBlock.Rpc.Block.NotFound', context: null }> }
47
70
  ```
48
71
 
49
72
  You may found more examples in the [examples/nodejs/ts-esm](https://github.com/eclipseeer/near-api-ts/tree/main/examples/nodejs/ts-esm)
package/dist/index.d.cts CHANGED
@@ -775,7 +775,9 @@ type BaseDeserializeResult = ({ rawResult, }: {
775
775
  rawResult: RawCallResult;
776
776
  }) => unknown;
777
777
  type MaybeBaseDeserializeResult = BaseDeserializeResult | undefined;
778
- type BaseSerializeArgs<A> = (args: {
778
+ type BaseSerializeArgs<A> = [A] extends [undefined] ? (args?: {
779
+ functionArgs: A;
780
+ }) => Uint8Array : (args: {
779
781
  functionArgs: A;
780
782
  }) => Uint8Array;
781
783
  type BaseFnCallArgs = {
package/dist/index.d.ts CHANGED
@@ -775,7 +775,9 @@ type BaseDeserializeResult = ({ rawResult, }: {
775
775
  rawResult: RawCallResult;
776
776
  }) => unknown;
777
777
  type MaybeBaseDeserializeResult = BaseDeserializeResult | undefined;
778
- type BaseSerializeArgs<A> = (args: {
778
+ type BaseSerializeArgs<A> = [A] extends [undefined] ? (args?: {
779
+ functionArgs: A;
780
+ }) => Uint8Array : (args: {
779
781
  functionArgs: A;
780
782
  }) => Uint8Array;
781
783
  type BaseFnCallArgs = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "near-api-ts",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Typescript library for interactions with Near Protocol in the browser or Node.js",
5
5
  "type": "module",
6
6
  "exports": {
@@ -34,13 +34,12 @@
34
34
  "test:all": "vitest run"
35
35
  },
36
36
  "dependencies": {
37
- "@near-js/jsonrpc-types": "^1.4.0",
37
+ "@near-js/jsonrpc-types": "^1.5.0",
38
38
  "@noble/curves": "^1.9.4",
39
39
  "@noble/hashes": "^1.8.0",
40
40
  "@scure/base": "^1.2.6",
41
41
  "borsh": "^2.0.0",
42
42
  "lodash-es": "^4.17.21",
43
- "valibot": "^1.1.0",
44
- "zod": "^4.0.11"
43
+ "zod": "^4.1.13"
45
44
  }
46
45
  }
@@ -1,23 +1,16 @@
1
- export const BinaryCryptoKeyLengths = {
1
+ export const BinaryLengths = {
2
2
  Ed25519: {
3
- // SecretKey + PublicKey
4
- PrivateKey: 64,
3
+ PrivateKey: 64, // SecretKey + PublicKey
5
4
  SecretKey: 32,
6
5
  PublicKey: 32,
6
+ Signature: 64,
7
7
  },
8
8
  Secp256k1: {
9
- // SecretKey + PublicKey
10
- PrivateKey: 96,
9
+ PrivateKey: 96, // SecretKey + PublicKey
11
10
  SecretKey: 32,
12
11
  PublicKey: 64,
12
+ Signature: 65,
13
13
  },
14
14
  } as const;
15
15
 
16
- export const BinaryCryptoHashLength = 32;
17
16
  export const NearDecimals = 24;
18
-
19
- // Fetch block every 1000 blocks * 600ms best block time = >10 minutes
20
- export const RefetchBlockHashInterval = 600_000;
21
-
22
- // 1 minute
23
- export const SignerTaskTtlMs = 60_000 as const
@@ -0,0 +1,50 @@
1
+ import type {
2
+ NatErrorKind,
3
+ CreateNatErrorArgs,
4
+ ContextFor,
5
+ } from 'nat-types/natError';
6
+
7
+ export const NatErrorBrand = Symbol('NatError');
8
+
9
+ export class NatError<K extends NatErrorKind> extends Error {
10
+ public readonly [NatErrorBrand] = true;
11
+ public readonly kind: K;
12
+ public readonly context: ContextFor<K>;
13
+
14
+ constructor(args: CreateNatErrorArgs<K>) {
15
+ super(`<${args.kind}>`);
16
+ this.name = 'NatError';
17
+ this.kind = args.kind;
18
+ this.context = args.context;
19
+ }
20
+ }
21
+
22
+ export const createNatError = <K extends NatErrorKind>(
23
+ args: CreateNatErrorArgs<K>,
24
+ ): NatError<K> => new NatError(args);
25
+
26
+ export const isNatError = <K extends NatErrorKind>(
27
+ error: unknown,
28
+ kind?: K,
29
+ ): error is NatError<K> => {
30
+ const isNatErr =
31
+ typeof error === 'object' && error !== null && NatErrorBrand in error;
32
+
33
+ if (kind === undefined) return isNatErr;
34
+ return isNatErr && (error as NatError<K>)?.kind === kind;
35
+ };
36
+
37
+ type NatErrorUnion<K extends readonly NatErrorKind[]> = {
38
+ [I in keyof K]: NatError<K[I]>;
39
+ }[number];
40
+
41
+ export const isNatErrorOf = <const K extends readonly NatErrorKind[]>(
42
+ error: unknown,
43
+ kinds: K,
44
+ ): error is NatErrorUnion<K> => {
45
+ const isNatErr =
46
+ typeof error === 'object' && error !== null && NatErrorBrand in error;
47
+
48
+ if (!isNatErr) return false;
49
+ return kinds.includes((error as NatError<any>).kind);
50
+ };
@@ -1,3 +1,2 @@
1
1
  export * from './transaction';
2
- export * from './signedTransaction';
3
2
  export * from './delegateAction';
@@ -11,6 +11,7 @@ import { stakeActionBorshSchema } from './actions/stake';
11
11
  import { deleteKeyActionBorshSchema } from './actions/deleteKey';
12
12
  import { deleteAccountActionBorshSchema } from './actions/deleteAccount';
13
13
  import { signedDelegateActionBorshSchema } from './actions/signedDelegate';
14
+ import { signatureBorshSchema } from '@common/schemas/borsh/signature';
14
15
 
15
16
  // Actions order in this enum is important and must match nearcore
16
17
  const actionBorshSchema: Schema = {
@@ -40,3 +41,10 @@ export const transactionBorshSchema: Schema = {
40
41
  actions: { array: { type: actionBorshSchema } },
41
42
  },
42
43
  };
44
+
45
+ export const signedTransactionBorshSchema: Schema = {
46
+ struct: {
47
+ transaction: transactionBorshSchema,
48
+ signature: signatureBorshSchema,
49
+ },
50
+ };
@@ -0,0 +1,34 @@
1
+ import * as z from 'zod/mini';
2
+ import { PartialTransportPolicySchema } from '../../../client/transport/transportPolicy';
3
+ import {
4
+ BlockHashSchema,
5
+ BlockHeightSchema,
6
+ } from '@common/schemas/zod/common/common';
7
+
8
+ export const PoliciesSchema = z.optional(
9
+ z.object({
10
+ transport: PartialTransportPolicySchema,
11
+ }),
12
+ );
13
+
14
+ export const BaseOptionsSchema = z.optional(
15
+ z.object({
16
+ signal: z.optional(z.instanceof(AbortSignal)),
17
+ }),
18
+ );
19
+
20
+ export const BlockReferenceSchema = z.union([
21
+ z.literal('LatestOptimisticBlock'),
22
+ z.literal('LatestNearFinalBlock'),
23
+ z.literal('LatestFinalBlock'),
24
+ z.literal('EarliestAvailableBlock'),
25
+ z.literal('GenesisBlock'),
26
+ z.object({
27
+ blockHash: BlockHashSchema,
28
+ blockHeight: z.optional(z.never()),
29
+ }),
30
+ z.object({
31
+ blockHash: z.optional(z.never()),
32
+ blockHeight: BlockHeightSchema,
33
+ }),
34
+ ]);
@@ -0,0 +1,11 @@
1
+ import * as z from 'zod/mini';
2
+ import { oneLine } from '@common/utils/common';
3
+
4
+ export const AccountIdSchema = z.string().check(
5
+ z.minLength(2),
6
+ z.maxLength(64),
7
+ z.regex(/^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/, {
8
+ error: oneLine(`Account ID may contain only lowercase letters (a–z),
9
+ digits (0–9), and separators (., -, _).`),
10
+ }),
11
+ );
@@ -0,0 +1,16 @@
1
+ import * as z from 'zod/mini';
2
+ import { CryptoHashSchema } from '@common/schemas/zod/common/cryptoHash';
3
+
4
+ export const BlockHashSchema = CryptoHashSchema;
5
+ export const BlockHeightSchema = z.number().check(z.nonnegative());
6
+ export const BlockIdSchema = z.union([BlockHeightSchema, BlockHashSchema]);
7
+
8
+ export const NonceSchema = z.number().check(z.int(), z.nonnegative());
9
+
10
+ export const ContractFunctionNameSchema = z
11
+ .string()
12
+ .check(z.minLength(1), z.maxLength(256));
13
+
14
+ // TODO Zod doesn't allow to pass objects with undefined fields
15
+ // like { a: 1, b: undefined }. But our types allow it. Need to fix zod schema.
16
+ export const JsonSchema = z.json();
@@ -0,0 +1,25 @@
1
+ import * as z from 'zod/mini';
2
+ import { base58 } from '@scure/base';
3
+ import { oneLine } from '@common/utils/common';
4
+
5
+ const Base58StringSchema = z.string().check(
6
+ z.regex(
7
+ /^[1-9A-HJ-NP-Za-km-z]+$/,
8
+ oneLine(`Base58 string contains invalid characters. Allowed characters:
9
+ 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`),
10
+ ),
11
+ );
12
+
13
+ export const CryptoHashSchema = z
14
+ .pipe(
15
+ Base58StringSchema,
16
+ z.transform((cryptoHash) => {
17
+ const u8CryptoHash = base58.decode(cryptoHash);
18
+ return { cryptoHash, u8CryptoHash };
19
+ }),
20
+ )
21
+ .check(
22
+ z.refine(({ u8CryptoHash }) => u8CryptoHash.length === 32, {
23
+ error: 'Crypto hash length should be 32 bytes',
24
+ }),
25
+ );
@@ -0,0 +1,22 @@
1
+ import * as z from 'zod/mini';
2
+ import { oneLine } from '@common/utils/common';
3
+ import type { Curve, CurveString } from 'nat-types/_common/curveString';
4
+ import { base58 } from '@scure/base';
5
+
6
+ export const CurveStringSchema = z.pipe(
7
+ z.string().check(
8
+ z.regex(
9
+ /^(ed25519|secp256k1):[1-9A-HJ-NP-Za-km-z]+$/,
10
+ oneLine(`Curve strings should use the
11
+ ed25519:<base58String> or secp256k1:<base58String> format.`),
12
+ ),
13
+ ),
14
+ z.transform((curveString: CurveString) => {
15
+ const [curve, base58String] = curveString.split(':');
16
+ return {
17
+ curveString,
18
+ curve: curve as Curve,
19
+ u8Data: base58.decode(base58String),
20
+ };
21
+ }),
22
+ );
@@ -0,0 +1,33 @@
1
+ import * as z from 'zod/mini';
2
+
3
+ export const GasInputSchema = z.union([
4
+ z.bigint(),
5
+ z.pipe(
6
+ z.number().check(z.int()),
7
+ z.transform((v) => BigInt(v)),
8
+ ),
9
+ ]);
10
+
11
+ const createTeraGasInputSchema = (decimals: number) =>
12
+ z.string().check(
13
+ z.refine(
14
+ (val) => {
15
+ const decimalPattern = new RegExp(`^\\d+(?:\\.\\d{1,${decimals}})?$`);
16
+ return decimalPattern.test(val);
17
+ },
18
+ {
19
+ message: `Must be a valid number with up to ${decimals} decimal places`,
20
+ },
21
+ ),
22
+ );
23
+
24
+ export const TeraGasInputSchema = createTeraGasInputSchema(12);
25
+
26
+ export const NearGasArgsSchema = z.union([
27
+ z.object({
28
+ gas: GasInputSchema,
29
+ }),
30
+ z.object({
31
+ teraGas: TeraGasInputSchema,
32
+ }),
33
+ ]);
@@ -0,0 +1,54 @@
1
+ import * as z from 'zod/mini';
2
+
3
+ /**
4
+ * Validate a positive decimal string with an optional fractional part
5
+ * whose length is limited by `decimals`:
6
+ *
7
+ * Pattern: ^\d+(?:\.\d{1,decimals})?$
8
+ * - ^ : anchor at start — match the whole string only
9
+ * - \d+ : integer part — one or more digits (requires a digit before the dot)
10
+ * - (?: ... ) : non-capturing group for the optional fractional part
11
+ * - \. : literal dot
12
+ * - \d{1,decimals} : 1 to decimals digits after the dot
13
+ * - ? : make the fractional group optional (allow integers)
14
+ * - $ : anchor at end — no extra chars allowed
15
+ *
16
+ * Notes:
17
+ * - Disallows ".5" (no integer part) and "5." (no fractional digits).
18
+ * - Disallows signs, spaces, commas, exponent notation, etc.
19
+ * - Allows leading zeros in the integer part (e.g., "0001", "0.05").
20
+ *
21
+ * Examples (decimals = 2):
22
+ * ✓ "0", "12", "3.4", "10.00"
23
+ * ✗ ".5", "5.", "1.234", "-1", "1e3", " 1"
24
+ */
25
+ const createTokensInputSchema = (decimals: number) =>
26
+ z.string().check(
27
+ z.refine(
28
+ (val) => {
29
+ const decimalPattern = new RegExp(`^\\d+(?:\\.\\d{1,${decimals}})?$`);
30
+ return decimalPattern.test(val);
31
+ },
32
+ {
33
+ message: `Must be a valid number with up to ${decimals} decimal places`,
34
+ },
35
+ ),
36
+ );
37
+
38
+ export const NearInputSchema = createTokensInputSchema(24);
39
+
40
+ const BigintStringSchema = z.pipe(
41
+ z.string().check(z.regex(/^\d+$/, 'Must contain only digits')),
42
+ z.transform((v) => BigInt(v)),
43
+ );
44
+
45
+ export const YoctoNearInputSchema = z.union([z.bigint(), BigintStringSchema]);
46
+
47
+ export const NearTokenArgsSchema = z.union([
48
+ z.object({
49
+ near: NearInputSchema,
50
+ }),
51
+ z.object({
52
+ yoctoNear: YoctoNearInputSchema,
53
+ }),
54
+ ]);
@@ -0,0 +1,26 @@
1
+ import * as z from 'zod/mini';
2
+ import { BinaryLengths } from '@common/configs/constants';
3
+ import { CurveStringSchema } from '@common/schemas/zod/common/curveString';
4
+
5
+ const { Ed25519, Secp256k1 } = BinaryLengths;
6
+
7
+ export const PrivateKeySchema = z
8
+ .pipe(
9
+ CurveStringSchema,
10
+ z.transform((val) => ({
11
+ privateKey: val.curveString,
12
+ u8PrivateKey: val.u8Data,
13
+ curve: val.curve,
14
+ })),
15
+ )
16
+ .check(
17
+ z.refine(
18
+ ({ curve, u8PrivateKey }) =>
19
+ curve === 'ed25519'
20
+ ? u8PrivateKey.length === Ed25519.PrivateKey
21
+ : u8PrivateKey.length === Secp256k1.PrivateKey,
22
+ { error: 'Invalid private key length' },
23
+ ),
24
+ );
25
+
26
+ export type InnerPrivateKey = z.infer<typeof PrivateKeySchema>;
@@ -0,0 +1,26 @@
1
+ import * as z from 'zod/mini';
2
+ import { BinaryLengths } from '@common/configs/constants';
3
+ import { CurveStringSchema } from '@common/schemas/zod/common/curveString';
4
+
5
+ const { Ed25519, Secp256k1 } = BinaryLengths;
6
+
7
+ export const PublicKeySchema = z
8
+ .pipe(
9
+ CurveStringSchema,
10
+ z.transform((val) => ({
11
+ publicKey: val.curveString,
12
+ u8PublicKey: val.u8Data,
13
+ curve: val.curve,
14
+ })),
15
+ )
16
+ .check(
17
+ z.refine(
18
+ ({ curve, u8PublicKey }) =>
19
+ curve === 'ed25519'
20
+ ? u8PublicKey.length === Ed25519.PublicKey
21
+ : u8PublicKey.length === Secp256k1.PublicKey,
22
+ { error: 'Invalid public key length' },
23
+ ),
24
+ );
25
+
26
+ export type InnerPublicKey = z.infer<typeof PublicKeySchema>;
@@ -0,0 +1,26 @@
1
+ import * as z from 'zod/mini';
2
+ import { BinaryLengths } from '@common/configs/constants';
3
+ import { CurveStringSchema } from '@common/schemas/zod/common/curveString';
4
+
5
+ const { Ed25519, Secp256k1 } = BinaryLengths;
6
+
7
+ export const SignatureSchema = z
8
+ .pipe(
9
+ CurveStringSchema,
10
+ z.transform((val) => ({
11
+ signature: val.curveString,
12
+ u8Signature: val.u8Data,
13
+ curve: val.curve,
14
+ })),
15
+ )
16
+ .check(
17
+ z.refine(
18
+ ({ curve, u8Signature }) =>
19
+ curve === 'ed25519'
20
+ ? u8Signature.length === Ed25519.Signature
21
+ : u8Signature.length === Secp256k1.Signature,
22
+ { error: 'Invalid signature length' },
23
+ ),
24
+ );
25
+
26
+ export type InnerSignature = z.infer<typeof SignatureSchema>;
@@ -1,9 +1,62 @@
1
1
  import * as z from 'zod/mini';
2
- import { RpcErrorSchema } from '@near-js/jsonrpc-types';
3
2
 
4
- export const RpcResponseSchema = z.object({
3
+ const BaseRpcResponseSchema = z.object({
5
4
  jsonrpc: z.literal('2.0'),
6
- id: z.unknown(),
7
- result: z.optional(z.unknown()),
8
- error: z.optional(RpcErrorSchema()),
5
+ id: z.number(),
9
6
  });
7
+
8
+ const BaseRpcErrorSchema = z.object({
9
+ code: z.number(),
10
+ message: z.string(),
11
+ data: z.optional(z.unknown()),
12
+ });
13
+
14
+ const RpcErrorSchema = z.discriminatedUnion('name', [
15
+ z.object({
16
+ ...BaseRpcErrorSchema.shape,
17
+ name: z.literal('REQUEST_VALIDATION_ERROR'),
18
+ cause: z.discriminatedUnion('name', [
19
+ z.object({
20
+ name: z.literal('METHOD_NOT_FOUND'),
21
+ info: z.object({ methodName: z.string() }),
22
+ }),
23
+ z.object({
24
+ name: z.literal('PARSE_ERROR'),
25
+ info: z.object({ errorMessage: z.string() }),
26
+ }),
27
+ ]),
28
+ }),
29
+ z.object({
30
+ ...BaseRpcErrorSchema.shape,
31
+ name: z.literal('HANDLER_ERROR'),
32
+ cause: z.object({
33
+ info: z.unknown(),
34
+ name: z.string(),
35
+ }),
36
+ }),
37
+ z.object({
38
+ ...BaseRpcErrorSchema.shape,
39
+ name: z.literal('INTERNAL_ERROR'),
40
+ cause: z.object({
41
+ name: z.literal('INTERNAL_ERROR'),
42
+ info: z.object({ errorMessage: z.string() }),
43
+ }),
44
+ }),
45
+ ]);
46
+
47
+ export type RpcError = z.infer<typeof RpcErrorSchema>;
48
+
49
+ export const RpcResponseSchema = z.union([
50
+ z.object({
51
+ ...BaseRpcResponseSchema.shape,
52
+ result: z.unknown(),
53
+ error: z.optional(z.never()),
54
+ }),
55
+ z.object({
56
+ ...BaseRpcResponseSchema.shape,
57
+ result: z.optional(z.never()),
58
+ error: RpcErrorSchema,
59
+ }),
60
+ ]);
61
+
62
+ export type RpcResponse = z.infer<typeof RpcResponseSchema>;
@@ -0,0 +1,29 @@
1
+ import * as z from 'zod/mini';
2
+ import { PublicKeySchema } from '@common/schemas/zod/common/publicKey';
3
+ import { AccountIdSchema } from '@common/schemas/zod/common/accountId';
4
+ import { ContractFunctionNameSchema } from '@common/schemas/zod/common/common';
5
+ import { NearTokenArgsSchema } from '@common/schemas/zod/common/nearToken';
6
+
7
+ const AddFullAccessKeyActionSchema = z.object({
8
+ actionType: z.literal('AddKey'),
9
+ accessType: z.literal('FullAccess'),
10
+ publicKey: PublicKeySchema,
11
+ });
12
+
13
+ const AddFunctionCallKeyActionSchema = z.object({
14
+ actionType: z.literal('AddKey'),
15
+ accessType: z.literal('FunctionCall'),
16
+ publicKey: PublicKeySchema,
17
+ contractAccountId: AccountIdSchema,
18
+ gasBudget: z.optional(NearTokenArgsSchema),
19
+ allowedFunctions: z.optional(
20
+ z.array(ContractFunctionNameSchema).check(z.minLength(1)),
21
+ ),
22
+ });
23
+
24
+ export const AddKeyActionSchema = z.union([
25
+ AddFullAccessKeyActionSchema,
26
+ AddFunctionCallKeyActionSchema,
27
+ ]);
28
+
29
+ export type InnerAddKeyAction = z.infer<typeof AddKeyActionSchema>;
@@ -0,0 +1,5 @@
1
+ import * as z from 'zod/mini';
2
+
3
+ export const CreateAccountActionSchema = z.object({
4
+ actionType: z.literal('CreateAccount'),
5
+ });
@@ -0,0 +1,11 @@
1
+ import * as z from 'zod/mini';
2
+ import { AccountIdSchema } from '@common/schemas/zod/common/accountId';
3
+
4
+ export const DeleteAccountActionSchema = z.object({
5
+ actionType: z.literal('DeleteAccount'),
6
+ beneficiaryAccountId: AccountIdSchema,
7
+ });
8
+
9
+ export type InnerDeleteAccountAction = z.infer<
10
+ typeof DeleteAccountActionSchema
11
+ >;
@@ -0,0 +1,9 @@
1
+ import * as z from 'zod/mini';
2
+ import { PublicKeySchema } from '@common/schemas/zod/common/publicKey';
3
+
4
+ export const DeleteKeyActionSchema = z.object({
5
+ actionType: z.literal('DeleteKey'),
6
+ publicKey: PublicKeySchema,
7
+ });
8
+
9
+ export type InnerDeleteKeyAction = z.infer<typeof DeleteKeyActionSchema>;
@@ -0,0 +1,10 @@
1
+ import * as z from 'zod/mini';
2
+
3
+ export const DeployContractActionSchema = z.object({
4
+ actionType: z.literal('DeployContract'),
5
+ wasmBytes: z.instanceof(Uint8Array),
6
+ });
7
+
8
+ export type InnerDeployContractAction = z.infer<
9
+ typeof DeployContractActionSchema
10
+ >;
@@ -0,0 +1,14 @@
1
+ import * as z from 'zod/mini';
2
+ import { NearTokenArgsSchema } from '@common/schemas/zod/common/nearToken';
3
+ import { NearGasArgsSchema } from '@common/schemas/zod/common/nearGas';
4
+ import { ContractFunctionNameSchema } from '@common/schemas/zod/common/common';
5
+
6
+ export const FunctionCallActionSchema = z.object({
7
+ actionType: z.literal('FunctionCall'),
8
+ functionName: ContractFunctionNameSchema,
9
+ functionArgs: z.instanceof(Uint8Array),
10
+ gasLimit: NearGasArgsSchema,
11
+ attachedDeposit: z.optional(NearTokenArgsSchema),
12
+ });
13
+
14
+ export type InnerFunctionCallAction = z.infer<typeof FunctionCallActionSchema>;
@@ -0,0 +1,9 @@
1
+ import * as z from 'zod/mini';
2
+ import { NearTokenArgsSchema } from '@common/schemas/zod/common/nearToken';
3
+
4
+ export const TransferActionSchema = z.object({
5
+ actionType: z.literal('Transfer'),
6
+ amount: NearTokenArgsSchema,
7
+ });
8
+
9
+ export type InnerTransferAction = z.infer<typeof TransferActionSchema>;