starknet 11.9.3 → 11.10.1

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ ## [11.10.1](https://github.com/starknet-io/starknet.js/compare/v11.10.0...v11.10.1) (2026-11-30)
2
+
3
+ ### Bug Fixes
4
+
5
+ - **batch:** return the node error when a whole batch is rejected ([#1769](https://github.com/starknet-io/starknet.js/issues/1769)) ([86b3c65](https://github.com/starknet-io/starknet.js/commit/86b3c6529ccc703f33d5afa4d8e438248305c2a4))
6
+
7
+ # [11.10.0](https://github.com/starknet-io/starknet.js/compare/v11.9.3...v11.10.0) (2026-11-26)
8
+
9
+ ### Features
10
+
11
+ - **utils:** add parseUnits and formatUnits for any number of decimals ([#1768](https://github.com/starknet-io/starknet.js/issues/1768)) ([3965479](https://github.com/starknet-io/starknet.js/commit/3965479aecd9644df16d43897d3416709debd67a))
12
+
1
13
  ## [11.9.3](https://github.com/starknet-io/starknet.js/compare/v11.9.2...v11.9.3) (2026-11-26)
2
14
 
3
15
  ### Bug Fixes
package/dist/index.d.ts CHANGED
@@ -18624,6 +18624,7 @@ declare function createTransactionReceipt(receipt: GetTxReceiptResponseWithoutHe
18624
18624
 
18625
18625
  /**
18626
18626
  * Convert strk to fri or fri to strk. Negative amounts are accepted in both directions.
18627
+ * For another token, use `parseUnits` and `formatUnits`.
18627
18628
  * @param {string | bigint} amount amount to convert, in the unit given by `symbol`
18628
18629
  * @param {'fri' | 'strk'} symbol unit of `amount`: 'fri' (default) gives strk, 'strk' gives fri
18629
18630
  * @throws {Error} if a strk amount is not a bigint, a hex string or a decimal string
@@ -18639,6 +18640,54 @@ declare function createTransactionReceipt(receipt: GetTxReceiptResponseWithoutHe
18639
18640
  * ```
18640
18641
  */
18641
18642
  declare function units(amount: string | bigint, symbol?: 'fri' | 'strk'): string;
18643
+ /**
18644
+ * Convert a decimal amount of a token, written as text, into an integer in the smallest unit
18645
+ * of the token. With 6 decimals, '1.5' gives 1500000n.
18646
+ *
18647
+ * Only text is accepted, on purpose:
18648
+ * - an amount read on-chain is already in the smallest unit of the token: a bigint from a
18649
+ * contract call, or a hex text from a node. Passed here by mistake, it would be multiplied
18650
+ * by 10^decimals, without an error. To display such an amount, use `formatUnits`.
18651
+ * - a JavaScript number can be inexact: `0.1 + 0.2` is `0.30000000000000004`.
18652
+ *
18653
+ * @param {string} value decimal amount: an optional minus sign, then digits with at most one
18654
+ * dot ('1', '-1.5', '.5', '1.')
18655
+ * @param {BigNumberish} decimals number of decimals of the token: an integer from 0 to 255
18656
+ * @param {string} [tokenName] name of the token, written in the error messages
18657
+ * @returns {bigint} the amount in the smallest unit of the token
18658
+ * @throws {Error} if `value` is not a decimal amount, or has more than `decimals` decimals,
18659
+ * not counting zeros at the end
18660
+ * @throws {Error} if `decimals` is not an integer from 0 to 255, or if `tokenName` is empty
18661
+ * @example
18662
+ * ```typescript
18663
+ * parseUnits('1.5', 6); // 1500000n
18664
+ * parseUnits('-0.25', 6); // -250000n
18665
+ * parseUnits('1.1234567', 6, 'USDC');
18666
+ * // throws Error("'1.1234567' USDC has more than 6 decimals")
18667
+ * ```
18668
+ */
18669
+ declare function parseUnits(value: string, decimals: BigNumberish, tokenName?: string): bigint;
18670
+ /**
18671
+ * Write an amount given in the smallest unit of a token as a decimal amount of the token.
18672
+ * With 6 decimals, 1500000n gives '1.5'. The result has no zero at the end, and no dot when it
18673
+ * has no decimals.
18674
+ * @param {BigNumberish} value amount in the smallest unit of the token: a bigint (as a contract
18675
+ * call returns it), a hex text (as a node returns it), a decimal text or a number
18676
+ * @param {BigNumberish} decimals number of decimals of the token: an integer from 0 to 255
18677
+ * @param {string} [tokenName] name of the token, written in the error messages
18678
+ * @returns {string} the decimal amount
18679
+ * @throws {Error} if `value` is an empty string, or is not a number, a bigint or a string
18680
+ * @throws {SyntaxError} if `value` is a text that `BigInt` cannot read, such as '1.5'
18681
+ * @throws {Error} if `decimals` is not an integer from 0 to 255, or if `tokenName` is empty
18682
+ * @example
18683
+ * ```typescript
18684
+ * formatUnits(1500000n, 6); // '1.5'
18685
+ * formatUnits('0x2710', 6); // '0.01'
18686
+ * formatUnits(-1500000n, 6, 'USDC'); // '-1.5'
18687
+ * formatUnits(10n ** 18n, 18); // '1'
18688
+ * ```
18689
+ */
18690
+ declare function formatUnits(value: BigNumberish, decimals: BigNumberish, tokenName?: string): string;
18642
18691
 
18643
18692
  /**
18644
18693
  * Request Permission for wallet account, return addresses that are allowed by user
@@ -19120,5 +19169,5 @@ declare class Logger {
19120
19169
  */
19121
19170
  declare const logger: Logger;
19122
19171
 
19123
- export { AbiParser0, AbiParser1, AbiParser2, AbiParserInterface, Account, AccountInterface, BatchClient, BlockStatus, BlockTag, BrotherIdImpl, CairoArray, CairoBool, CairoByteArray, CairoBytes31, CairoClassHash, CairoContractAddress, CairoCustomEnum, CairoEthAddress, CairoFelt252, CairoFixedArray, CairoInt128, CairoInt16, CairoInt32, CairoInt64, CairoInt8, CairoNonZero, CairoOption, CairoOptionVariant, CairoResult, CairoResultVariant, CairoSecp256k1Point, CairoStorageAddress, CairoStruct, CairoTuple, CairoTypeCustomEnum, CairoTypeOption, CairoTypeResult, CairoUint128, CairoUint16, CairoUint256, CairoUint32, CairoUint512, CairoUint64, CairoUint8, CairoUint96, CallData, Contract, ContractInterface, Deployer, DeployerInterface, EDAMode, EDataAvailabilityMode, ESubscriptionTag, ETH_ADDRESS, ETraceFlag, ETransactionExecutionStatus, ETransactionStatus, ETransactionVersion, ETransactionVersion3, ETxnResponseFlag, EntryPointType, EthSigner, HttpTransport, Int, LedgerSigner111 as LedgerSigner, LedgerSigner111, LedgerSigner221, LedgerSigner231, LibraryError, Literal, LogLevelIndex, NON_ZERO_PREFIX, OutsideExecutionTypesV1, OutsideExecutionTypesV2, OutsideExecutionVersion, PaymasterInterface, PaymasterRpc, PluginManager, Provider, ProviderInterface, index$9 as RPC, index$7 as RPC0102, index$6 as RPC0103, index$5 as RPC0104, index$4 as RPC0105, index$8 as RPC09, RPCResponseParser, ReconnectingWsTransport, ResponseParser, RpcChannel, RpcError, RpcProvider, SECP256K1_POINT_MAX, SECP256K1_POINT_MIN, Signer, SignerInterface, StarknetIdImpl, Subscription, TimeoutError, TransactionExecutionStatus, TransactionFinalityStatus, TransactionType, UINT_128_MAX, UINT_128_MIN, UINT_256_HIGH_MAX, UINT_256_HIGH_MIN, UINT_256_LOW_MAX, UINT_256_LOW_MIN, UINT_256_MAX, UINT_256_MIN, UINT_512_MAX, UINT_512_MIN, Uint, ValidateType, WalletAccount, WalletAccountV5, WalletAccountV6, WebSocketChannel, WebSocketNotConnectedError, WebSocketProvider, WsTransport, addAddressPadding, brotherId, byteArray, cairo, cairoTypeStrategy, compareVersions, config, constants, contractClassResponseToLegacyCompiledContract, contractLoader, createAbiParser, createTransactionReceipt, defaultDeployer, defaultPlugins, ec, encode, enumStrategy, eth, index as events, extractContractHashes, fastCairoTypeStrategy, fastExecute, fastParsingStrategy, getAbiVersion, getChecksumAddress, getGasPrices, getLedgerPathBuffer111 as getLedgerPathBuffer, getLedgerPathBuffer111, getLedgerPathBuffer221, getTipStatsFromBlocks, index$3 as hash, hdParsingStrategy, isAccount, isCairoType, isFileSystemAvailable, isNoConstructorValid, isPreConfirmedBlock, isPreConfirmedStateUpdate, isPreConfirmedTransaction, isRPC08Plus_ResourceBounds, isRPC08Plus_ResourceBoundsBN, isSierra, isSupportedSpecVersion, isV3Tx, isVersion, json, legacyDeployer, logger, merkle, num, outsideExecution, parseCalldataField, utils as paymaster, paymasterPlugin, provider, selector, shortString, src5, index$1 as stark, starknetId, starknetId$1 as starknetIdPlugin, structStrategy, toAnyPatchVersion, toApiVersion, toReleaseVersion, index$2 as transaction, typedData, uint256, units, v3 as v3hash, validateAndParseAddress, validateChecksumAddress, verifyMessageInStarknet, connect as wallet, connectV5 as walletV5, connectV6 as walletV6 };
19172
+ export { AbiParser0, AbiParser1, AbiParser2, AbiParserInterface, Account, AccountInterface, BatchClient, BlockStatus, BlockTag, BrotherIdImpl, CairoArray, CairoBool, CairoByteArray, CairoBytes31, CairoClassHash, CairoContractAddress, CairoCustomEnum, CairoEthAddress, CairoFelt252, CairoFixedArray, CairoInt128, CairoInt16, CairoInt32, CairoInt64, CairoInt8, CairoNonZero, CairoOption, CairoOptionVariant, CairoResult, CairoResultVariant, CairoSecp256k1Point, CairoStorageAddress, CairoStruct, CairoTuple, CairoTypeCustomEnum, CairoTypeOption, CairoTypeResult, CairoUint128, CairoUint16, CairoUint256, CairoUint32, CairoUint512, CairoUint64, CairoUint8, CairoUint96, CallData, Contract, ContractInterface, Deployer, DeployerInterface, EDAMode, EDataAvailabilityMode, ESubscriptionTag, ETH_ADDRESS, ETraceFlag, ETransactionExecutionStatus, ETransactionStatus, ETransactionVersion, ETransactionVersion3, ETxnResponseFlag, EntryPointType, EthSigner, HttpTransport, Int, LedgerSigner111 as LedgerSigner, LedgerSigner111, LedgerSigner221, LedgerSigner231, LibraryError, Literal, LogLevelIndex, NON_ZERO_PREFIX, OutsideExecutionTypesV1, OutsideExecutionTypesV2, OutsideExecutionVersion, PaymasterInterface, PaymasterRpc, PluginManager, Provider, ProviderInterface, index$9 as RPC, index$7 as RPC0102, index$6 as RPC0103, index$5 as RPC0104, index$4 as RPC0105, index$8 as RPC09, RPCResponseParser, ReconnectingWsTransport, ResponseParser, RpcChannel, RpcError, RpcProvider, SECP256K1_POINT_MAX, SECP256K1_POINT_MIN, Signer, SignerInterface, StarknetIdImpl, Subscription, TimeoutError, TransactionExecutionStatus, TransactionFinalityStatus, TransactionType, UINT_128_MAX, UINT_128_MIN, UINT_256_HIGH_MAX, UINT_256_HIGH_MIN, UINT_256_LOW_MAX, UINT_256_LOW_MIN, UINT_256_MAX, UINT_256_MIN, UINT_512_MAX, UINT_512_MIN, Uint, ValidateType, WalletAccount, WalletAccountV5, WalletAccountV6, WebSocketChannel, WebSocketNotConnectedError, WebSocketProvider, WsTransport, addAddressPadding, brotherId, byteArray, cairo, cairoTypeStrategy, compareVersions, config, constants, contractClassResponseToLegacyCompiledContract, contractLoader, createAbiParser, createTransactionReceipt, defaultDeployer, defaultPlugins, ec, encode, enumStrategy, eth, index as events, extractContractHashes, fastCairoTypeStrategy, fastExecute, fastParsingStrategy, formatUnits, getAbiVersion, getChecksumAddress, getGasPrices, getLedgerPathBuffer111 as getLedgerPathBuffer, getLedgerPathBuffer111, getLedgerPathBuffer221, getTipStatsFromBlocks, index$3 as hash, hdParsingStrategy, isAccount, isCairoType, isFileSystemAvailable, isNoConstructorValid, isPreConfirmedBlock, isPreConfirmedStateUpdate, isPreConfirmedTransaction, isRPC08Plus_ResourceBounds, isRPC08Plus_ResourceBoundsBN, isSierra, isSupportedSpecVersion, isV3Tx, isVersion, json, legacyDeployer, logger, merkle, num, outsideExecution, parseCalldataField, parseUnits, utils as paymaster, paymasterPlugin, provider, selector, shortString, src5, index$1 as stark, starknetId, starknetId$1 as starknetIdPlugin, structStrategy, toAnyPatchVersion, toApiVersion, toReleaseVersion, index$2 as transaction, typedData, uint256, units, v3 as v3hash, validateAndParseAddress, validateChecksumAddress, verifyMessageInStarknet, connect as wallet, connectV5 as walletV5, connectV6 as walletV6 };
19124
19173
  export type { Abi, AbiEntry, AbiEntryType, AbiEnum, AbiEnums, AbiEvent, AbiEvents, AbiInterfaces, AbiStruct, AbiStructs, AccountHooks, AccountInvocationItem, AccountInvocations, AccountInvocationsFactoryDetails, AccountOptions, AllowArray, ApiEstimateFeeResponse, Args, ArgsOrCalldata, ArraySignatureType, AsyncContractFunction, BLOCK_HASH, BLOCK_NUMBER, BatchClientOptions, BigNumberish, Block$1 as Block, BlockIdentifier, BlockNumber, BlockTransactionTrace, BlockTransactionsTracesWithInitialReads, BlockWithTxHashes, BrotherIdProviderMethods, BrotherProfile, Builtins, ByteArray, ByteCode, CairoAssembly, CairoContract, CairoEnum, CairoEnumRaw, CairoEvent, CairoEventDefinition, CairoEventVariant, CairoType, CairoTypeStrategy, CairoVersion, Call, CallContractResponse, CallDetails, CallOptions, CallResult, Calldata, CommonContractOptions, CompiledContract, CompiledSierra, CompiledSierraCasm, CompilerVersion, CompleteDeclareContractPayload, CompressedProgram, ContractClass, ContractClassIdentifier, ContractClassPayload, ContractClassResponse, ContractEntryPointFields, ContractFunction, ContractOptions, ContractVersion, DeclareAndDeployContractPayload, DeclareContractPayload, DeclareContractResponse, DeclareContractTransaction, DeclareDeployUDCResponse, DeclareSignerDetails, DeclareTransactionReceiptResponse, DeclaredTransaction, DeployAccountContractPayload, DeployAccountContractTransaction, DeployAccountSignerDetails, DeployAccountTransactionReceiptResponse, DeployAndInvokeTransaction, DeployContractResponse, DeployContractUDCResponse, DeployTransaction, DeployTransactionReceiptResponse, DeployedAccountTransaction, DeployerCall, EVENTS_CHUNK, EmittedEvent, EntryPointsByType, ErrorReceiptResponseHelper, EstimateFeeBulk, EstimateFeeResponseBulkOverhead, EstimateFeeResponseOverhead, Event$1 as Event, EventEntry, EventFilter, ExecutableDeployAndInvokeTransaction, ExecutableDeployTransaction, ExecutableInvokeTransaction, ExecutableUserInvoke, ExecutableUserTransaction, ExecuteOptions, ExecutionParameters, FEE_ESTIMATE, FELT, FactoryParams, FastExecuteAccountMethods, FastExecuteProviderMethods, FastExecuteResponse, FastWaitForTransactionOptions, FeeEstimate, FeeMode, FormatResponse, FunctionAbi, GasPrices, GetBlockResponse, GetTransactionReceiptResponse, GetTransactionResponse, GetTxReceiptResponseWithoutHelper, HexCalldata, Hint, HttpTransportOptions, INITIAL_READS, InterfaceAbi, Invocation, Invocations, InvocationsDetails, InvocationsDetailsWithNonce, InvocationsSignerDetails, InvokeFunctionResponse, InvokeTransaction, InvokeTransactionReceiptResponse, InvokedTransaction, L1HandlerTransactionReceiptResponse, L1_HANDLER_TXN, LedgerPathCalculation, LegacyCompiledContract, LegacyContractClass, LegacyEvent, LoadedContract, LogLevel, Methods, MultiDeployContractResponse, MultiType, Nonce, OptionalPayload, OutsideCall, OutsideExecution, OutsideExecutionOptions, OutsideTransaction, PRE_CONFIRMED_STATE_UPDATE, PRICE_UNIT, ParsedEvent, ParsedEvents, ParsedStruct, ParsingStrategy, PaymasterAccountMethods, PaymasterDetails, PaymasterFeeEstimate, PaymasterOptions, PaymasterRpcOptions, PaymasterTimeBounds, PluginConfig, PreConfirmedBlock, PreConfirmedStateUpdate, PreparedDeployAndInvokeTransaction, PreparedDeployTransaction, PreparedInvokeTransaction, PreparedTransaction, Program, ProviderHooks, ProviderOptions, ProviderOrAccount, PythonicHints, RESOURCE_PRICE, RPC_ERROR, RPC_ERROR_SET, RawArgs, RawArgsArray, RawArgsObject, RawCalldata, Receipt, ReconnectOptions, ReconnectingWsTransportOptions, RequiredKeysOf, ResourceBounds, ResourceBoundsBN, ResourceBoundsOverhead, RevertedTransactionReceiptResponse, RevertedTransactionReceiptResponseHelper, RpcNotification, RpcProviderOptions, RpcTransport, SIMULATION_FLAG, STATE_UPDATE, STRK20_ACTION, STRK20_CALL_AND_PROOF, STRK20_SHADOW_ACCOUNT_INVOKE_ACTION, Secp256k1PointStruct, SierraContractClass, SierraContractEntryPointFields, SierraEntryPointsByType, SierraProgramDebugInfo, Signature, Simplify, SimulateTransaction, SimulateTransactionDetails, SimulateTransactionOverhead, SimulateTransactionOverheadResponse, SimulateTransactionResponse, SimulationFlags, StarkProfile, StarknetIdAccountMethods, StarknetIdProviderMethods, StarknetPlugin, StateUpdate, StateUpdateResponse, StorageResponse, SubscribeEventsParams, SubscribeNewHeadsParams, SubscribeNewTransactionReceiptsParams, SubscribeNewTransactionsParams, SubscribeTransactionStatusParams, SubscriptionBlockIdentifier, SubscriptionNewHeadsEvent, SubscriptionNewTransactionEvent, SubscriptionNewTransactionReceiptsEvent, SubscriptionOptions, SubscriptionOwner, SubscriptionStarknetEventsEvent, SubscriptionTransactionStatusEvent, SuccessfulTransactionReceiptResponse, SuccessfulTransactionReceiptResponseHelper, TXN_EXECUTION_STATUS, TXN_HASH, TXN_STATUS, TipAnalysisOptions, TipEstimate, TipType, TokenData, TransactionReceipt, TransactionReceiptCallbacks, TransactionReceiptCallbacksDefault, TransactionReceiptCallbacksDefined, TransactionReceiptStatus, TransactionReceiptValue, TransactionStatus, TransactionStatusReceiptSets, TransactionTrace, TransactionWithHash, Tupled, TypedContractV2, Uint256, Uint512, UniversalDeployerContractPayload, UniversalDetails, UserInvoke, UserTransaction, V3DeclareSignerDetails, V3DeployAccountSignerDetails, V3InvocationsSignerDetails, V3TransactionDetails, VariantType, WebSocketModule, WebSocketOptions, WebSocketProviderOptions, WeierstrassSignatureType, WithOptions, WsTransportOptions, WsTransportState, getBlockTransactionsTracesOptions, getContractVersionOptions, getEstimateFeeBulkOptions, getSimulateTransactionOptions, waitForTransactionOptions };
@@ -195,6 +195,7 @@ var starknet = (() => {
195
195
  fastCairoTypeStrategy: () => fastCairoTypeStrategy,
196
196
  fastExecute: () => fastExecute,
197
197
  fastParsingStrategy: () => fastParsingStrategy,
198
+ formatUnits: () => formatUnits,
198
199
  getAbiVersion: () => getAbiVersion,
199
200
  getChecksumAddress: () => getChecksumAddress,
200
201
  getGasPrices: () => getGasPrices,
@@ -224,6 +225,7 @@ var starknet = (() => {
224
225
  num: () => num_exports,
225
226
  outsideExecution: () => outsideExecution_exports,
226
227
  parseCalldataField: () => parseCalldataField,
228
+ parseUnits: () => parseUnits,
227
229
  paymaster: () => utils_exports2,
228
230
  paymasterPlugin: () => paymasterPlugin,
229
231
  provider: () => provider_exports,
@@ -19477,8 +19479,17 @@ ${indent}}` : "}";
19477
19479
  this.batchPromises[key] = promise;
19478
19480
  });
19479
19481
  }
19480
- const results = await this.batchPromises[requestId];
19481
- delete this.batchPromises[requestId];
19482
+ let results;
19483
+ try {
19484
+ results = await this.batchPromises[requestId];
19485
+ } finally {
19486
+ delete this.batchPromises[requestId];
19487
+ }
19488
+ if (!Array.isArray(results)) {
19489
+ const reply = results;
19490
+ if (reply?.error) return reply;
19491
+ throw new Error(`Unexpected reply to a batch request. Method: ${String(method)}`);
19492
+ }
19482
19493
  const result = results.find((res) => res.id === requestId);
19483
19494
  if (!result)
19484
19495
  throw new Error(`Couldn't find the result for the request. Method: ${String(method)}`);
@@ -27641,36 +27652,80 @@ ${indent}}` : "}";
27641
27652
  };
27642
27653
 
27643
27654
  // src/utils/units.ts
27655
+ function amountName(tokenName) {
27656
+ return tokenName ? `${tokenName} amount` : "amount";
27657
+ }
27658
+ function checkTokenName(tokenName) {
27659
+ if (tokenName === void 0) return;
27660
+ assert(isString(tokenName), `the token name must be a string, not ${typeof tokenName}`);
27661
+ assert(tokenName.trim() !== "", "the token name is an empty string");
27662
+ }
27663
+ function toDecimals(decimals) {
27664
+ const shown = isString(decimals) ? `'${decimals}'` : String(decimals);
27665
+ assert(
27666
+ isBigNumberish(decimals) && (!isNumber2(decimals) || Number.isInteger(decimals)),
27667
+ `decimals must be an integer, not ${shown}`
27668
+ );
27669
+ assertInRange(decimals, RANGE_U8.min, RANGE_U8.max, "decimals");
27670
+ return Number(decimals);
27671
+ }
27672
+ function decimalToInteger(text, decimals, tokenName) {
27673
+ const match = /^(-?)(\d*)(?:\.(\d*))?$/.exec(text);
27674
+ assert(
27675
+ match !== null && `${match[2]}${match[3] ?? ""}` !== "",
27676
+ `'${text}' is not a valid ${amountName(tokenName)}`
27677
+ );
27678
+ const [, sign2, integer, fraction = ""] = match;
27679
+ const name = tokenName ? ` ${tokenName}` : "";
27680
+ const unit = decimals === 1 ? "decimal" : "decimals";
27681
+ assert(
27682
+ !/[1-9]/.test(fraction.slice(decimals)),
27683
+ `'${text}'${name} has more than ${decimals} ${unit}`
27684
+ );
27685
+ const result = BigInt(`0${integer}${fraction.slice(0, decimals).padEnd(decimals, "0")}`);
27686
+ return sign2 === "-" ? -result : result;
27687
+ }
27688
+ function integerToDecimal(value, decimals, tokenName) {
27689
+ assert(
27690
+ !isString(value) || value.trim() !== "",
27691
+ `the ${amountName(tokenName)} is an empty string`
27692
+ );
27693
+ const integer = toBigInt(value);
27694
+ const sign2 = integer < 0n ? "-" : "";
27695
+ const digits = (integer < 0n ? -integer : integer).toString();
27696
+ let text;
27697
+ if (digits.length <= decimals) {
27698
+ text = `0.${digits.padStart(decimals, "0")}`;
27699
+ } else {
27700
+ text = `${digits.slice(0, digits.length - decimals)}.${digits.slice(digits.length - decimals)}`;
27701
+ }
27702
+ return sign2 + text.replace(/(\.[0-9]*[1-9])0+$|\.0*$/, "$1");
27703
+ }
27644
27704
  function units(amount, symbol = "fri") {
27645
27705
  if (symbol === "strk") {
27646
- if (!isBigInt(amount) && !isString(amount)) {
27647
- throw new Error(`units: a strk amount must be a string or a bigint, not ${typeof amount}`);
27648
- }
27649
- const numStr = isBigInt(amount) || isHex2(amount) ? toBigInt(amount).toString() : amount;
27650
- const match = /^(-?)(\d*)(?:\.(\d*))?$/.exec(numStr);
27651
- if (!match || `${match[2]}${match[3] ?? ""}` === "") {
27652
- throw new Error(`units: '${numStr}' is not a strk amount`);
27653
- }
27654
- const [, sign3, integer, decimal = ""] = match;
27655
- if (/[1-9]/.test(decimal.slice(18))) {
27656
- throw new Error(`units: '${numStr}' strk has more than 18 decimals`);
27657
- }
27658
- const fri2 = BigInt(`${integer}${decimal.slice(0, 18).padEnd(18, "0")}`);
27659
- return fri2 === 0n ? "0" : `${sign3}${fri2.toString()}`;
27660
- }
27661
- if (isString(amount) && amount.trim() === "") {
27662
- throw new Error("units: the fri amount is an empty string");
27663
- }
27664
- const fri = toBigInt(amount);
27665
- const sign2 = fri < 0n ? "-" : "";
27666
- const bis = (fri < 0n ? -fri : fri).toString();
27667
- let strk;
27668
- if (bis.length <= 18) {
27669
- strk = `0.${bis.padStart(18, "0")}`;
27670
- } else {
27671
- strk = `${bis.slice(0, bis.length - 18)}.${bis.slice(bis.length - 18)}`;
27706
+ assert(
27707
+ isBigInt(amount) || isString(amount),
27708
+ `the strk amount must be a string or a bigint, not ${typeof amount}`
27709
+ );
27710
+ const text = isBigInt(amount) || isHex2(amount) ? toBigInt(amount).toString() : amount;
27711
+ return decimalToInteger(text, 18, "strk").toString();
27672
27712
  }
27673
- return sign2 + strk.replace(/(\.[0-9]*[1-9])0+$|\.0*$/, "$1");
27713
+ return integerToDecimal(amount, 18, "fri");
27714
+ }
27715
+ function parseUnits(value, decimals, tokenName) {
27716
+ checkTokenName(tokenName);
27717
+ const decimalCount = toDecimals(decimals);
27718
+ assert(isString(value), `the ${amountName(tokenName)} must be a string, not ${typeof value}`);
27719
+ return decimalToInteger(value, decimalCount, tokenName);
27720
+ }
27721
+ function formatUnits(value, decimals, tokenName) {
27722
+ checkTokenName(tokenName);
27723
+ const decimalCount = toDecimals(decimals);
27724
+ assert(
27725
+ isNumber2(value) || isBigInt(value) || isString(value),
27726
+ `the ${amountName(tokenName)} must be a number, a bigint or a string, not ${typeof value}`
27727
+ );
27728
+ return integerToDecimal(value, decimalCount, tokenName);
27674
27729
  }
27675
27730
  return __toCommonJS(index_exports);
27676
27731
  })();