@orbinum/sdk 0.16.0 → 0.18.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/dist/index.d.mts CHANGED
@@ -105,6 +105,18 @@ declare class SubstrateClient {
105
105
  private constructor();
106
106
  private _dynamicBuilder;
107
107
  private _extDecoder;
108
+ private _inflightTxCount;
109
+ /**
110
+ * `true` while any submitted transaction is still waiting for finalization.
111
+ * Connection managers use this to defer destroying the client — killing the
112
+ * WS mid-submit rejects the pending tx with "Client destroyed" even though
113
+ * it may still land on-chain.
114
+ *
115
+ * Only covers promise-based submits (`submit`, `submitUnsignedAndWatch`,
116
+ * `signAndSubmit`); observable-based `submitAndWatch` callers are not tracked.
117
+ */
118
+ get hasInflightTx(): boolean;
119
+ private trackTx;
108
120
  /**
109
121
  * Connects to the Orbinum node via WebSocket.
110
122
  * Throws if the node does not respond within `timeoutMs`.
@@ -285,14 +297,25 @@ declare class EvmClient {
285
297
  }): Promise<bigint>;
286
298
  /** Returns a transaction receipt by hash, or `null` if the transaction has not been mined yet. */
287
299
  getTransactionReceipt(txHash: string): Promise<Record<string, unknown> | null>;
300
+ /**
301
+ * Fetches a transaction by hash, or `null` when the node no longer knows it
302
+ * (never mined and evicted from the pool). Unlike `request`, a `null`
303
+ * result is a valid answer here, not an error.
304
+ */
305
+ getTransactionByHash(txHash: string): Promise<Record<string, unknown> | null>;
288
306
  /**
289
307
  * Polls `eth_getTransactionReceipt` until the transaction is included in a block.
290
308
  *
309
+ * After `timeoutMs`, the tx-pool is consulted: a tx no longer known to the
310
+ * node is reported as dropped (safe to retry), while a tx still in the pool
311
+ * gets an extended grace window (up to 4× `timeoutMs`) before a "still
312
+ * pending" error — it may confirm later, so callers must NOT blindly retry.
313
+ *
291
314
  * @param txHash - The transaction hash to wait for.
292
315
  * @param intervalMs - Polling interval in milliseconds (default: 500).
293
316
  * @param timeoutMs - Maximum time to wait in milliseconds (default: 60_000).
294
317
  * @returns The transaction receipt once mined.
295
- * @throws If the transaction is not mined within `timeoutMs` or if it reverted (`status == 0x0`).
318
+ * @throws If the transaction dropped, is still pending after the grace window, or reverted (`status == 0x0`).
296
319
  */
297
320
  waitForReceipt(txHash: string, intervalMs?: number, timeoutMs?: number): Promise<Record<string, unknown>>;
298
321
  }
