near-api-ts 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.
Files changed (77) hide show
  1. package/README.md +0 -1
  2. package/dist/index.d.cts +3 -1
  3. package/dist/index.d.ts +3 -1
  4. package/package.json +2 -3
  5. package/src/_common/transformers/toNative/actions/addKey.ts +7 -7
  6. package/src/_common/transformers/toNative/actions/deleteAccount.ts +1 -1
  7. package/src/_common/transformers/toNative/actions/deleteKey.ts +1 -1
  8. package/src/_common/transformers/toNative/actions/deployContract.ts +3 -3
  9. package/src/_common/transformers/toNative/actions/functionCall.ts +8 -10
  10. package/src/_common/transformers/toNative/actions/transfer.ts +2 -2
  11. package/src/client/methods/account/getAccountState.ts +1 -1
  12. package/src/client/methods/account/helpers/transformKey.ts +1 -1
  13. package/src/client/methods/protocol/getGasPrice.ts +1 -1
  14. package/src/client/rpcError.ts +2 -2
  15. package/src/helpers/actionCreators/addFullAccessKey.ts +7 -9
  16. package/src/helpers/actionCreators/addFunctionCallKey.ts +7 -15
  17. package/src/helpers/actionCreators/deleteAccount.ts +3 -3
  18. package/src/helpers/actionCreators/deleteKey.ts +5 -3
  19. package/src/helpers/actionCreators/deployContract.ts +3 -5
  20. package/src/helpers/actionCreators/functionCall.ts +20 -8
  21. package/src/helpers/actionCreators/transfer.ts +3 -3
  22. package/src/helpers/crypto/getPublicKey.ts +5 -37
  23. package/src/helpers/crypto/sign.ts +11 -23
  24. package/src/helpers/nearGas.ts +123 -0
  25. package/src/helpers/{near.ts → nearToken.ts} +42 -36
  26. package/src/index.ts +6 -2
  27. package/src/keyServices/memoryKeyService/parseKeySources.ts +1 -4
  28. package/src/signers/memorySigner/createMemorySigner.ts +8 -4
  29. package/src/signers/memorySigner/executors/executeTransaction.ts +23 -4
  30. package/src/signers/memorySigner/executors/helpers/getSignedTransaction.ts +8 -4
  31. package/src/signers/memorySigner/executors/signTransaction.ts +6 -3
  32. package/src/signers/memorySigner/keyPool/createFindKeyForTask.ts +22 -14
  33. package/src/signers/memorySigner/keyPool/createIsKeyForTaskExist.ts +18 -7
  34. package/src/signers/memorySigner/keyPool/createKeyPool.ts +5 -2
  35. package/src/signers/memorySigner/keyPool/getFullAccessKeyList.ts +11 -10
  36. package/src/signers/memorySigner/keyPool/getFunctionCallKeyList.ts +10 -10
  37. package/src/signers/memorySigner/keyPool/helpers/keyUtils.ts +4 -3
  38. package/src/signers/memorySigner/matcher/createMatcher.ts +16 -10
  39. package/src/signers/memorySigner/resolver/createResolver.ts +18 -7
  40. package/src/signers/memorySigner/state/createState.ts +9 -2
  41. package/src/signers/memorySigner/taskQueue/addTask/{executeMultipleTransactions.ts → createExecuteMultipleTransactions.ts} +13 -4
  42. package/src/signers/memorySigner/taskQueue/addTask/createExecuteTransaction.ts +39 -0
  43. package/src/signers/memorySigner/taskQueue/addTask/{signMultipleTransactions.ts → createSignMultipleTransactions.ts} +13 -4
  44. package/src/signers/memorySigner/taskQueue/addTask/{signTransaction.ts → createSignTransaction.ts} +9 -4
  45. package/src/signers/memorySigner/taskQueue/addTask/helpers/getSigningKeyPriority.ts +9 -11
  46. package/src/signers/memorySigner/taskQueue/createFindTaskForKey.ts +27 -11
  47. package/src/signers/memorySigner/taskQueue/createTaskQueue.ts +20 -13
  48. package/types/accountKey.ts +2 -1
  49. package/types/actions/addKey.ts +15 -9
  50. package/types/actions/deleteAccount.ts +2 -3
  51. package/types/actions/deleteKey.ts +2 -3
  52. package/types/actions/deployContract.ts +2 -3
  53. package/types/actions/functionCall.ts +39 -11
  54. package/types/actions/transfer.ts +4 -5
  55. package/types/client/methods/account/getAccountState.ts +1 -1
  56. package/types/client/methods/protocol/getGasPrice.ts +2 -1
  57. package/types/common.ts +10 -29
  58. package/types/nearGas.ts +19 -0
  59. package/types/nearToken.ts +21 -0
  60. package/types/signers/memorySigner/keyPool.ts +39 -0
  61. package/types/signers/memorySigner/matcher.ts +8 -0
  62. package/types/signers/memorySigner/memorySigner.ts +53 -0
  63. package/types/signers/memorySigner/resolver.ts +16 -0
  64. package/types/signers/memorySigner/state.ts +6 -0
  65. package/types/signers/memorySigner/taskQueue.ts +92 -0
  66. package/types/transaction.ts +2 -7
  67. package/src/_common/schemas/valibot/common.ts +0 -12
  68. package/src/_common/schemas/valibot/cryptoHash.ts +0 -12
  69. package/src/_common/schemas/valibot/curveString.ts +0 -23
  70. package/src/_common/schemas/valibot/privateKey.ts +0 -38
  71. package/src/_common/schemas/valibot/publicKey.ts +0 -33
  72. package/src/_common/schemas/valibot/transaction.ts +0 -42
  73. package/src/_common/transformers/contract.ts +0 -11
  74. package/src/helpers/gas.ts +0 -25
  75. package/src/signers/memorySigner/taskQueue/addTask/executeTransaction.ts +0 -28
  76. package/types/contract.ts +0 -13
  77. package/types/signers/memorySigner.ts +0 -60
