starknet 11.9.2 → 11.10.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ # [11.10.0](https://github.com/starknet-io/starknet.js/compare/v11.9.3...v11.10.0) (2026-11-26)
2
+
3
+ ### Features
4
+
5
+ - **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))
6
+
7
+ ## [11.9.3](https://github.com/starknet-io/starknet.js/compare/v11.9.2...v11.9.3) (2026-11-26)
8
+
9
+ ### Bug Fixes
10
+
11
+ - toHex() refuses a negative value instead of returning 0x-5 ([#1767](https://github.com/starknet-io/starknet.js/issues/1767)) ([e2036f1](https://github.com/starknet-io/starknet.js/commit/e2036f13326f140b4cb78aede5d10361a0cff8de))
12
+
1
13
  ## [11.9.2](https://github.com/starknet-io/starknet.js/compare/v11.9.1...v11.9.2) (2026-11-25)
2
14
 
3
15
  ### Bug Fixes
package/dist/index.d.ts CHANGED
@@ -9492,7 +9492,7 @@ declare class RpcProvider implements ProviderInterface {
9492
9492
  getBlock(blockIdentifier: 'pre_confirmed'): Promise<PreConfirmedBlock>;
9493
9493
  getBlock(blockIdentifier: 'latest'): Promise<Block$1>;
9494
9494
  getBlock(blockIdentifier: BlockIdentifier): Promise<GetBlockResponse>;
9495
- getBlockLatestAccepted(): Promise<RPC.BlockHashAndNumber>;
9495
+ getBlockLatestAccepted(): Promise<RPC$1.BlockHashAndNumber>;
9496
9496
  getBlockNumber(): Promise<number>;
9497
9497
  getBlockWithTxHashes(blockIdentifier?: BlockIdentifier): Promise<({
9498
9498
  status: RPC.BLOCK_STATUS;
@@ -9640,7 +9640,7 @@ declare class RpcProvider implements ProviderInterface {
9640
9640
  getTransactionReceipt(txHash: BigNumberish): Promise<GetTransactionReceiptResponse>;
9641
9641
  getTransactionTrace<V extends _SupportedRpcVersion = _SupportedRpcVersion>(txHash: BigNumberish): Promise<V extends SupportedRpcVersion0_10 ? RPCSPEC0105.TRANSACTION_TRACE : RPC.TRANSACTION_TRACE>;
9642
9642
  getTransactionTrace(txHash: BigNumberish): Promise<RPCSPEC0105.TRANSACTION_TRACE | RPC.TRANSACTION_TRACE>;
9643
- getTransactionStatus(transactionHash: BigNumberish): Promise<RPC.TXN_STATUS_RESULT>;
9643
+ getTransactionStatus(transactionHash: BigNumberish): Promise<RPC$1.TXN_STATUS_RESULT>;
9644
9644
  getSimulateTransaction(invocations: AccountInvocations, options?: getSimulateTransactionOptions): Promise<SimulateTransactionOverheadResponse>;
9645
9645
  waitForTransaction(txHash: BigNumberish, options?: waitForTransactionOptions): Promise<GetTransactionReceiptResponse>;
9646
9646
  getStorageAt(contractAddress: BigNumberish, key: BigNumberish, blockIdentifier?: BlockIdentifier, responseFlags?: RPCSPEC0105.STORAGE_RESPONSE_FLAG[]): Promise<STORAGE_RESULT>;
@@ -9770,7 +9770,7 @@ declare class RpcProvider implements ProviderInterface {
9770
9770
  callContract(call: Call, blockIdentifier?: BlockIdentifier): Promise<string[]>;
9771
9771
  estimateMessageFee<V extends _SupportedRpcVersion = _SupportedRpcVersion>(message: RPC.L1Message, blockIdentifier?: BlockIdentifier): Promise<V extends SupportedRpcVersion0_10 ? RPCSPEC0105.FEE_ESTIMATE : RPC.MESSAGE_FEE_ESTIMATE>;
9772
9772
  estimateMessageFee(message: RPC.L1Message, blockIdentifier?: BlockIdentifier): Promise<RPCSPEC0105.FEE_ESTIMATE | RPC.MESSAGE_FEE_ESTIMATE>;
9773
- getSyncingStats(): Promise<RPC.Syncing>;
9773
+ getSyncingStats(): Promise<RPC$1.Syncing>;
9774
9774
  getEvents<V extends _SupportedRpcVersion = _SupportedRpcVersion>(eventFilter: V extends SupportedRpcVersion0_10 ? RPCSPEC0105.EventFilter : RPC.EventFilter): Promise<V extends SupportedRpcVersion0_10 ? RPCSPEC0105.EVENTS_CHUNK : RPC.EVENTS_CHUNK>;
9775
9775
  getEvents(eventFilter: RPCSPEC0105.EventFilter | RPC.EventFilter): Promise<RPCSPEC0105.EVENTS_CHUNK | RPC.EVENTS_CHUNK>;
9776
9776
  verifyMessageInStarknet(message: BigNumberish | TypedData, signature: Signature, accountAddress: BigNumberish, signatureVerificationFunctionName?: string, signatureVerificationResponse?: {
@@ -12283,13 +12283,16 @@ declare function tryToBigInt(value: BigNumberish | undefined): bigint | undefine
12283
12283
  /**
12284
12284
  * Convert BigNumberish to hex-string
12285
12285
  *
12286
+ * A negative value is refused: a hex-string has no sign, and `'0x-5'` is not one.
12286
12287
  * @param {BigNumberish} value value to convert
12287
12288
  * @returns {string} converted number in hex-string format
12289
+ * @throws {Error} when the value is negative, or cannot be read by {@link toBigInt}
12288
12290
  * @example
12289
12291
  * ```typescript
12290
12292
  * toHex(100); // '0x64'
12291
12293
  * toHex('200'); // '0xc8'
12292
12294
  * toHex('0x00023AB'); // '0x23ab'
12295
+ * toHex(-5); // throws Error('Invalid input: -5 is negative, a hex-string cannot hold a sign')
12293
12296
  * ```
12294
12297
  */
12295
12298
  declare function toHex(value: BigNumberish): string;
@@ -18621,6 +18624,7 @@ declare function createTransactionReceipt(receipt: GetTxReceiptResponseWithoutHe
18621
18624
 
18622
18625
  /**
18623
18626
  * Convert strk to fri or fri to strk. Negative amounts are accepted in both directions.
18627
+ * For another token, use `parseUnits` and `formatUnits`.
18624
18628
  * @param {string | bigint} amount amount to convert, in the unit given by `symbol`
18625
18629
  * @param {'fri' | 'strk'} symbol unit of `amount`: 'fri' (default) gives strk, 'strk' gives fri
18626
18630
  * @throws {Error} if a strk amount is not a bigint, a hex string or a decimal string
@@ -18636,6 +18640,54 @@ declare function createTransactionReceipt(receipt: GetTxReceiptResponseWithoutHe
18636
18640
  * ```
18637
18641
  */
18638
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;
18639
18691
 
18640
18692
  /**
18641
18693
  * Request Permission for wallet account, return addresses that are allowed by user
@@ -19117,5 +19169,5 @@ declare class Logger {
19117
19169
  */
19118
19170
  declare const logger: Logger;
19119
19171
 
19120
- 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 };
19121
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,
@@ -3089,17 +3091,21 @@ ${indent}}` : "}";
3089
3091
  return value ? BigInt(value) : void 0;
3090
3092
  }
3091
3093
  function toHex(value) {
3092
- return addHexPrefix(toBigInt(value).toString(16));
3094
+ const bn = toBigInt(value);
3095
+ if (bn < 0n) {
3096
+ throw new Error(`Invalid input: ${bn} is negative, a hex-string cannot hold a sign`);
3097
+ }
3098
+ return addHexPrefix(bn.toString(16));
3093
3099
  }
3094
3100
  var toHexString = toHex;
3095
3101
  function cleanHex(hex) {
3096
3102
  return toHex(hex);
3097
3103
  }
3098
3104
  function toStorageKey(number) {
3099
- return addHexPrefix(toBigInt(number).toString(16).padStart(64, "0"));
3105
+ return addHexPrefix(removeHexPrefix(toHex(number)).padStart(64, "0"));
3100
3106
  }
3101
3107
  function toHex64(number) {
3102
- const res = addHexPrefix(toBigInt(number).toString(16).padStart(64, "0"));
3108
+ const res = addHexPrefix(removeHexPrefix(toHex(number)).padStart(64, "0"));
3103
3109
  if (res.length !== 66) throw TypeError("number is too big for hex 0x(64) representation");
3104
3110
  return res;
3105
3111
  }
@@ -21779,14 +21785,16 @@ ${indent}}` : "}";
21779
21785
  return void 0;
21780
21786
  }
21781
21787
  function getHex(value) {
21788
+ let bn;
21782
21789
  try {
21783
- return toHex(value);
21790
+ bn = toBigInt(value);
21784
21791
  } catch (e) {
21785
21792
  if (isString(value)) {
21786
21793
  return toHex(CairoBytes31.fromText(value).toBigInt());
21787
21794
  }
21788
21795
  throw new Error(`Invalid BigNumberish: ${value}`);
21789
21796
  }
21797
+ return toHex(bn);
21790
21798
  }
21791
21799
  function validateTypedData(data) {
21792
21800
  const typedData = data;
@@ -27635,36 +27643,80 @@ ${indent}}` : "}";
27635
27643
  };
27636
27644
 
27637
27645
  // src/utils/units.ts
27646
+ function amountName(tokenName) {
27647
+ return tokenName ? `${tokenName} amount` : "amount";
27648
+ }
27649
+ function checkTokenName(tokenName) {
27650
+ if (tokenName === void 0) return;
27651
+ assert(isString(tokenName), `the token name must be a string, not ${typeof tokenName}`);
27652
+ assert(tokenName.trim() !== "", "the token name is an empty string");
27653
+ }
27654
+ function toDecimals(decimals) {
27655
+ const shown = isString(decimals) ? `'${decimals}'` : String(decimals);
27656
+ assert(
27657
+ isBigNumberish(decimals) && (!isNumber2(decimals) || Number.isInteger(decimals)),
27658
+ `decimals must be an integer, not ${shown}`
27659
+ );
27660
+ assertInRange(decimals, RANGE_U8.min, RANGE_U8.max, "decimals");
27661
+ return Number(decimals);
27662
+ }
27663
+ function decimalToInteger(text, decimals, tokenName) {
27664
+ const match = /^(-?)(\d*)(?:\.(\d*))?$/.exec(text);
27665
+ assert(
27666
+ match !== null && `${match[2]}${match[3] ?? ""}` !== "",
27667
+ `'${text}' is not a valid ${amountName(tokenName)}`
27668
+ );
27669
+ const [, sign2, integer, fraction = ""] = match;
27670
+ const name = tokenName ? ` ${tokenName}` : "";
27671
+ const unit = decimals === 1 ? "decimal" : "decimals";
27672
+ assert(
27673
+ !/[1-9]/.test(fraction.slice(decimals)),
27674
+ `'${text}'${name} has more than ${decimals} ${unit}`
27675
+ );
27676
+ const result = BigInt(`0${integer}${fraction.slice(0, decimals).padEnd(decimals, "0")}`);
27677
+ return sign2 === "-" ? -result : result;
27678
+ }
27679
+ function integerToDecimal(value, decimals, tokenName) {
27680
+ assert(
27681
+ !isString(value) || value.trim() !== "",
27682
+ `the ${amountName(tokenName)} is an empty string`
27683
+ );
27684
+ const integer = toBigInt(value);
27685
+ const sign2 = integer < 0n ? "-" : "";
27686
+ const digits = (integer < 0n ? -integer : integer).toString();
27687
+ let text;
27688
+ if (digits.length <= decimals) {
27689
+ text = `0.${digits.padStart(decimals, "0")}`;
27690
+ } else {
27691
+ text = `${digits.slice(0, digits.length - decimals)}.${digits.slice(digits.length - decimals)}`;
27692
+ }
27693
+ return sign2 + text.replace(/(\.[0-9]*[1-9])0+$|\.0*$/, "$1");
27694
+ }
27638
27695
  function units(amount, symbol = "fri") {
27639
27696
  if (symbol === "strk") {
27640
- if (!isBigInt(amount) && !isString(amount)) {
27641
- throw new Error(`units: a strk amount must be a string or a bigint, not ${typeof amount}`);
27642
- }
27643
- const numStr = isBigInt(amount) || isHex2(amount) ? toBigInt(amount).toString() : amount;
27644
- const match = /^(-?)(\d*)(?:\.(\d*))?$/.exec(numStr);
27645
- if (!match || `${match[2]}${match[3] ?? ""}` === "") {
27646
- throw new Error(`units: '${numStr}' is not a strk amount`);
27647
- }
27648
- const [, sign3, integer, decimal = ""] = match;
27649
- if (/[1-9]/.test(decimal.slice(18))) {
27650
- throw new Error(`units: '${numStr}' strk has more than 18 decimals`);
27651
- }
27652
- const fri2 = BigInt(`${integer}${decimal.slice(0, 18).padEnd(18, "0")}`);
27653
- return fri2 === 0n ? "0" : `${sign3}${fri2.toString()}`;
27654
- }
27655
- if (isString(amount) && amount.trim() === "") {
27656
- throw new Error("units: the fri amount is an empty string");
27657
- }
27658
- const fri = toBigInt(amount);
27659
- const sign2 = fri < 0n ? "-" : "";
27660
- const bis = (fri < 0n ? -fri : fri).toString();
27661
- let strk;
27662
- if (bis.length <= 18) {
27663
- strk = `0.${bis.padStart(18, "0")}`;
27664
- } else {
27665
- strk = `${bis.slice(0, bis.length - 18)}.${bis.slice(bis.length - 18)}`;
27697
+ assert(
27698
+ isBigInt(amount) || isString(amount),
27699
+ `the strk amount must be a string or a bigint, not ${typeof amount}`
27700
+ );
27701
+ const text = isBigInt(amount) || isHex2(amount) ? toBigInt(amount).toString() : amount;
27702
+ return decimalToInteger(text, 18, "strk").toString();
27666
27703
  }
27667
- return sign2 + strk.replace(/(\.[0-9]*[1-9])0+$|\.0*$/, "$1");
27704
+ return integerToDecimal(amount, 18, "fri");
27705
+ }
27706
+ function parseUnits(value, decimals, tokenName) {
27707
+ checkTokenName(tokenName);
27708
+ const decimalCount = toDecimals(decimals);
27709
+ assert(isString(value), `the ${amountName(tokenName)} must be a string, not ${typeof value}`);
27710
+ return decimalToInteger(value, decimalCount, tokenName);
27711
+ }
27712
+ function formatUnits(value, decimals, tokenName) {
27713
+ checkTokenName(tokenName);
27714
+ const decimalCount = toDecimals(decimals);
27715
+ assert(
27716
+ isNumber2(value) || isBigInt(value) || isString(value),
27717
+ `the ${amountName(tokenName)} must be a number, a bigint or a string, not ${typeof value}`
27718
+ );
27719
+ return integerToDecimal(value, decimalCount, tokenName);
27668
27720
  }
27669
27721
  return __toCommonJS(index_exports);
27670
27722
  })();