@@ -1776,6 +1799,7 @@ declare class OrbinumClientProvider {
1776
1799
  private _reconnectTimer;
1777
1800
  private _stableTimer;
1778
1801
  private _reconnectAttempt;
1802
+ private _probeFailures;
1779
1803
  private _listeners;
1780
1804
  /** Creates a new provider with the given configuration. Does not connect automatically — call `connect()` to initiate. */
1781
1805
  constructor(config: ClientProviderConfig);
@@ -1806,6 +1830,21 @@ declare class OrbinumClientProvider {
1806
1830
  * On failure: destroys any orphaned client and transitions to `'disconnected'`.
1807
1831
  */
1808
1832
  private attemptConnect;
1833
+ /**
1834
+ * Consecutive failed probes required before the client is torn down. A
1835
+ * single missed probe is routine (throttled background tab, node busy
1836
+ * verifying a ZK proof, transient network blip) — destroying the client on
1837
+ * it rejects every in-flight request with "Client destroyed" even though
1838
+ * the tx may still land on-chain.
1839
+ */
1840
+ private static readonly PROBE_FAILURE_THRESHOLD;
1841
+ /**
1842
+ * With a tx awaiting finalization, tolerate more missed probes: an unsigned
1843
+ * private_transfer/unshield makes the node CPU-bound on proof verification,
1844
+ * which is exactly when probes time out — tearing down then kills the very
1845
+ * tx being processed.
1846
+ */
1847
+ private static readonly PROBE_FAILURE_THRESHOLD_INFLIGHT;
1809
1848
  /** Starts the periodic heartbeat loop. Replaces any existing timer. */
1810
1849
  private startHeartbeat;
1811
1850
  /** Clears the heartbeat interval timer if active. */
@@ -2104,6 +2143,14 @@ declare function selfEphWindow(spendingKey: bigint, ivkPacked: Uint8Array, from:
2104
2143
  * deriveSpendingKeyFromSignature.
2105
2144
  */
2106
2145
  declare function computeNullifier(commitment: bigint, spendingKey: bigint): bigint;
2146
+ /**
2147
+ * Computes a note commitment.
2148
+ * commitment = Poseidon4(value, assetId, ownerPk, blinding)
2149
+ *
2150
+ * Mirrors NoteCommitment in note.circom — use it to verify a stored note
2151
+ * against its on-chain commitment before spending it.
2152
+ */
2153
+ declare function computeNoteCommitment(value: bigint, assetId: bigint, ownerPk: bigint, blinding: bigint): bigint;
2107
2154
  interface TryDecryptOptions {
2108
2155
  /**
2109
2156
  * View-tag fast path: compute the ECDH shared secret once, compare the
@@ -4261,4 +4308,4 @@ interface ExtrinsicFailedData {
4261
4308
  dispatch_info: DispatchInfo;
4262
4309
  }
4263
4310
 
4264
- export { type AccountListing, type AccountMappedData, type AccountMappedEvent, type AccountMappingCall, type AccountMappingEvent, AccountMappingModule, AccountMappingPrecompile, type AccountMetadata, type AccountUnmappedEvent, type ActiveVersionSetEvent, type AddChainLinkArgs, type AddChainLinkParams, type AddSupportedChainArgs, type AliasFullIdentity, type AliasInfo, type AliasListedForSaleEvent, type AliasOnSaleData, type AliasRegisteredData, type AliasRegisteredEvent, type AliasReleasedEvent, type AliasSaleCancelledEvent, type AliasSoldData, type AliasSoldEvent, type AliasTransferredData, type AliasTransferredEvent, type AssetRegisteredEvent, type AssetUnverifiedEvent, type AssetVerifiedEvent, BABYJUB_SUBORDER, BN254_R, type BatchRegisterVerificationKeysArgs, type BatchVerificationKeysRegisteredEvent, type BlockInfo, type BuyAliasArgs, type Bytes32, CURRENT_CIRCUIT_VERSION, type ChainInfo, type ChainLink, type ChainLinkAddedEvent, type ChainLinkRemovedEvent, CircuitId, CircuitId as CircuitIdType, CircuitVersionResolver, type ClaimShieldedFeesParams, type ClientProviderConfig, type CommitmentsInsertedEvent, type CommitmentsInsertedEventData, type ConnectionStatus, CryptoPrecompiles, type DecodedAddChainLinkArgs, type DecodedBatchArgs, type DecodedDispatchAsPrivateLinkArgs, type DecodedEthereumTransactArgs, type DecodedEvmCallArgs, type DecodedPrecompile, type DecodedPrivateTransferArgs, type DecodedPutAliasForSaleArgs, type DecodedRegisterAliasArgs, type DecodedRemarkArgs, type DecodedRevealPrivateLinkArgs, type DecodedSetAccountMetadataArgs, type DecodedShieldArgs, type DecodedShieldBatchArgs, type DecodedShieldBatchOperation, type DecodedSudoArgs, type DecodedTransferAllArgs, type DecodedTransferArgs, type DecodedTransferKeepAliveArgs, type DecodedUnshieldArgs, type DecryptedMemo, type DispatchAsLinkedAccountArgs, type DispatchAsLinkedParams, type DispatchAsPrivateLinkArgs, type DispatchError, type DispatchInfo, type DynamicBuilder, ENCRYPTED_MEMO_SIZE, EncryptedMemo, type EncryptedNoteRecord, type EndowedEventData, type EthereumExecutedData, type EventData, type EventPhase, type EventRecord, type EvmAddressInfo, type EvmBlock, EvmClient, type EvmExecutedData, type EvmExitReason, EvmExplorer, type EvmLog, type EvmSigner, type EvmTransaction, type EvmTxRequest, type EvmTxSummary, type ExtrinsicDecoder, type ExtrinsicFailedData, type ExtrinsicSuccessData, type FeeClaimProofInputs, type FormatOptions, KNOWN_PRECOMPILES, type KnownPrecompileInfo, type ListingInfo, type MerkleRootUpdatedData, type MerkleRootUpdatedEvent, type MerkleTreeInfo, type MetadataUpdatedEvent, NoteBuilder, type NoteDisclosure, type NoteInput, type NoteStatusUpdate, type NullifiersSpentEvent, type NullifiersSpentEventData, OrbinumClient, type OrbinumClientConfig, OrbinumClientProvider, PRECOMPILE_ADDR, PrivacyKeyManager, type PrivacyMerkleProof, PrivacyModule, type PrivateChainLinkAddedEvent, type PrivateChainLinkRemovedEvent, type PrivateChainLinkRevealedEvent, type PrivateLink, type PrivateLinkDispatchExecutedEvent, type PrivateTransferArgs, type PrivateTransferInput, type PrivateTransferOutput, type PrivateTransferParams, type PrivateTransferProofInputs, type ProofVerificationFailedEvent, type ProofVerifiedEvent, type ProxyCallExecutedEvent, type PutAliasOnSaleArgs, type PutOnSaleParams, type RawBlock, type RawBlockHeader, type RawTransferInput, type RawTransferOutput, type RegisterAliasArgs, type RegisterAssetArgs, type RegisterPrivateLinkArgs, type RegisterVerificationKeyArgs, type RelayerInfo, RelayerStatusModule, type RemoveChainLinkArgs, type RemovePrivateLinkArgs, type RemoveSupportedChainArgs, type RemoveVerificationKeyArgs, type ReservedEventData, type ResolvedAlias, type ResolvedSpendVersion, type RevealPrivateLinkArgs, type RpcV2MerkleProof, type RpcV2NullifierStatus, type RpcV2PoolAssetBalance, type RpcV2PoolStats, SLIP0044_NAMESPACE, type ScanCommitment, type SelfEphWindowEntry, type SetAccountMetadataArgs, type SetActiveVersionArgs, type SetMetadataParams, type ShieldArgs, type ShieldBatchArgs, type ShieldBatchItem, type ShieldBatchParams, type ShieldOperation, type ShieldParams, type ShieldedEvent, type ShieldedEventData, type ShieldedPoolCall, type ShieldedPoolEvent, ShieldedPoolModule, ShieldedPoolPrecompile, SignatureScheme, type StatusChangeEvent, type StatusListener, SubstrateClient, type SupportedChain, type SupportedChainAddedEvent, type SupportedChainRemovedEvent, type SystemHealth, type TokenInfo, type TokenTransfer, type TransferAliasArgs, type TransferEventData, type TransferInputNote, type TransferOutputNote, type TryDecryptOptions, type TxResult, type UnsafeTxOptions, type UnshieldArgs, type UnshieldParams, type UnshieldProofInputs, type UnshieldedEvent, type UnshieldedEventData, type UnverifyAssetArgs, VaultLockedError, type VerificationKeyRegisteredEvent, type VerificationKeyRemovedEvent, type VerifyAssetArgs, type VerifyProofArgs, type VkEntry, type ZkNote, type ZkVerifierCall, type ZkVerifierCircuitVersionInfo, type ZkVerifierEvent, type ZkVerifierHistoricalVersion, ZkVerifierModule, type ZkVerifierVersionStats, type ZkVerifierVkHash, accountIdHexToSs58, addressToAccountIdHex, applyNoteStatus, bigintTo32Be, bigintTo32Le, bigintTo32LeArr, blindTag, buildDummyTransferInput, bytesToBigintLE, computeNullifier, computePathIndices, createNoteDisclosureKey, decodeNoteDisclosureKey, decodePrecompileCalldata, decryptJson, decryptNoteRecord, deriveMasterKeyBytes, deriveOwnerPk, deriveSelfEphSk, deriveSpendingKeyFromSignature, deriveSpendingKeyMessage, deriveStealthOwnerPk, deriveStealthSk, deriveVaultBlindKey, deriveVaultKey, deriveViewTag, deriveViewingPublicKey, deriveViewingSecretKey, encryptJson, encryptNote, ensureHexPrefix, evmAddressToAccountId, evmToImplicitSubstrate, evmToMappedAccountHex, evmToSubstrate, formatBalance, formatORB, fromBase64, fromHex, generateFeeClaimProof, generateTransferProof, generateUnshieldProof, getPrecompileLabel, hexToBigint, hexToNumber, implicitSubstrateToEvm, isEvmAddress, isImplicitEvmAccount, isSs58, isSubstrateAddress, isUnifiedAddress, leHexToBigint, mapExtrinsicArgs, mapZkEventData, normalizeEvmAddress, noteBlindTag, randomBlinding, recoverOwnerPkPoint, selectNotes, selfEphWindow, shortHash, substrateSs58ToAccountIdHex, substrateToEvm, toBase64, toHex, toTxResult, truncateMiddle, tryDecryptNote, tryDecryptNoteVerbose, vaultReplacer, vaultReviver };
4311
+ export { type AccountListing, type AccountMappedData, type AccountMappedEvent, type AccountMappingCall, type AccountMappingEvent, AccountMappingModule, AccountMappingPrecompile, type AccountMetadata, type AccountUnmappedEvent, type ActiveVersionSetEvent, type AddChainLinkArgs, type AddChainLinkParams, type AddSupportedChainArgs, type AliasFullIdentity, type AliasInfo, type AliasListedForSaleEvent, type AliasOnSaleData, type AliasRegisteredData, type AliasRegisteredEvent, type AliasReleasedEvent, type AliasSaleCancelledEvent, type AliasSoldData, type AliasSoldEvent, type AliasTransferredData, type AliasTransferredEvent, type AssetRegisteredEvent, type AssetUnverifiedEvent, type AssetVerifiedEvent, BABYJUB_SUBORDER, BN254_R, type BatchRegisterVerificationKeysArgs, type BatchVerificationKeysRegisteredEvent, type BlockInfo, type BuyAliasArgs, type Bytes32, CURRENT_CIRCUIT_VERSION, type ChainInfo, type ChainLink, type ChainLinkAddedEvent, type ChainLinkRemovedEvent, CircuitId, CircuitId as CircuitIdType, CircuitVersionResolver, type ClaimShieldedFeesParams, type ClientProviderConfig, type CommitmentsInsertedEvent, type CommitmentsInsertedEventData, type ConnectionStatus, CryptoPrecompiles, type DecodedAddChainLinkArgs, type DecodedBatchArgs, type DecodedDispatchAsPrivateLinkArgs, type DecodedEthereumTransactArgs, type DecodedEvmCallArgs, type DecodedPrecompile, type DecodedPrivateTransferArgs, type DecodedPutAliasForSaleArgs, type DecodedRegisterAliasArgs, type DecodedRemarkArgs, type DecodedRevealPrivateLinkArgs, type DecodedSetAccountMetadataArgs, type DecodedShieldArgs, type DecodedShieldBatchArgs, type DecodedShieldBatchOperation, type DecodedSudoArgs, type DecodedTransferAllArgs, type DecodedTransferArgs, type DecodedTransferKeepAliveArgs, type DecodedUnshieldArgs, type DecryptedMemo, type DispatchAsLinkedAccountArgs, type DispatchAsLinkedParams, type DispatchAsPrivateLinkArgs, type DispatchError, type DispatchInfo, type DynamicBuilder, ENCRYPTED_MEMO_SIZE, EncryptedMemo, type EncryptedNoteRecord, type EndowedEventData, type EthereumExecutedData, type EventData, type EventPhase, type EventRecord, type EvmAddressInfo, type EvmBlock, EvmClient, type EvmExecutedData, type EvmExitReason, EvmExplorer, type EvmLog, type EvmSigner, type EvmTransaction, type EvmTxRequest, type EvmTxSummary, type ExtrinsicDecoder, type ExtrinsicFailedData, type ExtrinsicSuccessData, type FeeClaimProofInputs, type FormatOptions, KNOWN_PRECOMPILES, type KnownPrecompileInfo, type ListingInfo, type MerkleRootUpdatedData, type MerkleRootUpdatedEvent, type MerkleTreeInfo, type MetadataUpdatedEvent, NoteBuilder, type NoteDisclosure, type NoteInput, type NoteStatusUpdate, type NullifiersSpentEvent, type NullifiersSpentEventData, OrbinumClient, type OrbinumClientConfig, OrbinumClientProvider, PRECOMPILE_ADDR, PrivacyKeyManager, type PrivacyMerkleProof, PrivacyModule, type PrivateChainLinkAddedEvent, type PrivateChainLinkRemovedEvent, type PrivateChainLinkRevealedEvent, type PrivateLink, type PrivateLinkDispatchExecutedEvent, type PrivateTransferArgs, type PrivateTransferInput, type PrivateTransferOutput, type PrivateTransferParams, type PrivateTransferProofInputs, type ProofVerificationFailedEvent, type ProofVerifiedEvent, type ProxyCallExecutedEvent, type PutAliasOnSaleArgs, type PutOnSaleParams, type RawBlock, type RawBlockHeader, type RawTransferInput, type RawTransferOutput, type RegisterAliasArgs, type RegisterAssetArgs, type RegisterPrivateLinkArgs, type RegisterVerificationKeyArgs, type RelayerInfo, RelayerStatusModule, type RemoveChainLinkArgs, type RemovePrivateLinkArgs, type RemoveSupportedChainArgs, type RemoveVerificationKeyArgs, type ReservedEventData, type ResolvedAlias, type ResolvedSpendVersion, type RevealPrivateLinkArgs, type RpcV2MerkleProof, type RpcV2NullifierStatus, type RpcV2PoolAssetBalance, type RpcV2PoolStats, SLIP0044_NAMESPACE, type ScanCommitment, type SelfEphWindowEntry, type SetAccountMetadataArgs, type SetActiveVersionArgs, type SetMetadataParams, type ShieldArgs, type ShieldBatchArgs, type ShieldBatchItem, type ShieldBatchParams, type ShieldOperation, type ShieldParams, type ShieldedEvent, type ShieldedEventData, type ShieldedPoolCall, type ShieldedPoolEvent, ShieldedPoolModule, ShieldedPoolPrecompile, SignatureScheme, type StatusChangeEvent, type StatusListener, SubstrateClient, type SupportedChain, type SupportedChainAddedEvent, type SupportedChainRemovedEvent, type SystemHealth, type TokenInfo, type TokenTransfer, type TransferAliasArgs, type TransferEventData, type TransferInputNote, type TransferOutputNote, type TryDecryptOptions, type TxResult, type UnsafeTxOptions, type UnshieldArgs, type UnshieldParams, type UnshieldProofInputs, type UnshieldedEvent, type UnshieldedEventData, type UnverifyAssetArgs, VaultLockedError, type VerificationKeyRegisteredEvent, type VerificationKeyRemovedEvent, type VerifyAssetArgs, type VerifyProofArgs, type VkEntry, type ZkNote, type ZkVerifierCall, type ZkVerifierCircuitVersionInfo, type ZkVerifierEvent, type ZkVerifierHistoricalVersion, ZkVerifierModule, type ZkVerifierVersionStats, type ZkVerifierVkHash, accountIdHexToSs58, addressToAccountIdHex, applyNoteStatus, bigintTo32Be, bigintTo32Le, bigintTo32LeArr, blindTag, buildDummyTransferInput, bytesToBigintLE, computeNoteCommitment, computeNullifier, computePathIndices, createNoteDisclosureKey, decodeNoteDisclosureKey, decodePrecompileCalldata, decryptJson, decryptNoteRecord, deriveMasterKeyBytes, deriveOwnerPk, deriveSelfEphSk, deriveSpendingKeyFromSignature, deriveSpendingKeyMessage, deriveStealthOwnerPk, deriveStealthSk, deriveVaultBlindKey, deriveVaultKey, deriveViewTag, deriveViewingPublicKey, deriveViewingSecretKey, encryptJson, encryptNote, ensureHexPrefix, evmAddressToAccountId, evmToImplicitSubstrate, evmToMappedAccountHex, evmToSubstrate, formatBalance, formatORB, fromBase64, fromHex, generateFeeClaimProof, generateTransferProof, generateUnshieldProof, getPrecompileLabel, hexToBigint, hexToNumber, implicitSubstrateToEvm, isEvmAddress, isImplicitEvmAccount, isSs58, isSubstrateAddress, isUnifiedAddress, leHexToBigint, mapExtrinsicArgs, mapZkEventData, normalizeEvmAddress, noteBlindTag, randomBlinding, recoverOwnerPkPoint, selectNotes, selfEphWindow, shortHash, substrateSs58ToAccountIdHex, substrateToEvm, toBase64, toHex, toTxResult, truncateMiddle, tryDecryptNote, tryDecryptNoteVerbose, vaultReplacer, vaultReviver };
package/dist/index.d.ts CHANGED
@@ -105,6 +105,18 @@ declare class SubstrateClient {
105
105
  private constructor();
106
106
  private _dynamicBuilder;
107
107
  private _extDecoder;
108
+ private _inflightTxCount;
109
+ /**
110
+ * `true` while any submitted transaction is still waiting for finalization.
111
+ * Connection managers use this to defer destroying the client — killing the
112
+ * WS mid-submit rejects the pending tx with "Client destroyed" even though
113
+ * it may still land on-chain.
114
+ *
115
+ * Only covers promise-based submits (`submit`, `submitUnsignedAndWatch`,
116
+ * `signAndSubmit`); observable-based `submitAndWatch` callers are not tracked.
117
+ */
118
+ get hasInflightTx(): boolean;
119
+ private trackTx;
108
120
  /**
109
121
  * Connects to the Orbinum node via WebSocket.
110
122
  * Throws if the node does not respond within `timeoutMs`.
@@ -285,14 +297,25 @@ declare class EvmClient {
285
297
  }): Promise<bigint>;
286
298
  /** Returns a transaction receipt by hash, or `null` if the transaction has not been mined yet. */
287
299
  getTransactionReceipt(txHash: string): Promise<Record<string, unknown> | null>;
300
+ /**
301
+ * Fetches a transaction by hash, or `null` when the node no longer knows it
302
+ * (never mined and evicted from the pool). Unlike `request`, a `null`
303
+ * result is a valid answer here, not an error.
304
+ */
305
+ getTransactionByHash(txHash: string): Promise<Record<string, unknown> | null>;
288
306
  /**
289
307
  * Polls `eth_getTransactionReceipt` until the transaction is included in a block.
290
308
  *
309
+ * After `timeoutMs`, the tx-pool is consulted: a tx no longer known to the
310
+ * node is reported as dropped (safe to retry), while a tx still in the pool
311
+ * gets an extended grace window (up to 4× `timeoutMs`) before a "still
312
+ * pending" error — it may confirm later, so callers must NOT blindly retry.
313
+ *
291
314
  * @param txHash - The transaction hash to wait for.
292
315
  * @param intervalMs - Polling interval in milliseconds (default: 500).
293
316
  * @param timeoutMs - Maximum time to wait in milliseconds (default: 60_000).
294
317
  * @returns The transaction receipt once mined.
295
- * @throws If the transaction is not mined within `timeoutMs` or if it reverted (`status == 0x0`).
318
+ * @throws If the transaction dropped, is still pending after the grace window, or reverted (`status == 0x0`).
296
319
  */
297
320
  waitForReceipt(txHash: string, intervalMs?: number, timeoutMs?: number): Promise<Record<string, unknown>>;
298
321
  }
@@ -1776,6 +1799,7 @@ declare class OrbinumClientProvider {
1776
1799
  private _reconnectTimer;
1777
1800
  private _stableTimer;
1778
1801
  private _reconnectAttempt;
1802
+ private _probeFailures;
1779
1803
  private _listeners;
1780
1804
  /** Creates a new provider with the given configuration. Does not connect automatically — call `connect()` to initiate. */
1781
1805
  constructor(config: ClientProviderConfig);
@@ -1806,6 +1830,21 @@ declare class OrbinumClientProvider {
1806
1830
  * On failure: destroys any orphaned client and transitions to `'disconnected'`.
1807
1831
  */
1808
1832
  private attemptConnect;
1833
+ /**
1834
+ * Consecutive failed probes required before the client is torn down. A
1835
+ * single missed probe is routine (throttled background tab, node busy
1836
+ * verifying a ZK proof, transient network blip) — destroying the client on
1837
+ * it rejects every in-flight request with "Client destroyed" even though
1838
+ * the tx may still land on-chain.
1839
+ */
1840
+ private static readonly PROBE_FAILURE_THRESHOLD;
1841
+ /**
1842
+ * With a tx awaiting finalization, tolerate more missed probes: an unsigned
1843
+ * private_transfer/unshield makes the node CPU-bound on proof verification,
1844
+ * which is exactly when probes time out — tearing down then kills the very
1845
+ * tx being processed.
1846
+ */
1847
+ private static readonly PROBE_FAILURE_THRESHOLD_INFLIGHT;
1809
1848
  /** Starts the periodic heartbeat loop. Replaces any existing timer. */
1810
1849
  private startHeartbeat;
1811
1850
  /** Clears the heartbeat interval timer if active. */
@@ -2104,6 +2143,14 @@ declare function selfEphWindow(spendingKey: bigint, ivkPacked: Uint8Array, from:
2104
2143
  * deriveSpendingKeyFromSignature.
2105
2144
  */
2106
2145
  declare function computeNullifier(commitment: bigint, spendingKey: bigint): bigint;
2146
+ /**
2147
+ * Computes a note commitment.
2148
+ * commitment = Poseidon4(value, assetId, ownerPk, blinding)
2149
+ *
2150
+ * Mirrors NoteCommitment in note.circom — use it to verify a stored note
2151
+ * against its on-chain commitment before spending it.
2152
+ */
2153
+ declare function computeNoteCommitment(value: bigint, assetId: bigint, ownerPk: bigint, blinding: bigint): bigint;
2107
2154
  interface TryDecryptOptions {
2108
2155
  /**
2109
2156
  * View-tag fast path: compute the ECDH shared secret once, compare the
@@ -4261,4 +4308,4 @@ interface ExtrinsicFailedData {
4261
4308
  dispatch_info: DispatchInfo;
4262
4309
  }
4263
4310
 
4264
- export { type AccountListing, type AccountMappedData, type AccountMappedEvent, type AccountMappingCall, type AccountMappingEvent, AccountMappingModule, AccountMappingPrecompile, type AccountMetadata, type AccountUnmappedEvent, type ActiveVersionSetEvent, type AddChainLinkArgs, type AddChainLinkParams, type AddSupportedChainArgs, type AliasFullIdentity, type AliasInfo, type AliasListedForSaleEvent, type AliasOnSaleData, type AliasRegisteredData, type AliasRegisteredEvent, type AliasReleasedEvent, type AliasSaleCancelledEvent, type AliasSoldData, type AliasSoldEvent, type AliasTransferredData, type AliasTransferredEvent, type AssetRegisteredEvent, type AssetUnverifiedEvent, type AssetVerifiedEvent, BABYJUB_SUBORDER, BN254_R, type BatchRegisterVerificationKeysArgs, type BatchVerificationKeysRegisteredEvent, type BlockInfo, type BuyAliasArgs, type Bytes32, CURRENT_CIRCUIT_VERSION, type ChainInfo, type ChainLink, type ChainLinkAddedEvent, type ChainLinkRemovedEvent, CircuitId, CircuitId as CircuitIdType, CircuitVersionResolver, type ClaimShieldedFeesParams, type ClientProviderConfig, type CommitmentsInsertedEvent, type CommitmentsInsertedEventData, type ConnectionStatus, CryptoPrecompiles, type DecodedAddChainLinkArgs, type DecodedBatchArgs, type DecodedDispatchAsPrivateLinkArgs, type DecodedEthereumTransactArgs, type DecodedEvmCallArgs, type DecodedPrecompile, type DecodedPrivateTransferArgs, type DecodedPutAliasForSaleArgs, type DecodedRegisterAliasArgs, type DecodedRemarkArgs, type DecodedRevealPrivateLinkArgs, type DecodedSetAccountMetadataArgs, type DecodedShieldArgs, type DecodedShieldBatchArgs, type DecodedShieldBatchOperation, type DecodedSudoArgs, type DecodedTransferAllArgs, type DecodedTransferArgs, type DecodedTransferKeepAliveArgs, type DecodedUnshieldArgs, type DecryptedMemo, type DispatchAsLinkedAccountArgs, type DispatchAsLinkedParams, type DispatchAsPrivateLinkArgs, type DispatchError, type DispatchInfo, type DynamicBuilder, ENCRYPTED_MEMO_SIZE, EncryptedMemo, type EncryptedNoteRecord, type EndowedEventData, type EthereumExecutedData, type EventData, type EventPhase, type EventRecord, type EvmAddressInfo, type EvmBlock, EvmClient, type EvmExecutedData, type EvmExitReason, EvmExplorer, type EvmLog, type EvmSigner, type EvmTransaction, type EvmTxRequest, type EvmTxSummary, type ExtrinsicDecoder, type ExtrinsicFailedData, type ExtrinsicSuccessData, type FeeClaimProofInputs, type FormatOptions, KNOWN_PRECOMPILES, type KnownPrecompileInfo, type ListingInfo, type MerkleRootUpdatedData, type MerkleRootUpdatedEvent, type MerkleTreeInfo, type MetadataUpdatedEvent, NoteBuilder, type NoteDisclosure, type NoteInput, type NoteStatusUpdate, type NullifiersSpentEvent, type NullifiersSpentEventData, OrbinumClient, type OrbinumClientConfig, OrbinumClientProvider, PRECOMPILE_ADDR, PrivacyKeyManager, type PrivacyMerkleProof, PrivacyModule, type PrivateChainLinkAddedEvent, type PrivateChainLinkRemovedEvent, type PrivateChainLinkRevealedEvent, type PrivateLink, type PrivateLinkDispatchExecutedEvent, type PrivateTransferArgs, type PrivateTransferInput, type PrivateTransferOutput, type PrivateTransferParams, type PrivateTransferProofInputs, type ProofVerificationFailedEvent, type ProofVerifiedEvent, type ProxyCallExecutedEvent, type PutAliasOnSaleArgs, type PutOnSaleParams, type RawBlock, type RawBlockHeader, type RawTransferInput, type RawTransferOutput, type RegisterAliasArgs, type RegisterAssetArgs, type RegisterPrivateLinkArgs, type RegisterVerificationKeyArgs, type RelayerInfo, RelayerStatusModule, type RemoveChainLinkArgs, type RemovePrivateLinkArgs, type RemoveSupportedChainArgs, type RemoveVerificationKeyArgs, type ReservedEventData, type ResolvedAlias, type ResolvedSpendVersion, type RevealPrivateLinkArgs, type RpcV2MerkleProof, type RpcV2NullifierStatus, type RpcV2PoolAssetBalance, type RpcV2PoolStats, SLIP0044_NAMESPACE, type ScanCommitment, type SelfEphWindowEntry, type SetAccountMetadataArgs, type SetActiveVersionArgs, type SetMetadataParams, type ShieldArgs, type ShieldBatchArgs, type ShieldBatchItem, type ShieldBatchParams, type ShieldOperation, type ShieldParams, type ShieldedEvent, type ShieldedEventData, type ShieldedPoolCall, type ShieldedPoolEvent, ShieldedPoolModule, ShieldedPoolPrecompile, SignatureScheme, type StatusChangeEvent, type StatusListener, SubstrateClient, type SupportedChain, type SupportedChainAddedEvent, type SupportedChainRemovedEvent, type SystemHealth, type TokenInfo, type TokenTransfer, type TransferAliasArgs, type TransferEventData, type TransferInputNote, type TransferOutputNote, type TryDecryptOptions, type TxResult, type UnsafeTxOptions, type UnshieldArgs, type UnshieldParams, type UnshieldProofInputs, type UnshieldedEvent, type UnshieldedEventData, type UnverifyAssetArgs, VaultLockedError, type VerificationKeyRegisteredEvent, type VerificationKeyRemovedEvent, type VerifyAssetArgs, type VerifyProofArgs, type VkEntry, type ZkNote, type ZkVerifierCall, type ZkVerifierCircuitVersionInfo, type ZkVerifierEvent, type ZkVerifierHistoricalVersion, ZkVerifierModule, type ZkVerifierVersionStats, type ZkVerifierVkHash, accountIdHexToSs58, addressToAccountIdHex, applyNoteStatus, bigintTo32Be, bigintTo32Le, bigintTo32LeArr, blindTag, buildDummyTransferInput, bytesToBigintLE, computeNullifier, computePathIndices, createNoteDisclosureKey, decodeNoteDisclosureKey, decodePrecompileCalldata, decryptJson, decryptNoteRecord, deriveMasterKeyBytes, deriveOwnerPk, deriveSelfEphSk, deriveSpendingKeyFromSignature, deriveSpendingKeyMessage, deriveStealthOwnerPk, deriveStealthSk, deriveVaultBlindKey, deriveVaultKey, deriveViewTag, deriveViewingPublicKey, deriveViewingSecretKey, encryptJson, encryptNote, ensureHexPrefix, evmAddressToAccountId, evmToImplicitSubstrate, evmToMappedAccountHex, evmToSubstrate, formatBalance, formatORB, fromBase64, fromHex, generateFeeClaimProof, generateTransferProof, generateUnshieldProof, getPrecompileLabel, hexToBigint, hexToNumber, implicitSubstrateToEvm, isEvmAddress, isImplicitEvmAccount, isSs58, isSubstrateAddress, isUnifiedAddress, leHexToBigint, mapExtrinsicArgs, mapZkEventData, normalizeEvmAddress, noteBlindTag, randomBlinding, recoverOwnerPkPoint, selectNotes, selfEphWindow, shortHash, substrateSs58ToAccountIdHex, substrateToEvm, toBase64, toHex, toTxResult, truncateMiddle, tryDecryptNote, tryDecryptNoteVerbose, vaultReplacer, vaultReviver };
4311
+ export { type AccountListing, type AccountMappedData, type AccountMappedEvent, type AccountMappingCall, type AccountMappingEvent, AccountMappingModule, AccountMappingPrecompile, type AccountMetadata, type AccountUnmappedEvent, type ActiveVersionSetEvent, type AddChainLinkArgs, type AddChainLinkParams, type AddSupportedChainArgs, type AliasFullIdentity, type AliasInfo, type AliasListedForSaleEvent, type AliasOnSaleData, type AliasRegisteredData, type AliasRegisteredEvent, type AliasReleasedEvent, type AliasSaleCancelledEvent, type AliasSoldData, type AliasSoldEvent, type AliasTransferredData, type AliasTransferredEvent, type AssetRegisteredEvent, type AssetUnverifiedEvent, type AssetVerifiedEvent, BABYJUB_SUBORDER, BN254_R, type BatchRegisterVerificationKeysArgs, type BatchVerificationKeysRegisteredEvent, type BlockInfo, type BuyAliasArgs, type Bytes32, CURRENT_CIRCUIT_VERSION, type ChainInfo, type ChainLink, type ChainLinkAddedEvent, type ChainLinkRemovedEvent, CircuitId, CircuitId as CircuitIdType, CircuitVersionResolver, type ClaimShieldedFeesParams, type ClientProviderConfig, type CommitmentsInsertedEvent, type CommitmentsInsertedEventData, type ConnectionStatus, CryptoPrecompiles, type DecodedAddChainLinkArgs, type DecodedBatchArgs, type DecodedDispatchAsPrivateLinkArgs, type DecodedEthereumTransactArgs, type DecodedEvmCallArgs, type DecodedPrecompile, type DecodedPrivateTransferArgs, type DecodedPutAliasForSaleArgs, type DecodedRegisterAliasArgs, type DecodedRemarkArgs, type DecodedRevealPrivateLinkArgs, type DecodedSetAccountMetadataArgs, type DecodedShieldArgs, type DecodedShieldBatchArgs, type DecodedShieldBatchOperation, type DecodedSudoArgs, type DecodedTransferAllArgs, type DecodedTransferArgs, type DecodedTransferKeepAliveArgs, type DecodedUnshieldArgs, type DecryptedMemo, type DispatchAsLinkedAccountArgs, type DispatchAsLinkedParams, type DispatchAsPrivateLinkArgs, type DispatchError, type DispatchInfo, type DynamicBuilder, ENCRYPTED_MEMO_SIZE, EncryptedMemo, type EncryptedNoteRecord, type EndowedEventData, type EthereumExecutedData, type EventData, type EventPhase, type EventRecord, type EvmAddressInfo, type EvmBlock, EvmClient, type EvmExecutedData, type EvmExitReason, EvmExplorer, type EvmLog, type EvmSigner, type EvmTransaction, type EvmTxRequest, type EvmTxSummary, type ExtrinsicDecoder, type ExtrinsicFailedData, type ExtrinsicSuccessData, type FeeClaimProofInputs, type FormatOptions, KNOWN_PRECOMPILES, type KnownPrecompileInfo, type ListingInfo, type MerkleRootUpdatedData, type MerkleRootUpdatedEvent, type MerkleTreeInfo, type MetadataUpdatedEvent, NoteBuilder, type NoteDisclosure, type NoteInput, type NoteStatusUpdate, type NullifiersSpentEvent, type NullifiersSpentEventData, OrbinumClient, type OrbinumClientConfig, OrbinumClientProvider, PRECOMPILE_ADDR, PrivacyKeyManager, type PrivacyMerkleProof, PrivacyModule, type PrivateChainLinkAddedEvent, type PrivateChainLinkRemovedEvent, type PrivateChainLinkRevealedEvent, type PrivateLink, type PrivateLinkDispatchExecutedEvent, type PrivateTransferArgs, type PrivateTransferInput, type PrivateTransferOutput, type PrivateTransferParams, type PrivateTransferProofInputs, type ProofVerificationFailedEvent, type ProofVerifiedEvent, type ProxyCallExecutedEvent, type PutAliasOnSaleArgs, type PutOnSaleParams, type RawBlock, type RawBlockHeader, type RawTransferInput, type RawTransferOutput, type RegisterAliasArgs, type RegisterAssetArgs, type RegisterPrivateLinkArgs, type RegisterVerificationKeyArgs, type RelayerInfo, RelayerStatusModule, type RemoveChainLinkArgs, type RemovePrivateLinkArgs, type RemoveSupportedChainArgs, type RemoveVerificationKeyArgs, type ReservedEventData, type ResolvedAlias, type ResolvedSpendVersion, type RevealPrivateLinkArgs, type RpcV2MerkleProof, type RpcV2NullifierStatus, type RpcV2PoolAssetBalance, type RpcV2PoolStats, SLIP0044_NAMESPACE, type ScanCommitment, type SelfEphWindowEntry, type SetAccountMetadataArgs, type SetActiveVersionArgs, type SetMetadataParams, type ShieldArgs, type ShieldBatchArgs, type ShieldBatchItem, type ShieldBatchParams, type ShieldOperation, type ShieldParams, type ShieldedEvent, type ShieldedEventData, type ShieldedPoolCall, type ShieldedPoolEvent, ShieldedPoolModule, ShieldedPoolPrecompile, SignatureScheme, type StatusChangeEvent, type StatusListener, SubstrateClient, type SupportedChain, type SupportedChainAddedEvent, type SupportedChainRemovedEvent, type SystemHealth, type TokenInfo, type TokenTransfer, type TransferAliasArgs, type TransferEventData, type TransferInputNote, type TransferOutputNote, type TryDecryptOptions, type TxResult, type UnsafeTxOptions, type UnshieldArgs, type UnshieldParams, type UnshieldProofInputs, type UnshieldedEvent, type UnshieldedEventData, type UnverifyAssetArgs, VaultLockedError, type VerificationKeyRegisteredEvent, type VerificationKeyRemovedEvent, type VerifyAssetArgs, type VerifyProofArgs, type VkEntry, type ZkNote, type ZkVerifierCall, type ZkVerifierCircuitVersionInfo, type ZkVerifierEvent, type ZkVerifierHistoricalVersion, ZkVerifierModule, type ZkVerifierVersionStats, type ZkVerifierVkHash, accountIdHexToSs58, addressToAccountIdHex, applyNoteStatus, bigintTo32Be, bigintTo32Le, bigintTo32LeArr, blindTag, buildDummyTransferInput, bytesToBigintLE, computeNoteCommitment, computeNullifier, computePathIndices, createNoteDisclosureKey, decodeNoteDisclosureKey, decodePrecompileCalldata, decryptJson, decryptNoteRecord, deriveMasterKeyBytes, deriveOwnerPk, deriveSelfEphSk, deriveSpendingKeyFromSignature, deriveSpendingKeyMessage, deriveStealthOwnerPk, deriveStealthSk, deriveVaultBlindKey, deriveVaultKey, deriveViewTag, deriveViewingPublicKey, deriveViewingSecretKey, encryptJson, encryptNote, ensureHexPrefix, evmAddressToAccountId, evmToImplicitSubstrate, evmToMappedAccountHex, evmToSubstrate, formatBalance, formatORB, fromBase64, fromHex, generateFeeClaimProof, generateTransferProof, generateUnshieldProof, getPrecompileLabel, hexToBigint, hexToNumber, implicitSubstrateToEvm, isEvmAddress, isImplicitEvmAccount, isSs58, isSubstrateAddress, isUnifiedAddress, leHexToBigint, mapExtrinsicArgs, mapZkEventData, normalizeEvmAddress, noteBlindTag, randomBlinding, recoverOwnerPkPoint, selectNotes, selfEphWindow, shortHash, substrateSs58ToAccountIdHex, substrateToEvm, toBase64, toHex, toTxResult, truncateMiddle, tryDecryptNote, tryDecryptNoteVerbose, vaultReplacer, vaultReviver };
package/dist/index.js CHANGED
@@ -63,6 +63,7 @@ __export(index_exports, {
63
63
  blindTag: () => blindTag,
64
64
  buildDummyTransferInput: () => buildDummyTransferInput,
65
65
  bytesToBigintLE: () => bytesToBigintLE,
66
+ computeNoteCommitment: () => computeNoteCommitment,
66
67
  computeNullifier: () => computeNullifier,
67
68
  computePathIndices: () => computePathIndices,
68
69
  connectInjectedExtension: () => import_pjs_signer.connectInjectedExtension,
@@ -224,6 +225,27 @@ var SubstrateClient = class _SubstrateClient {
224
225
  _httpUrl;
225
226
  _dynamicBuilder = null;
226
227
  _extDecoder = null;
228
+ _inflightTxCount = 0;
229
+ /**
230
+ * `true` while any submitted transaction is still waiting for finalization.
231
+ * Connection managers use this to defer destroying the client — killing the
232
+ * WS mid-submit rejects the pending tx with "Client destroyed" even though
233
+ * it may still land on-chain.
234
+ *
235
+ * Only covers promise-based submits (`submit`, `submitUnsignedAndWatch`,
236
+ * `signAndSubmit`); observable-based `submitAndWatch` callers are not tracked.
237
+ */
238
+ get hasInflightTx() {
239
+ return this._inflightTxCount > 0;
240
+ }
241
+ async trackTx(p) {
242
+ this._inflightTxCount++;
243
+ try {
244
+ return await p;
245
+ } finally {
246
+ this._inflightTxCount--;
247
+ }
248
+ }
227
249
  /**
228
250
  * Connects to the Orbinum node via WebSocket.
229
251
  * Throws if the node does not respond within `timeoutMs`.
@@ -436,7 +458,7 @@ var SubstrateClient = class _SubstrateClient {
436
458
  * Submits a pre-signed extrinsic (hex string) and waits for finalization.
437
459
  */
438
460
  async submit(signedHex) {
439
- return this._papi.submit(import_polkadot_api.Binary.fromHex(signedHex));
461
+ return this.trackTx(this._papi.submit(import_polkadot_api.Binary.fromHex(signedHex)));
440
462
  }
441
463
  /**
442
464
  * Submits a pre-signed extrinsic and returns an Observable of tx lifecycle events.
@@ -451,14 +473,14 @@ var SubstrateClient = class _SubstrateClient {
451
473
  * The bare tx bytes are produced by `tx.getBareTx()` from polkadot-api.
452
474
  */
453
475
  async submitUnsignedAndWatch(bareTx) {
454
- return this._papi.submit(bareTx);
476
+ return this.trackTx(this._papi.submit(bareTx));
455
477
  }
456
478
  /**
457
479
  * Convenience: wrap raw call bytes and sign+submit in one step.
458
480
  */
459
481
  async signAndSubmit(callData, signer) {
460
482
  const tx = await this.txFromCallData(callData);
461
- return tx.signAndSubmit(signer);
483
+ return this.trackTx(tx.signAndSubmit(signer));
462
484
  }
463
485
  /** Closes the WebSocket connection. */
464
486
  destroy() {
@@ -715,17 +737,46 @@ var EvmClient = class {
715
737
  }
716
738
  return json.result ?? null;
717
739
  }
740
+ /**
741
+ * Fetches a transaction by hash, or `null` when the node no longer knows it
742
+ * (never mined and evicted from the pool). Unlike `request`, a `null`
743
+ * result is a valid answer here, not an error.
744
+ */
745
+ async getTransactionByHash(txHash) {
746
+ const res = await postJsonWithRetry(
747
+ this.rpcUrl,
748
+ JSON.stringify({
749
+ id: 1,
750
+ jsonrpc: "2.0",
751
+ method: "eth_getTransactionByHash",
752
+ params: [txHash]
753
+ })
754
+ );
755
+ if (!res.ok) throw new Error(`EVM HTTP ${res.status}: ${res.statusText}`);
756
+ const json = await res.json();
757
+ if (json.error) {
758
+ throw new Error(`EVM RPC [${json.error.code}]: ${json.error.message}`);
759
+ }
760
+ return json.result ?? null;
761
+ }
718
762
  /**
719
763
  * Polls `eth_getTransactionReceipt` until the transaction is included in a block.
720
764
  *
765
+ * After `timeoutMs`, the tx-pool is consulted: a tx no longer known to the
766
+ * node is reported as dropped (safe to retry), while a tx still in the pool
767
+ * gets an extended grace window (up to 4× `timeoutMs`) before a "still
768
+ * pending" error — it may confirm later, so callers must NOT blindly retry.
769
+ *
721
770
  * @param txHash - The transaction hash to wait for.
722
771
  * @param intervalMs - Polling interval in milliseconds (default: 500).
723
772
  * @param timeoutMs - Maximum time to wait in milliseconds (default: 60_000).
724
773
  * @returns The transaction receipt once mined.
725
- * @throws If the transaction is not mined within `timeoutMs` or if it reverted (`status == 0x0`).
774
+ * @throws If the transaction dropped, is still pending after the grace window, or reverted (`status == 0x0`).
726
775
  */
727
776
  async waitForReceipt(txHash, intervalMs = 500, timeoutMs = 6e4) {
728
- const deadline = Date.now() + timeoutMs;
777
+ const start = Date.now();
778
+ const hardDeadline = start + timeoutMs * 4;
779
+ let deadline = start + timeoutMs;
729
780
  while (Date.now() < deadline) {
730
781
  const receipt = await this.getTransactionReceipt(txHash);
731
782
  if (receipt !== null) {
@@ -736,10 +787,7 @@ var EvmClient = class {
736
787
  if (!revertDetail) {
737
788
  try {
738
789
  const blockParam = receipt["blockNumber"] ?? "latest";
739
- const rawTx = await this.request(
740
- "eth_getTransactionByHash",
741
- [txHash]
742
- ).catch(() => null);
790
+ const rawTx = await this.getTransactionByHash(txHash).catch(() => null);
743
791
  if (rawTx) {
744
792
  const calldata = rawTx["input"] ?? rawTx["data"];
745
793
  if (calldata) {
@@ -762,8 +810,19 @@ var EvmClient = class {
762
810
  return receipt;
763
811
  }
764
812
  await new Promise((resolve) => setTimeout(resolve, intervalMs));
813
+ if (Date.now() >= deadline && Date.now() < hardDeadline) {
814
+ const known = await this.getTransactionByHash(txHash).catch(() => void 0);
815
+ if (known === null) {
816
+ throw new Error(
817
+ `Transaction dropped from the tx pool (not mined within ${Date.now() - start}ms): ${txHash}`
818
+ );
819
+ }
820
+ deadline = Math.min(deadline + timeoutMs, hardDeadline);
821
+ }
765
822
  }
766
- throw new Error(`Transaction not mined within ${timeoutMs}ms: ${txHash}`);
823
+ throw new Error(
824
+ `Transaction still pending after ${Date.now() - start}ms: ${txHash} \u2014 it may still confirm; check the hash on the explorer before retrying`
825
+ );
767
826
  }
768
827
  };
769
828
 
@@ -3367,7 +3426,7 @@ var DEFAULT_HEARTBEAT_TIMEOUT_MS = 4e3;
3367
3426
  var DEFAULT_RECONNECT_BASE_MS = 3e3;
3368
3427
  var DEFAULT_RECONNECT_MAX_MS = 3e4;
3369
3428
  var DEFAULT_STABLE_AFTER_MS = 1e4;
3370
- var OrbinumClientProvider = class {
3429
+ var OrbinumClientProvider = class _OrbinumClientProvider {
3371
3430
  config;
3372
3431
  connectTimeoutMs;
3373
3432
  heartbeatIntervalMs;
@@ -3384,6 +3443,7 @@ var OrbinumClientProvider = class {
3384
3443
  _reconnectTimer = null;
3385
3444
  _stableTimer = null;
3386
3445
  _reconnectAttempt = 0;
3446
+ _probeFailures = 0;
3387
3447
  // ─── Events ─────────────────────────────────────────────────────────────
3388
3448
  _listeners = /* @__PURE__ */ new Set();
3389
3449
  /** Creates a new provider with the given configuration. Does not connect automatically — call `connect()` to initiate. */
@@ -3516,13 +3576,36 @@ var OrbinumClientProvider = class {
3516
3576
  }
3517
3577
  }
3518
3578
  // ─── Heartbeat ──────────────────────────────────────────────────────────
3579
+ /**
3580
+ * Consecutive failed probes required before the client is torn down. A
3581
+ * single missed probe is routine (throttled background tab, node busy
3582
+ * verifying a ZK proof, transient network blip) — destroying the client on
3583
+ * it rejects every in-flight request with "Client destroyed" even though
3584
+ * the tx may still land on-chain.
3585
+ */
3586
+ static PROBE_FAILURE_THRESHOLD = 2;
3587
+ /**
3588
+ * With a tx awaiting finalization, tolerate more missed probes: an unsigned
3589
+ * private_transfer/unshield makes the node CPU-bound on proof verification,
3590
+ * which is exactly when probes time out — tearing down then kills the very
3591
+ * tx being processed.
3592
+ */
3593
+ static PROBE_FAILURE_THRESHOLD_INFLIGHT = 6;
3519
3594
  /** Starts the periodic heartbeat loop. Replaces any existing timer. */
3520
3595
  startHeartbeat() {
3521
3596
  this.stopHeartbeat();
3597
+ this._probeFailures = 0;
3522
3598
  this._heartbeatTimer = setInterval(async () => {
3523
3599
  if (this._status !== "connected" || !this._orbinumClient) return;
3524
3600
  const alive = await this.probe();
3525
- if (!alive && this._status === "connected") {
3601
+ if (this._status !== "connected") return;
3602
+ if (alive) {
3603
+ this._probeFailures = 0;
3604
+ return;
3605
+ }
3606
+ this._probeFailures++;
3607
+ const threshold = this._orbinumClient?.substrate.hasInflightTx ? _OrbinumClientProvider.PROBE_FAILURE_THRESHOLD_INFLIGHT : _OrbinumClientProvider.PROBE_FAILURE_THRESHOLD;
3608
+ if (this._probeFailures >= threshold) {
3526
3609
  this.setStatus("disconnected", "Node is unreachable");
3527
3610
  this.teardownClient();
3528
3611
  this.scheduleReconnect();
@@ -3948,6 +4031,9 @@ var import_poseidon_lite2 = require("poseidon-lite");
3948
4031
  function computeNullifier(commitment, spendingKey) {
3949
4032
  return (0, import_poseidon_lite2.poseidon2)([commitment, spendingKey]);
3950
4033
  }
4034
+ function computeNoteCommitment(value, assetId, ownerPk, blinding) {
4035
+ return (0, import_poseidon_lite2.poseidon4)([value, assetId, ownerPk, blinding]);
4036
+ }
3951
4037
  function tryDecryptNote(commitment, viewingSecretKey, spendingKey, ownOwnerPk = 0n, opts) {
3952
4038
  return tryDecryptNoteVerbose(commitment, viewingSecretKey, spendingKey, ownOwnerPk, opts).note;
3953
4039
  }
@@ -5374,6 +5460,7 @@ var import_polkadot_api4 = require("polkadot-api");
5374
5460
  blindTag,
5375
5461
  buildDummyTransferInput,
5376
5462
  bytesToBigintLE,
5463
+ computeNoteCommitment,
5377
5464
  computeNullifier,
5378
5465
  computePathIndices,
5379
5466
  connectInjectedExtension,
package/dist/index.mjs CHANGED
@@ -90,6 +90,27 @@ var SubstrateClient = class _SubstrateClient {
90
90
  _httpUrl;
91
91
  _dynamicBuilder = null;
92
92
  _extDecoder = null;
93
+ _inflightTxCount = 0;
94
+ /**
95
+ * `true` while any submitted transaction is still waiting for finalization.
96
+ * Connection managers use this to defer destroying the client — killing the
97
+ * WS mid-submit rejects the pending tx with "Client destroyed" even though
98
+ * it may still land on-chain.
99
+ *
100
+ * Only covers promise-based submits (`submit`, `submitUnsignedAndWatch`,
101
+ * `signAndSubmit`); observable-based `submitAndWatch` callers are not tracked.
102
+ */
103
+ get hasInflightTx() {
104
+ return this._inflightTxCount > 0;
105
+ }
106
+ async trackTx(p) {
107
+ this._inflightTxCount++;
108
+ try {
109
+ return await p;
110
+ } finally {
111
+ this._inflightTxCount--;
112
+ }
113
+ }
93
114
  /**
94
115
  * Connects to the Orbinum node via WebSocket.
95
116
  * Throws if the node does not respond within `timeoutMs`.
@@ -302,7 +323,7 @@ var SubstrateClient = class _SubstrateClient {
302
323
  * Submits a pre-signed extrinsic (hex string) and waits for finalization.
303
324
  */
304
325
  async submit(signedHex) {
305
- return this._papi.submit(Binary.fromHex(signedHex));
326
+ return this.trackTx(this._papi.submit(Binary.fromHex(signedHex)));
306
327
  }
307
328
  /**
308
329
  * Submits a pre-signed extrinsic and returns an Observable of tx lifecycle events.
@@ -317,14 +338,14 @@ var SubstrateClient = class _SubstrateClient {
317
338
  * The bare tx bytes are produced by `tx.getBareTx()` from polkadot-api.
318
339
  */
319
340
  async submitUnsignedAndWatch(bareTx) {
320
- return this._papi.submit(bareTx);
341
+ return this.trackTx(this._papi.submit(bareTx));
321
342
  }
322
343
  /**
323
344
  * Convenience: wrap raw call bytes and sign+submit in one step.
324
345
  */
325
346
  async signAndSubmit(callData, signer) {
326
347
  const tx = await this.txFromCallData(callData);
327
- return tx.signAndSubmit(signer);
348
+ return this.trackTx(tx.signAndSubmit(signer));
328
349
  }
329
350
  /** Closes the WebSocket connection. */
330
351
  destroy() {
@@ -581,17 +602,46 @@ var EvmClient = class {
581
602
  }
582
603
  return json.result ?? null;
583
604
  }
605
+ /**
606
+ * Fetches a transaction by hash, or `null` when the node no longer knows it
607
+ * (never mined and evicted from the pool). Unlike `request`, a `null`
608
+ * result is a valid answer here, not an error.
609
+ */
610
+ async getTransactionByHash(txHash) {
611
+ const res = await postJsonWithRetry(
612
+ this.rpcUrl,
613
+ JSON.stringify({
614
+ id: 1,
615
+ jsonrpc: "2.0",
616
+ method: "eth_getTransactionByHash",
617
+ params: [txHash]
618
+ })
619
+ );
620
+ if (!res.ok) throw new Error(`EVM HTTP ${res.status}: ${res.statusText}`);
621
+ const json = await res.json();
622
+ if (json.error) {
623
+ throw new Error(`EVM RPC [${json.error.code}]: ${json.error.message}`);
624
+ }
625
+ return json.result ?? null;
626
+ }
584
627
  /**
585
628
  * Polls `eth_getTransactionReceipt` until the transaction is included in a block.
586
629
  *
630
+ * After `timeoutMs`, the tx-pool is consulted: a tx no longer known to the
631
+ * node is reported as dropped (safe to retry), while a tx still in the pool
632
+ * gets an extended grace window (up to 4× `timeoutMs`) before a "still
633
+ * pending" error — it may confirm later, so callers must NOT blindly retry.
634
+ *
587
635
  * @param txHash - The transaction hash to wait for.
588
636
  * @param intervalMs - Polling interval in milliseconds (default: 500).
589
637
  * @param timeoutMs - Maximum time to wait in milliseconds (default: 60_000).
590
638
  * @returns The transaction receipt once mined.
591
- * @throws If the transaction is not mined within `timeoutMs` or if it reverted (`status == 0x0`).
639
+ * @throws If the transaction dropped, is still pending after the grace window, or reverted (`status == 0x0`).
592
640
  */
593
641
  async waitForReceipt(txHash, intervalMs = 500, timeoutMs = 6e4) {
594
- const deadline = Date.now() + timeoutMs;
642
+ const start = Date.now();
643
+ const hardDeadline = start + timeoutMs * 4;
644
+ let deadline = start + timeoutMs;
595
645
  while (Date.now() < deadline) {
596
646
  const receipt = await this.getTransactionReceipt(txHash);
597
647
  if (receipt !== null) {
@@ -602,10 +652,7 @@ var EvmClient = class {
602
652
  if (!revertDetail) {
603
653
  try {
604
654
  const blockParam = receipt["blockNumber"] ?? "latest";
605
- const rawTx = await this.request(
606
- "eth_getTransactionByHash",
607
- [txHash]
608
- ).catch(() => null);
655
+ const rawTx = await this.getTransactionByHash(txHash).catch(() => null);
609
656
  if (rawTx) {
610
657
  const calldata = rawTx["input"] ?? rawTx["data"];
611
658
  if (calldata) {
@@ -628,8 +675,19 @@ var EvmClient = class {
628
675
  return receipt;
629
676
  }
630
677
  await new Promise((resolve) => setTimeout(resolve, intervalMs));
678
+ if (Date.now() >= deadline && Date.now() < hardDeadline) {
679
+ const known = await this.getTransactionByHash(txHash).catch(() => void 0);
680
+ if (known === null) {
681
+ throw new Error(
682
+ `Transaction dropped from the tx pool (not mined within ${Date.now() - start}ms): ${txHash}`
683
+ );
684
+ }
685
+ deadline = Math.min(deadline + timeoutMs, hardDeadline);
686
+ }
631
687
  }
632
- throw new Error(`Transaction not mined within ${timeoutMs}ms: ${txHash}`);
688
+ throw new Error(
689
+ `Transaction still pending after ${Date.now() - start}ms: ${txHash} \u2014 it may still confirm; check the hash on the explorer before retrying`
690
+ );
633
691
  }
634
692
  };
635
693
 
@@ -3236,7 +3294,7 @@ var DEFAULT_HEARTBEAT_TIMEOUT_MS = 4e3;
3236
3294
  var DEFAULT_RECONNECT_BASE_MS = 3e3;
3237
3295
  var DEFAULT_RECONNECT_MAX_MS = 3e4;
3238
3296
  var DEFAULT_STABLE_AFTER_MS = 1e4;
3239
- var OrbinumClientProvider = class {
3297
+ var OrbinumClientProvider = class _OrbinumClientProvider {
3240
3298
  config;
3241
3299
  connectTimeoutMs;
3242
3300
  heartbeatIntervalMs;
@@ -3253,6 +3311,7 @@ var OrbinumClientProvider = class {
3253
3311
  _reconnectTimer = null;
3254
3312
  _stableTimer = null;
3255
3313
  _reconnectAttempt = 0;
3314
+ _probeFailures = 0;
3256
3315
  // ─── Events ─────────────────────────────────────────────────────────────
3257
3316
  _listeners = /* @__PURE__ */ new Set();
3258
3317
  /** Creates a new provider with the given configuration. Does not connect automatically — call `connect()` to initiate. */
@@ -3385,13 +3444,36 @@ var OrbinumClientProvider = class {
3385
3444
  }
3386
3445
  }
3387
3446
  // ─── Heartbeat ──────────────────────────────────────────────────────────
3447
+ /**
3448
+ * Consecutive failed probes required before the client is torn down. A
3449
+ * single missed probe is routine (throttled background tab, node busy
3450
+ * verifying a ZK proof, transient network blip) — destroying the client on
3451
+ * it rejects every in-flight request with "Client destroyed" even though
3452
+ * the tx may still land on-chain.
3453
+ */
3454
+ static PROBE_FAILURE_THRESHOLD = 2;
3455
+ /**
3456
+ * With a tx awaiting finalization, tolerate more missed probes: an unsigned
3457
+ * private_transfer/unshield makes the node CPU-bound on proof verification,
3458
+ * which is exactly when probes time out — tearing down then kills the very
3459
+ * tx being processed.
3460
+ */
3461
+ static PROBE_FAILURE_THRESHOLD_INFLIGHT = 6;
3388
3462
  /** Starts the periodic heartbeat loop. Replaces any existing timer. */
3389
3463
  startHeartbeat() {
3390
3464
  this.stopHeartbeat();
3465
+ this._probeFailures = 0;
3391
3466
  this._heartbeatTimer = setInterval(async () => {
3392
3467
  if (this._status !== "connected" || !this._orbinumClient) return;
3393
3468
  const alive = await this.probe();
3394
- if (!alive && this._status === "connected") {
3469
+ if (this._status !== "connected") return;
3470
+ if (alive) {
3471
+ this._probeFailures = 0;
3472
+ return;
3473
+ }
3474
+ this._probeFailures++;
3475
+ const threshold = this._orbinumClient?.substrate.hasInflightTx ? _OrbinumClientProvider.PROBE_FAILURE_THRESHOLD_INFLIGHT : _OrbinumClientProvider.PROBE_FAILURE_THRESHOLD;
3476
+ if (this._probeFailures >= threshold) {
3395
3477
  this.setStatus("disconnected", "Node is unreachable");
3396
3478
  this.teardownClient();
3397
3479
  this.scheduleReconnect();
@@ -3817,6 +3899,9 @@ import { poseidon2 as poseidon22, poseidon4 as poseidon42 } from "poseidon-lite"
3817
3899
  function computeNullifier(commitment, spendingKey) {
3818
3900
  return poseidon22([commitment, spendingKey]);
3819
3901
  }
3902
+ function computeNoteCommitment(value, assetId, ownerPk, blinding) {
3903
+ return poseidon42([value, assetId, ownerPk, blinding]);
3904
+ }
3820
3905
  function tryDecryptNote(commitment, viewingSecretKey, spendingKey, ownOwnerPk = 0n, opts) {
3821
3906
  return tryDecryptNoteVerbose(commitment, viewingSecretKey, spendingKey, ownOwnerPk, opts).note;
3822
3907
  }
@@ -5265,6 +5350,7 @@ export {
5265
5350
  blindTag,
5266
5351
  buildDummyTransferInput,
5267
5352
  bytesToBigintLE,
5353
+ computeNoteCommitment,
5268
5354
  computeNullifier,
5269
5355
  computePathIndices,
5270
5356
  connectInjectedExtension,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orbinum/sdk",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "description": "Official TypeScript SDK for Orbinum.",
5
5
  "author": "Orbinum",
6
6
  "license": "MIT",