package/README.md CHANGED
@@ -15,7 +15,6 @@ import {
15
15
  createTestnetClient,
16
16
  createMemoryKeyService,
17
17
  createMemorySigner,
18
- testnet,
19
18
  transfer,
20
19
  } from 'near-api-ts';
21
20
 
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.4.0",
4
4
  "description": "Typescript library for interactions with Near Protocol in the browser or Node.js",
5
5
  "type": "module",
6
6
  "exports": {
@@ -40,7 +40,6 @@
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.12"
45
44
  }
46
45
  }
@@ -3,19 +3,19 @@ import type {
3
3
  NativeAddKeyAction,
4
4
  } from 'nat-types/actions/addKey';
5
5
  import { toNativePublicKey } from '@common/transformers/toNative/publicKey';
6
- import { fromNearOption } from '../../../../helpers/near';
6
+ import { nearToken } from '../../../../helpers/nearToken';
7
7
 
8
8
  const getPermission = (
9
- params: AddKeyAction['params'],
9
+ action: AddKeyAction,
10
10
  ): NativeAddKeyAction['addKey']['accessKey']['permission'] => {
11
- if (params.accessType === 'FullAccess') return { fullAccess: {} };
11
+ if (action.accessType === 'FullAccess') return { fullAccess: {} };
12
12
 
13
- const { contractAccountId, gasBudget, allowedFunctions } = params;
13
+ const { contractAccountId, gasBudget, allowedFunctions } = action;
14
14
 
15
15
  return {
16
16
  functionCall: {
17
17
  receiverId: contractAccountId,
18
- allowance: gasBudget && fromNearOption(gasBudget).yoctoNear,
18
+ allowance: gasBudget && nearToken(gasBudget).yoctoNear,
19
19
  methodNames: allowedFunctions ?? [],
20
20
  },
21
21
  };
@@ -25,10 +25,10 @@ export const toNativeAddKeyAction = (
25
25
  action: AddKeyAction,
26
26
  ): NativeAddKeyAction => ({
27
27
  addKey: {
28
- publicKey: toNativePublicKey(action.params.publicKey),
28
+ publicKey: toNativePublicKey(action.publicKey),
29
29
  accessKey: {
30
30
  nonce: 0n, // Placeholder; It's not usable anymore: https://gov.near.org/t/issue-with-access-key-nonce/749
31
- permission: getPermission(action.params),
31
+ permission: getPermission(action),
32
32
  },
33
33
  },
34
34
  });
@@ -7,6 +7,6 @@ export const toNativeDeleteAccountAction = (
7
7
  action: DeleteAccountAction,
8
8
  ): NativeDeleteAccountAction => ({
9
9
  deleteAccount: {
10
- beneficiaryId: action.params.beneficiaryAccountId,
10
+ beneficiaryId: action.beneficiaryAccountId,
11
11
  },
12
12
  });
@@ -8,6 +8,6 @@ export const toNativeDeleteKeyAction = (
8
8
  action: DeleteKeyAction,
9
9
  ): NativeDeleteKeyAction => ({
10
10
  deleteKey: {
11
- publicKey: toNativePublicKey(action.params.publicKey),
11
+ publicKey: toNativePublicKey(action.publicKey),
12
12
  },
13
13
  });
@@ -7,9 +7,9 @@ import type {
7
7
  export const toNativeDeployContractAction = (
8
8
  action: DeployContractAction,
9
9
  ): NativeDeployContractAction => {
10
- const code = action.params.wasmBytes
11
- ? action.params.wasmBytes
12
- : base64.decode(action.params.wasmBase64);
10
+ const code = action.wasmBytes
11
+ ? action.wasmBytes
12
+ : base64.decode(action.wasmBase64);
13
13
 
14
14
  return {
15
15
  deployContract: { code },
@@ -2,21 +2,19 @@ import type {
2
2
  FunctionCallAction,
3
3
  NativeFunctionCallAction,
4
4
  } from 'nat-types/actions/functionCall';
5
- import { fromNearOption } from '../../../../helpers/near';
6
- import { fromGasOption } from '../../../../helpers/gas';
7
- import { toContractFnArgsBytes } from '@common/transformers/contract';
8
- import type { MaybeJsonLikeValue } from 'nat-types/common';
5
+ import { nearToken } from '../../../../helpers/nearToken';
6
+ import { nearGas } from '../../../../helpers/nearGas';
9
7
 
10
- export const toNativeFunctionCallAction = <AJ extends MaybeJsonLikeValue>(
11
- action: FunctionCallAction<AJ>,
8
+ export const toNativeFunctionCallAction = (
9
+ action: FunctionCallAction,
12
10
  ): NativeFunctionCallAction => {
13
- const { functionName, attachedDeposit, gasLimit } = action.params;
11
+ const { functionName, attachedDeposit, gasLimit, functionArgs } = action;
14
12
  return {
15
13
  functionCall: {
16
14
  methodName: functionName,
17
- args: toContractFnArgsBytes(action.params),
18
- gas: fromGasOption(gasLimit).gas,
19
- deposit: attachedDeposit ? fromNearOption(attachedDeposit).yoctoNear : 0n,
15
+ args: functionArgs,
16
+ gas: nearGas(gasLimit).gas,
17
+ deposit: attachedDeposit ? nearToken(attachedDeposit).yoctoNear : 0n,
20
18
  },
21
19
  };
22
20
  };
@@ -2,12 +2,12 @@ import type {
2
2
  TransferAction,
3
3
  NativeTransferAction,
4
4
  } from 'nat-types/actions/transfer';
5
- import { fromNearOption } from '../../../../helpers/near';
5
+ import { nearToken } from '../../../../helpers/nearToken';
6
6
 
7
7
  export const toNativeTransferAction = (
8
8
  action: TransferAction,
9
9
  ): NativeTransferAction => ({
10
10
  transfer: {
11
- deposit: fromNearOption(action.params.amount).yoctoNear,
11
+ deposit: nearToken(action.amount).yoctoNear,
12
12
  },
13
13
  });
@@ -1,7 +1,7 @@
1
1
  import * as z from 'zod/mini';
2
2
  import { toNativeBlockReference } from '@common/transformers/toNative/blockReference';
3
3
  import { AccountViewSchema, CryptoHashSchema } from '@near-js/jsonrpc-types';
4
- import { yoctoNear } from '../../../helpers/near';
4
+ import { yoctoNear } from '../../../helpers/nearToken';
5
5
  import { addTo } from '@common/utils/addTo';
6
6
  import type {
7
7
  CreateGetAccountState,
@@ -1,4 +1,4 @@
1
- import { yoctoNear } from '../../../../helpers/near';
1
+ import { yoctoNear } from '../../../../helpers/nearToken';
2
2
  import type { AccessKeyInfoView } from '@near-js/jsonrpc-types';
3
3
  import type { AccountKey, FunctionCallKey } from 'nat-types/accountKey';
4
4
  import type { PublicKey } from 'nat-types/crypto';
@@ -1,6 +1,6 @@
1
1
  import * as z from 'zod/mini';
2
2
  import { RpcGasPriceResponseSchema } from '@near-js/jsonrpc-types';
3
- import { yoctoNear } from '../../../helpers/near';
3
+ import { yoctoNear } from '../../../helpers/nearToken';
4
4
  import type {
5
5
  CreateGetGasPrice,
6
6
  GetGasPriceResult,
@@ -3,7 +3,7 @@ import { oneLine } from '@common/utils/common';
3
3
  import type { RpcRequestLog } from 'nat-types/client/transport';
4
4
  import type { TransportError } from './transport/transportError';
5
5
 
6
- const Brand = Symbol.for('near-api-ts.RpcError');
6
+ const Brand = Symbol.for('near-api-ts.RpcError'); // TODO check if it's a valid solution!
7
7
 
8
8
  const parseRequestValidationError = (name: string) => {
9
9
  if (name === 'PARSE_ERROR')
@@ -100,7 +100,7 @@ export class RpcError extends Error {
100
100
  super(
101
101
  `[${code}]: ${message} \n` +
102
102
  `Type: ${args.__rawRpcError.name} \n` +
103
- `Cause: ${JSON.stringify(args.__rawRpcError.cause, null, 2)}`,
103
+ `Cause: ${JSON.stringify(args.__rawRpcError, null, 2)}`,
104
104
  );
105
105
  this.name = 'RpcError';
106
106
  this.code = code;
@@ -1,14 +1,12 @@
1
1
  import type {
2
- AddKeyAction,
3
- FullAccessKeyParams,
2
+ AddFullAccessKeyAction,
3
+ CreateAddFullAccessKeyActionArgs,
4
4
  } from 'nat-types/actions/addKey';
5
5
 
6
- export const addFullAccessKey = ({
7
- publicKey,
8
- }: Omit<FullAccessKeyParams, 'accessType'>): AddKeyAction => ({
6
+ export const addFullAccessKey = (
7
+ args: CreateAddFullAccessKeyActionArgs,
8
+ ): AddFullAccessKeyAction => ({
9
+ ...args,
9
10
  actionType: 'AddKey',
10
- params: {
11
- accessType: 'FullAccess',
12
- publicKey,
13
- },
11
+ accessType: 'FullAccess',
14
12
  });
@@ -1,20 +1,12 @@
1
1
  import type {
2
- AddKeyAction,
3
- FunctionCallKeyParams,
2
+ AddFunctionCallKeyAction,
3
+ CreateAddFunctionCallKeyActionArgs,
4
4
  } from 'nat-types/actions/addKey';
5
5
 
6
- export const addFunctionCallKey = ({
7
- publicKey,
8
- contractAccountId,
9
- gasBudget,
10
- allowedFunctions,
11
- }: Omit<FunctionCallKeyParams, 'accessType'>): AddKeyAction => ({
6
+ export const addFunctionCallKey = (
7
+ args: CreateAddFunctionCallKeyActionArgs,
8
+ ): AddFunctionCallKeyAction => ({
9
+ ...args,
12
10
  actionType: 'AddKey',
13
- params: {
14
- accessType: 'FunctionCall',
15
- publicKey,
16
- contractAccountId,
17
- gasBudget,
18
- allowedFunctions,
19
- },
11
+ accessType: 'FunctionCall',
20
12
  });
@@ -1,11 +1,11 @@
1
1
  import type {
2
2
  DeleteAccountAction,
3
- DeleteAccountActionParams,
3
+ CreateDeleteAccountActionArgs,
4
4
  } from 'nat-types/actions/deleteAccount';
5
5
 
6
6
  export const deleteAccount = (
7
- params: DeleteAccountActionParams,
7
+ args: CreateDeleteAccountActionArgs,
8
8
  ): DeleteAccountAction => ({
9
+ ...args,
9
10
  actionType: 'DeleteAccount',
10
- params,
11
11
  });
@@ -1,9 +1,11 @@
1
1
  import type {
2
2
  DeleteKeyAction,
3
- DeleteKeyActionParams,
3
+ CreateDeleteKeyActionArgs,
4
4
  } from 'nat-types/actions/deleteKey';
5
5
 
6
- export const deleteKey = (params: DeleteKeyActionParams): DeleteKeyAction => ({
6
+ export const deleteKey = (
7
+ args: CreateDeleteKeyActionArgs,
8
+ ): DeleteKeyAction => ({
9
+ ...args,
7
10
  actionType: 'DeleteKey',
8
- params,
9
11
  });
@@ -1,13 +1,11 @@
1
1
  import type {
2
2
  DeployContractAction,
3
- DeployContractActionParams,
3
+ CreateDeployContractActionArgs,
4
4
  } from 'nat-types/actions/deployContract';
5
5
 
6
6
  export const deployContract = (
7
- params: DeployContractActionParams,
7
+ args: CreateDeployContractActionArgs,
8
8
  ): DeployContractAction => ({
9
+ ...args,
9
10
  actionType: 'DeployContract',
10
- params,
11
11
  });
12
-
13
-
@@ -1,12 +1,24 @@
1
1
  import type {
2
- FunctionCallAction,
3
- FunctionCallParams,
2
+ CreateFunctionCallAction,
3
+ InnerCreateFunctionCallActionArgs,
4
4
  } from 'nat-types/actions/functionCall';
5
- import type { MaybeJsonLikeValue } from 'nat-types/common';
5
+ import { toJsonBytes } from '@common/utils/common';
6
6
 
7
- export const functionCall = <AJ extends MaybeJsonLikeValue>(
8
- params: FunctionCallParams<AJ>,
9
- ): FunctionCallAction<AJ> => ({
10
- actionType: 'FunctionCall',
11
- params,
7
+ const serializeFunctionArgs = (args: InnerCreateFunctionCallActionArgs) => {
8
+ if (args?.options?.serializeArgs)
9
+ return args.options.serializeArgs({ functionArgs: args.functionArgs });
10
+
11
+ if (args?.functionArgs) return toJsonBytes(args?.functionArgs);
12
+
13
+ return new Uint8Array();
14
+ };
15
+
16
+ export const functionCall: CreateFunctionCallAction = (
17
+ args: InnerCreateFunctionCallActionArgs,
18
+ ) => ({
19
+ actionType: 'FunctionCall' as const,
20
+ functionName: args.functionName,
21
+ gasLimit: args.gasLimit,
22
+ functionArgs: serializeFunctionArgs(args),
23
+ attachedDeposit: args.attachedDeposit,
12
24
  });
@@ -1,9 +1,9 @@
1
1
  import type {
2
2
  TransferAction,
3
- TransferActionParams,
3
+ CreateTransferActionArgs,
4
4
  } from 'nat-types/actions/transfer';
5
5
 
6
- export const transfer = (params: TransferActionParams): TransferAction => ({
6
+ export const transfer = (args: CreateTransferActionArgs): TransferAction => ({
7
+ ...args,
7
8
  actionType: 'Transfer',
8
- params,
9
9
  });
@@ -1,52 +1,20 @@
1
- import * as v from 'valibot';
2
- import type {
3
- PublicKey,
4
- PrivateKey,
5
- Ed25519CurveString,
6
- Secp256k1CurveString,
7
- } from 'nat-types/crypto';
8
1
  import {
9
2
  fromCurveString,
10
3
  toEd25519CurveString,
11
4
  toSecp256k1CurveString,
12
5
  } from '@common/transformers/curveString';
13
- import {
14
- BinarySecp256k1PrivateKeySchema,
15
- BinaryEd25519PrivateKeySchema,
16
- } from '@common/schemas/valibot/privateKey';
17
6
  import { BinaryCryptoKeyLengths } from '@common/configs/constants';
7
+ import type { PublicKey, PrivateKey } from 'nat-types/crypto';
18
8
 
19
9
  const { Ed25519, Secp256k1 } = BinaryCryptoKeyLengths;
20
10
 
21
- const getBinaryEd25519PublicKey = (
22
- u8Ed25519PrivateKey: Uint8Array,
23
- ): Uint8Array => {
24
- const validEd25519PrivateKey = v.parse(
25
- BinaryEd25519PrivateKeySchema,
26
- u8Ed25519PrivateKey,
27
- );
28
- return validEd25519PrivateKey.slice(Ed25519.SecretKey);
29
- };
30
-
31
- const getEd25519PublicKey = (u8PrivateKey: Uint8Array): Ed25519CurveString => {
32
- const u8PublicKey = getBinaryEd25519PublicKey(u8PrivateKey);
11
+ const getEd25519PublicKey = (u8PrivateKey: Uint8Array) => {
12
+ const u8PublicKey = u8PrivateKey.slice(Ed25519.SecretKey);
33
13
  return toEd25519CurveString(u8PublicKey);
34
14
  };
35
15
 
36
- const getBinarySecp256k1PublicKey = (
37
- u8Secp256k1PrivateKey: Uint8Array,
38
- ): Uint8Array => {
39
- const validU8PrivateKey = v.parse(
40
- BinarySecp256k1PrivateKeySchema,
41
- u8Secp256k1PrivateKey,
42
- );
43
- return validU8PrivateKey.slice(Secp256k1.SecretKey);
44
- };
45
-
46
- const getSecp256k1PublicKey = (
47
- u8Secp256k1PrivateKey: Uint8Array,
48
- ): Secp256k1CurveString => {
49
- const u8PublicKey = getBinarySecp256k1PublicKey(u8Secp256k1PrivateKey);
16
+ const getSecp256k1PublicKey = (u8PrivateKey: Uint8Array) => {
17
+ const u8PublicKey = u8PrivateKey.slice(Secp256k1.SecretKey);
50
18
  return toSecp256k1CurveString(u8PublicKey);
51
19
  };
52
20
 
@@ -1,4 +1,3 @@
1
- import * as v from 'valibot';
2
1
  import type { PrivateKey, Signature } from 'nat-types/crypto';
3
2
  import type { Hex } from 'nat-types/common';
4
3
  import { ed25519 } from '@noble/curves/ed25519';
@@ -8,36 +7,25 @@ import {
8
7
  toEd25519CurveString,
9
8
  toSecp256k1CurveString,
10
9
  } from '@common/transformers/curveString';
11
- import {
12
- BinarySecp256k1PrivateKeySchema,
13
- BinaryEd25519PrivateKeySchema,
14
- } from '@common/schemas/valibot/privateKey';
15
10
  import { BinaryCryptoKeyLengths } from '@common/configs/constants';
16
11
 
17
- const { Ed25519, Secp256k1 } = BinaryCryptoKeyLengths;
18
-
19
- const getBinaryEd25519SecretKey = (u8PrivateKey: Uint8Array) =>
20
- v
21
- .parse(BinaryEd25519PrivateKeySchema, u8PrivateKey)
22
- .slice(0, Ed25519.SecretKey);
23
-
24
12
  const signByEd25519Key = (message: Hex, u8PrivateKey: Uint8Array) => {
25
- const u8SecretKey = getBinaryEd25519SecretKey(u8PrivateKey);
13
+ const u8SecretKey = u8PrivateKey.slice(
14
+ 0,
15
+ BinaryCryptoKeyLengths.Ed25519.SecretKey,
16
+ );
26
17
  const u8Signature = ed25519.sign(message, u8SecretKey);
27
-
28
18
  return {
29
19
  signature: toEd25519CurveString(u8Signature),
30
20
  u8Signature,
31
21
  };
32
22
  };
33
23
 
34
- const getBinarySecp256k1SecretKey = (u8PrivateKey: Uint8Array) =>
35
- v
36
- .parse(BinarySecp256k1PrivateKeySchema, u8PrivateKey)
37
- .slice(0, Secp256k1.SecretKey);
38
-
39
24
  const signBySecp256k1Key = (message: Hex, u8PrivateKey: Uint8Array) => {
40
- const u8SecretKey = getBinarySecp256k1SecretKey(u8PrivateKey);
25
+ const u8SecretKey = u8PrivateKey.slice(
26
+ 0,
27
+ BinaryCryptoKeyLengths.Secp256k1.SecretKey,
28
+ );
41
29
  const signatureObj = secp256k1.sign(message, u8SecretKey);
42
30
 
43
31
  const u8Signature = new Uint8Array([
@@ -51,17 +39,17 @@ const signBySecp256k1Key = (message: Hex, u8PrivateKey: Uint8Array) => {
51
39
  };
52
40
  };
53
41
 
54
- type SignInput = {
42
+ type SignArgs = {
55
43
  message: Hex;
56
44
  privateKey: PrivateKey;
57
45
  };
58
46
 
59
- type SignOutput = {
47
+ type SignResult = {
60
48
  signature: Signature;
61
49
  u8Signature: Uint8Array;
62
50
  };
63
51
 
64
- export const sign = ({ message, privateKey }: SignInput): SignOutput => {
52
+ export const sign = ({ message, privateKey }: SignArgs): SignResult => {
65
53
  const { curve, u8Data: u8PrivateKey } = fromCurveString(privateKey);
66
54
  return curve === 'ed25519'
67
55
  ? signByEd25519Key(message, u8PrivateKey)
@@ -0,0 +1,123 @@
1
+ import type {
2
+ Gas,
3
+ GasInputAmount,
4
+ NearGas,
5
+ NearGasArgs,
6
+ TeraGas,
7
+ TeraGasInputAmount,
8
+ } from 'nat-types/nearGas';
9
+ import { nodeInspectSymbol } from '@common/utils/common';
10
+ import type { InspectOptionsStylized } from 'node:util';
11
+
12
+ const TeraCoefficient = 1_000_000_000_000n; // 10 ** 12
13
+ const NearGasBrand = Symbol('NearGasBrand');
14
+
15
+ const cache = {
16
+ gas: new WeakMap<NearGas, Gas>(),
17
+ teraGas: new WeakMap<NearGas, TeraGas>(),
18
+ };
19
+
20
+ const toGas = (x: NearGasArgs | NearGas): Gas =>
21
+ isNearGas(x) ? x.gas : nearGas(x).gas;
22
+
23
+ /**
24
+ * We use it as a prototype for all new NearGas instances. It allows us to reuse
25
+ * these functions without creating a new fn instances every time we create a new NearGas
26
+ */
27
+ const nearGasProto: ThisType<NearGas> = {
28
+ [NearGasBrand]: true,
29
+ // Lazy getter - calculate the 'gas' value only after the first direct access;
30
+ // save the result in the cache
31
+ get gas(): Gas {
32
+ const maybeValue = cache.gas.get(this);
33
+ if (maybeValue) return maybeValue;
34
+
35
+ const value = BigInt(this.teraGas) * TeraCoefficient;
36
+ cache.gas.set(this, value);
37
+
38
+ return value;
39
+ },
40
+
41
+ get teraGas(): TeraGas {
42
+ const maybeValue = cache.teraGas.get(this);
43
+ if (maybeValue) return maybeValue;
44
+
45
+ const value = String(this.gas / TeraCoefficient); // We don't keep decimals
46
+ cache.teraGas.set(this, value);
47
+
48
+ return value;
49
+ },
50
+
51
+ add(x: NearGasArgs | NearGas): NearGas {
52
+ return gas(this.gas + toGas(x));
53
+ },
54
+
55
+ sub(x: NearGasArgs | NearGas): NearGas {
56
+ return gas(this.gas - toGas(x));
57
+ },
58
+
59
+ mul(x: NearGasArgs | NearGas): NearGas {
60
+ return gas(this.gas * toGas(x));
61
+ },
62
+
63
+ gt(x: NearGasArgs | NearGas): boolean {
64
+ return this.gas > toGas(x);
65
+ },
66
+
67
+ lt(x: NearGasArgs | NearGas): boolean {
68
+ return this.gas < toGas(x);
69
+ },
70
+
71
+ toString() {
72
+ return JSON.stringify({
73
+ teraGas: this.teraGas,
74
+ gas: this.gas.toString(),
75
+ });
76
+ },
77
+
78
+ // In Node.js, this allows you to see the teraGas/gas getter values,
79
+ // which are not normally visible unless you access them directly.
80
+ // This does not work in the browser — there you can only see a getter’s value
81
+ // by explicitly expanding/clicking on it.
82
+ ...(nodeInspectSymbol && {
83
+ [nodeInspectSymbol as symbol](
84
+ this: NearGas,
85
+ _depth: number,
86
+ _opts: InspectOptionsStylized,
87
+ ) {
88
+ return { teraGas: this.teraGas, gas: this.gas };
89
+ },
90
+ }),
91
+ } as const;
92
+
93
+ export const gas = (gasInputAmount: GasInputAmount): NearGas => {
94
+ const gasValue = BigInt(gasInputAmount); // TODO validate
95
+ const nearGas = Object.create(nearGasProto) as NearGas;
96
+
97
+ Object.defineProperty(nearGas, 'gas', {
98
+ value: gasValue,
99
+ enumerable: true,
100
+ });
101
+
102
+ return Object.freeze(nearGas);
103
+ };
104
+
105
+ export const teraGas = (teraGas: TeraGasInputAmount): NearGas => {
106
+ const nearGas = Object.create(nearGasProto) as NearGas;
107
+
108
+ Object.defineProperty(nearGas, 'teraGas', {
109
+ value: teraGas, // TODO Validate
110
+ enumerable: true,
111
+ });
112
+
113
+ return Object.freeze(nearGas);
114
+ };
115
+
116
+ export const nearGas = (args: NearGasArgs): NearGas => {
117
+ if ('teraGas' in args) return teraGas(args.teraGas);
118
+ if ('gas' in args) return gas(args.gas);
119
+ throw new Error('Invalid gas option');
120
+ };
121
+
122
+ export const isNearGas = (value: unknown): value is NearGas =>
123
+ typeof value === 'object' && value !== null && NearGasBrand in value;